flask-realtime
Skill2 starsChanged 5 months agoMITView on GitHub
Conventions for a Flask REST API with WebSockets (Flask-SocketIO). Invoke when atlas shows `flask` in pyproject/requirements and any of `flask-socketio`, `eventlet`, `gevent`, `python-socketio`. Covers blueprint structure, SocketIO room patterns, JWT+Flask-Login auth, SQLAlchemy+Alembic migration discipline, Celery/RQ background jobs, pytest fixtures, and the eventlet/gevent/ASGI decision.
In this repository60 other files it gives its agents.
- .claude/CLAUDE.mdCLAUDE.md
- CLAUDE.mdCLAUDE.md
- analyzeSkill
- animation-disciplineSkill
- api-versioningSkill
- autopilotSkill
- browser-e2eSkill
- characterizeSkill
- clarifySkill
- codemodSkill
- constitution-compactSkill
- constitutionSkill
- context-budgetSkill
- creative-webSkill
- db-migrationSkill
- debugSkill
- detect-stackSkill
- dispatch-criteriaSkill
- dreamSkill
- experimentSkill
- fastapiSkill
- flag-cleanupSkill
- flag-rolloutSkill
- framework-detectorSkill
- front-end-designSkill
- grill-meSkill
- handoffSkill
- image-generationSkill
- implementSkill
- initiativeSkill
- instinctSkill
- loopSkill
- nextjsSkill
- observabilitySkill
- okr-alignSkill
- parallel-swarmSkill
- pivotSkill
- planSkill
- pr-bodySkill
- prime-disciplineSkill
- prod-observabilitySkill
- react-nodeSkill
- react-viteSkill
- release-trainSkill
- researchSkill
- reviewSkill
- security-guardSkill
- self-healSkill
- shipSkill
- skill-creatorSkill
- specifySkill
- tailwind-disciplineSkill
- tasksSkill
- tdd-loopSkill
- token-budgetSkill
- typographySkill
- verify-loopSkill
- verifySkill
- wip-checkpointSkill
- <kebab-case-skill-name>Skill
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 21
One worker: when using sticky sessions.
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Flask REST + WebSockets
When to invoke
- Atlas
frameworks.api == "Flask"AND any offlask-socketio,eventlet,gevent,python-socketioinpyproject.toml/requirements.txt. - User mentions Flask + "realtime", "websockets", "Socket.IO", "presence", "live updates".
Key conventions
- Blueprints, not one giant
app.py. One blueprint per bounded context (auth,users,orders). Register in an app factorycreate_app(). No module-levelapp = Flask(__name__). - App factory + extension singletons. Instantiate
db = SQLAlchemy(),socketio = SocketIO(),migrate = Migrate(),jwt = JWTManager()at module top, then.init_app(app)insidecreate_app(). Lets tests build isolated apps. - Flask-SocketIO with
socketio.run(app)in dev, gunicorn + worker class in prod.- eventlet (
gunicorn -k eventlet -w 1) — mature, monkey-patches stdlib, the default for Flask-SocketIO. - gevent +
gevent-websocket— similar; pick if you already use gevent elsewhere. - ASGI via
asgiref.WsgiToAsgi— only when migrating to Quart/FastAPI; not ideal for SocketIO. - One worker when using sticky sessions; N workers + Redis message queue when scaling (
SocketIO(message_queue='redis://...')).
- eventlet (
- Auth split: Flask-Login (server-rendered admin views, cookie session) and Flask-JWT-Extended (REST API for the SPA). Don't mix on the same route. WebSocket auth: read the JWT from the
authpayload onconnect, NOT the query string. - SocketIO rooms = your authorization boundary. A user joins
room=user:<id>on connect. Broadcasts target rooms, never global. Noemit(..., broadcast=True)without a room filter. - SQLAlchemy + Alembic migrations are expand/contract. See
.claude/skills/db-migration/SKILL.md. Every migration has a downgrade unless data loss is documented in an ADR. Generate withflask db migrate -m "..."then ALWAYS hand-edit — autogen misses indexes, enums, server defaults. - Background jobs: Celery (broker + result backend, sturdy) for heavy + retried work, RQ (Redis-only, simple) for light. Don't do "background" work in the request thread — Flask-SocketIO already steals workers.
- Tests: pytest +
factory_boy+ Flask test client +pytest-flask+pytest-socketio. App-factory enables@pytest.fixturereturning an isolated app per test. Use a transactional rollback fixture for the DB.
Canonical structure
src/
myapp/
__init__.py # create_app() factory
extensions.py # db, socketio, migrate, jwt singletons
config.py # Config / TestConfig / ProdConfig
blueprints/
auth/{__init__.py, routes.py, schemas.py, services.py}
users/{...}
orders/{...}
realtime/
__init__.py # register_socketio_handlers(socketio)
events.py # @socketio.on('...') handlers
rooms.py # room name helpers
models/ # SQLAlchemy declarative
tasks/ # Celery tasks
cli.py # flask custom commands
migrations/ # alembic
tests/
conftest.py # app, client, db, socketio_client fixtures
factories.py
test_auth.py
test_realtime.py
pyproject.toml
gunicorn.conf.pyCommon pitfalls
- Forgetting
eventlet.monkey_patch()BEFORE any other import. Causespsycopg2/requeststo block the event loop. Put it at the very top ofwsgi.py(and only there). - JWT in WebSocket query string. Ends up in proxy access logs. Pass via the SocketIO
authdict on the client:io({ auth: { token } })→ read in@socketio.on('connect'). - Broadcasting without a room.
emit('update', data, broadcast=True)leaks across tenants. Alwaysroom=...orto=.... - Autogenerated Alembic migrations shipped untouched. Misses: enum changes, index drops, server defaults, server-side check constraints. Diff the migration, run on a prod-shaped DB, then ship.
- Sync DB calls inside SocketIO event handlers. Under eventlet, SQLAlchemy must use a driver that yields (psycopg2 monkey-patched is fine; cx_Oracle is not). Long queries block the worker.
- N+1 in JSON serializers.
User.query.all()then[u.orders for u in users]issues N queries. Usejoinedload(User.orders)or marshmallow withselect_related-style nesting.
References
- Flask app factory: https://flask.palletsprojects.com/en/latest/patterns/appfactories/
- Flask-SocketIO: https://flask-socketio.readthedocs.io
- Flask-JWT-Extended: https://flask-jwt-extended.readthedocs.io
- Alembic ops: https://alembic.sqlalchemy.org/en/latest/ops.html
- Celery + Flask: https://flask.palletsprojects.com/en/latest/patterns/celery/
- pytest-socketio: https://python-socketio.readthedocs.io/en/latest/server.html#testing
Hello world (room-scoped event)
# src/myapp/realtime/events.py
from flask import current_app
from flask_jwt_extended import decode_token
from ..extensions import socketio
@socketio.on('connect')
def on_connect(auth):
if not auth or 'token' not in auth:
return False # reject handshake
try:
claims = decode_token(auth['token'])
except Exception:
return False
user_id = claims['sub']
socketio.server.enter_room(request.sid, f'user:{user_id}')
@socketio.on('subscribe_order')
def on_subscribe(payload):
order_id = payload['order_id']
# ... authorize: does current user own this order?
socketio.server.enter_room(request.sid, f'order:{order_id}')
# elsewhere, when an order changes:
socketio.emit('order.updated', order.to_dict(), to=f'order:{order.id}')Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

