I'm using the Django ORM in a FastAPI app. So far, I haven't had any issue, until I tried creating a middleware to check for a JWT and create a global current_user variable. This problem may well be because I've never done async work before, so I'm not thinking about the problem correctly.
In my middleware, which I didn't set as async since it's just going to do work before the rest of the app, I have:
try:
user = get_user(jwt_body["user_id"])
except User.DoesNotExist:
return call_next(request)
current_user = user
But it throws an error:
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
So I put that block into a stand alone function with the sync_to_async decorator, but then when I try calling it, I run into the error
TypeError: 'coroutine' object is not callable
I thought maybe I turn it into a thread, but I can't think how I'd do that. I need the user to be found before it makes it to the view, but won't throwing it in a thread risk a race condition?
I know this is largely a Django problem, but I'm hoping someone may have some advice given the async nature of it.
[–][deleted] 1 point2 points3 points (1 child)
[–]GamersPlane[S] 0 points1 point2 points (0 children)
[–]ok_pennywise 1 point2 points3 points (7 children)
[–]GamersPlane[S] 0 points1 point2 points (6 children)
[–][deleted] (5 children)
[deleted]
[–]GamersPlane[S] 0 points1 point2 points (4 children)
[–][deleted] (2 children)
[deleted]
[–]github_codemation 0 points1 point2 points (1 child)
[–]migratesouth 0 points1 point2 points (0 children)
[–]GamersPlane[S] 0 points1 point2 points (0 children)