Server websocket conflicts with middleware stack #7396
Unanswered
al-dpopowich
asked this question in
Q&A
Replies: 1 comment 2 replies
-
Middlewares are just functions that call the next function in the list. So, the simple approach would be to do:
You could easily make that into some kind of decorator or similar:
|
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have a mature aiohttp server with the following middlewares defined:
The
db_trx
middleware does this:For those familiar with it, this is async SQLAlchemy (2.x). The handler is run within the context manager and if it succeeds the transaction is committed. If there's an exception, the trx is rolled back. This works beautifully across my application. Run any SQL inside my requests and I never need worry about committing vs rolling back; it's handled automatically.
Now, my question regarding websockets...
We want to add websockets to our app to handle "live" communication with the clients. Think chat or dashboard updates.
The stock websocket implementation as described in the Quickstart guide doesn't return. (Well, not until the connection is closed.) This is in conflict with my middleware stack which is designed for per-request common tasks. My websocket connection needs to "skip" the middleware stack and do its own version of it per-message. For example, I may want/need this:
All of which would be in conflict with my common application middlewares.
Surely, per-request middleware not being compatible with long-lived websocket connections can't be a new discovery, so what I think I'm asking is: does anyone have a recipe for skipping the middlewares for a given route?
All I've come up with seems un-aiohttp-ic:
Essentially, it requires one to munge the stack within the stack. What would be ideal is a way to customize the middlewares stack based on the route, with a default middlewares stack if there's no match against the custom definitions.
Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions