channels: Database query in custom authentication cause SynchronousOnlyOperation Error
In Custom Authentication section of documentation, there is database query in __call__
method:
def __call__(self, scope):
...
user = User.objects.get(id=int(scope["query_string"]))
...
It’s OK with Django 2, but in Django 3 it cause django.core.exceptions.SynchronousOnlyOperation
error.
please update docs, and explain how to use database query in Custom Authentications.
Thanks.
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 26
- Comments: 19 (8 by maintainers)
@jkupka You can use below code, Until docs be updated.
Hey, thanks for the work done thus far! Adapted @AmirMahmood solution for django rest framework’s token auth based on the old impl. See below:
Another way, based on
AuthMiddleware
:@avallete, According to the documentation
@database_sync_to_async
decorator cleans up database connections on exit. You can check this in the@database_sync_to_async
source code.@avallete, @SerhiyRomanov, @maxcmoi89 My pleasure. I created a PR for this issue. (#1442)
@frennkie, yes. it’s special case. I mentioned
AuthMiddlewareStack
for general scenarios, and for using session base authentication you must use a combination of ID, Token, etc … to login user and set session id. but it seems you don’t need login system in your case.@daxaxelrod I would also like to use this from the browser - but Javascript does not seem to have a way to use Websockets with a custom
Authorization
header. Therefore I added an option to pass the Token in aCookie
: https://gist.github.com/frennkie/e79c52d10a8ed0c7af81226a559eada2@daxaxelrod What happens if there is no User found with the given Token? I got an exception (
django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.
) and had to replaceexcept Token.DoesNotExist:
withexcept get_user_model().DoesNotExist: