Add route hooks #3
Hi @florimondmanca ! Bocadillo looks like a great project and I've already started using it in two of my projects!
A few use cases I could think of:
The hook doesn't have to always be async, but it can be allowed to be using
What do you think?
Hi @alin23, very good points about async support for these hooks (and middleware!). As it is now, hooks won't allow to read the request body because it can only be through
The support of both async and sync functions becomes a recurring problem in the code base, I'd also like to find a more generic (yet efficient) way of dealing with it.
As for your point concerning database calls — I've just added #4 about support for databases and an ORM within Bocadillo. You seem to have valuable input concerning databases in an async context, so feel free to check out the issue. :-)
I'll mark these as needing revision and come back to it soon.
Oh man, finally an ORM that uses
Yes, #4 would also be a great addition if tortoise would be considered instead of orator. A sync ORM is almost impossible to use in the context of an async/single-thread framework because every database call would halt every request handling until the call finishes. Of course, the db calls can be made in separate threads but as you probably know, Python doesn't have real parallelization when it comes to threads.
Anyway, the db point was just one of many examples. I could think of others like caching with
I forked your repo and made some preliminary changes for the hooks here: alin23@66b3bb0#diff-17d3d0ba7be943aecedec66175af840c
import asyncio from starlette.concurrency import run_in_threadpool async def ensure_async(func, *args, **kwargs): if asyncio.iscoroutinefunction(func): return await func(*args, **kwargs) return await run_in_threadpool(func, *args, **kwargs) # Example usage await ensure_async(self.hooks[BEFORE], request, response, view, kwargs)
From what I see,
What do you think? Can we use this to land this PR? It's quite an important feature, I've already started using async hooks and middleware as it seems to be the best solution for most server needs.
@alin23 Thanks for the tip about the reusable sync -> async converter :) I used it to add support for async hooks. Async middleware will be implemented in a future PR (this is a separate issue).
Note that, although it was already written that way in the docs, I removed the
If you have any comments, feel free. :) I'll probably merge this tonight.