Django jwt channels cannot verify - django

I use djangorestframework-simplejwt.
I have two Django Projects sharing the same database.
One is django-restframework
One is django-channels
django-restframework login will get JWT
I cannot verify successfully in django-channels
I wrote the test function
restframework verify ok
class Test(APIView):
def get(self, request):
try:
token = UntypedToken(
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.???.Z22plhyGEZW9IBZLzICu2mWTkuMrblYQhvUGoUtpKd0')
print(token, 'token') # output: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.???.Z22plhyGEZW9IBZLzICu2mWTkuMrblYQhvUGoUtpKd0
except (InvalidToken, TokenError):
print('InvalidToken, TokenError')
return Response(status=status.HTTP_200_OK)
channels verify error
#database_sync_to_async
def test_get_user():
try:
token = UntypedToken(
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.???.Z22plhyGEZW9IBZLzICu2mWTkuMrblYQhvUGoUtpKd0')
print(token, 'token')
except (InvalidToken, TokenError) as e:
print('InvalidToken, TokenError', e) # output InvalidToken, TokenError Token is invalid or expired
Can't verify JWT like this?
traceback
Exception inside application: Token is invalid or expired
Traceback (most recent call last):
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/rest_framework_simplejwt/backends.py", line 99, in decode
'verify_signature': verify,
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/jwt/api_jwt.py", line 119, in decode
decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/jwt/api_jwt.py", line 95, in decode_complete
**kwargs,
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/jwt/api_jws.py", line 152, in decode_complete
self._verify_signature(signing_input, header, signature, key, algorithms)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/jwt/api_jws.py", line 239, in _verify_signature
raise InvalidSignatureError("Signature verification failed")
jwt.exceptions.InvalidSignatureError: Signature verification failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/rest_framework_simplejwt/tokens.py", line 43, in __init__
self.payload = token_backend.decode(token, verify=verify)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/rest_framework_simplejwt/backends.py", line 105, in decode
raise TokenBackendError(_('Token is invalid or expired'))
rest_framework_simplejwt.exceptions.TokenBackendError: Token is invalid or expired
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/staticfiles.py", line 44, in __call__
return await self.application(scope, receive, send)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/routing.py", line 71, in __call__
return await application(scope, receive, send)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/sessions.py", line 47, in __call__
return await self.inner(dict(scope, cookies=cookies), receive, send)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/sessions.py", line 263, in __call__
return await self.inner(wrapper.scope, receive, wrapper.send)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/auth.py", line 185, in __call__
return await super().__call__(scope, receive, send)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/middleware.py", line 26, in __call__
return await self.inner(scope, receive, send)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/routing.py", line 160, in __call__
send,
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/consumer.py", line 94, in app
return await consumer(scope, receive, send)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/consumer.py", line 59, in __call__
[receive, self.channel_receive], self.dispatch
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/utils.py", line 51, in await_many_dispatch
await dispatch(result)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/consumer.py", line 73, in dispatch
await handler(message)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/generic/websocket.py", line 173, in websocket_connect
await self.connect()
File "/home/user/Daniel/Python/GitLab/django-signalserver/WebSocket/consumers.py", line 147, in connect
await test_get_user()
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/asgiref/sync.py", line 444, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "/usr/lib/python3.7/asyncio/tasks.py", line 414, in wait_for
return await fut
File "/usr/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/channels/db.py", line 13, in thread_handler
return super().thread_handler(loop, *args, **kwargs)
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/asgiref/sync.py", line 486, in thread_handler
return func(*args, **kwargs)
File "/home/user/Daniel/Python/GitLab/django-signalserver/WebSocket/consumers.py", line 127, in test_get_user
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.???.Z22plhyGEZW9IBZLzICu2mWTkuMrblYQhvUGoUtpKd0')
File "/home/user/Daniel/Python/GitLab/django-signalserver/venv/lib/python3.7/site-packages/rest_framework_simplejwt/tokens.py", line 45, in __init__
raise TokenError(_('Token is invalid or expired'))
rest_framework_simplejwt.exceptions.TokenError: Token is invalid or expired

Because i don't know how jwt verifies
Now I found that the verification method is SECRET_KEY in settings.py
As long as different projects use the same SECRET_KEY.
There is no problem with JWT authentication.

Related

Djoser reset password email with Celery

I want to send reset password email using Celery. I try to override the reset_password method of the class djoser.views.UserViewSet:
class CustomUserViewSet(UserViewSet):
#action(["post"], detail=False)
def reset_password(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.get_user()
if user:
send_reset_password_email.delay(
self.request,
{'user': user},
[get_user_email(user)]
)
return Response(status=status.HTTP_200_OK)
But I get an error:
Traceback (most recent call last):
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 39, in _reraise_errors
yield
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 210, in dumps
payload = encoder(data)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\utils\json.py", line 68, in dumps
return _dumps(s, cls=cls or _default_encoder,
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\utils\json.py", line 58, in default
return super().default(o)
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Request is not JSON serializable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Dev\rich-peach\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Dev\rich-peach\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Dev\rich-peach\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Dev\rich-peach\backend\api\views.py", line 51, in reset_password
send_reset_password_email.delay(
File "C:\Dev\rich-peach\venv\lib\site-packages\celery\app\task.py", line 425, in delay
return self.apply_async(args, kwargs)
File "C:\Dev\rich-peach\venv\lib\site-packages\celery\app\task.py", line 575, in apply_async
return app.send_task(
File "C:\Dev\rich-peach\venv\lib\site-packages\celery\app\base.py", line 788, in send_task
amqp.send_task_message(P, name, message, **options)
File "C:\Dev\rich-peach\venv\lib\site-packages\celery\app\amqp.py", line 510, in send_task_message
ret = producer.publish(
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\messaging.py", line 166, in publish
body, content_type, content_encoding = self._prepare(
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\messaging.py", line 254, in _prepare
body) = dumps(body, serializer=serializer)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 209, in dumps
with _reraise_errors(EncodeError):
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\contextlib.py", line 153, in __exit__
self.gen.throw(typ, value, traceback)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 43, in _reraise_errors
reraise(wrapper, wrapper(exc), sys.exc_info()[2])
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\exceptions.py", line 21, in reraise
raise value.with_traceback(tb)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 39, in _reraise_errors
yield
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 210, in dumps
payload = encoder(data)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\utils\json.py", line 68, in dumps
return _dumps(s, cls=cls or _default_encoder,
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\utils\json.py", line 58, in default
return super().default(o)
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
kombu.exceptions.EncodeError: Object of type Request is not JSON serializable
Celery task:
#app.task(bind=True, default_retry_delay=5 * 60)
def send_reset_password_email(self, request, context, email):
try:
PasswordResetEmail(request, context).send(email)
except Exception as exc:
raise self.retry(exc=exc, countdown=60)
What I've already tried:
I tried to change the serializer for the task to 'pickle':
#app.task(bind=True, default_retry_delay=5 * 60, serializer='pickle')
But I get a new error:
Traceback (most recent call last):
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 39, in _reraise_errors
yield
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 210, in dumps
payload = encoder(data)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 334, in pickle_dumps
return dumper(obj, protocol=pickle_protocol)
TypeError: cannot pickle '_io.BufferedReader' object
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Dev\rich-peach\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Dev\rich-peach\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Dev\rich-peach\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Dev\rich-peach\backend\api\views.py", line 51, in reset_password
send_reset_password_email.delay(
File "C:\Dev\rich-peach\venv\lib\site-packages\celery\app\task.py", line 425, in delay
return self.apply_async(args, kwargs)
File "C:\Dev\rich-peach\venv\lib\site-packages\celery\app\task.py", line 575, in apply_async
return app.send_task(
File "C:\Dev\rich-peach\venv\lib\site-packages\celery\app\base.py", line 788, in send_task
amqp.send_task_message(P, name, message, **options)
File "C:\Dev\rich-peach\venv\lib\site-packages\celery\app\amqp.py", line 510, in send_task_message
ret = producer.publish(
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\messaging.py", line 166, in publish
body, content_type, content_encoding = self._prepare(
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\messaging.py", line 254, in _prepare
body) = dumps(body, serializer=serializer)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 209, in dumps
with _reraise_errors(EncodeError):
File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\contextlib.py", line 153, in __exit__
self.gen.throw(typ, value, traceback)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 43, in _reraise_errors
reraise(wrapper, wrapper(exc), sys.exc_info()[2])
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\exceptions.py", line 21, in reraise
raise value.with_traceback(tb)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 39, in _reraise_errors
yield
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 210, in dumps
payload = encoder(data)
File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 334, in pickle_dumps
return dumper(obj, protocol=pickle_protocol)
kombu.exceptions.EncodeError: cannot pickle '_io.BufferedReader' object
How can I solve this problem?
Or how else can I do it?
Problem solved!
Instead of request, I pass the necessary fields to context, and instead of user - user.id:
#action(['post'], detail=False)
def reset_password(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.get_user()
if user:
send_reset_password_email.delay(
{
'user_id': user.id,
'domain': request.get_host(),
'protocol': 'https' if request.is_secure() else 'http',
'site_name': request.get_host()
},
[get_user_email(user)]
)
return Response(status=status.HTTP_200_OK)
This works because if you don't send a request to Password Reset E-mail, Djoser searches for the necessary fields in context:
class BaseEmailMessage(mail.EmailMultiAlternatives, ContextMixin):
def get_context_data(self, **kwargs):
ctx = super(BaseEmailMessage, self).get_context_data(**kwargs)
context = dict(ctx, **self.context)
if self.request:
site = get_current_site(self.request)
domain = context.get('domain') or (
getattr(settings, 'DOMAIN', '') or site.domain
)
protocol = context.get('protocol') or (
'https' if self.request.is_secure() else 'http'
)
site_name = context.get('site_name') or (
getattr(settings, 'SITE_NAME', '') or site.name
)
user = context.get('user') or self.request.user
else:
domain = context.get('domain') or getattr(settings, 'DOMAIN', '')
protocol = context.get('protocol') or 'http'
site_name = context.get('site_name') or getattr(
settings, 'SITE_NAME', ''
)
user = context.get('user')
context.update({
'domain': domain,
'protocol': protocol,
'site_name': site_name,
'user': user
})
return context
And in the task, I get the user by id, which I passed to context:
#app.task(bind=True, default_retry_delay=5 * 60)
def send_reset_password_email(self, context, email):
try:
context['user'] = CustomUser.objects.get(id=context.get('user_id'))
PasswordResetEmail(context=context).send(email)
except Exception as exc:
raise self.retry(exc=exc, countdown=60)

I am only passing one arguement but it is showing two were given

My code-:
I have tried to resolve the error but unable to get as the libraries are predefined and iam just calling the function of it.
It was running file earlier but due to some update in torch and torchvision might also be causing it.
import easyocr
import numpy as np
import cv2
def read_img(file):
'''
Function used to read content of image using Easyocr and return
the content as text.
'''
reader = easyocr.Reader(['en']) #getting English language model
new = cv2.imread(file) #for loading the image to new from file
results = reader.readtext(np.array(new)) #extracted text by ocr is stored in results
text=''
for result in results: #loop to concatenate all the text to single string
text += result[1] + ' '
return text
Error which I am facing after running it :-
Traceback (most recent call last):
File "g:\restate\env\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 369, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "g:\restate\env\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 59, in __call__
return await self.app(scope, receive, send)
File "g:\restate\env\lib\site-packages\fastapi\applications.py", line 199, in __call__
await super().__call__(scope, receive, send)
File "g:\restate\env\lib\site-packages\starlette\applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "g:\restate\env\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__
raise exc from None
File "g:\restate\env\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "g:\restate\env\lib\site-packages\starlette\exceptions.py", line 82, in __call__
raise exc from None
File "g:\restate\env\lib\site-packages\starlette\exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "g:\restate\env\lib\site-packages\starlette\routing.py", line 580, in __call__
await route.handle(scope, receive, send)
File "g:\restate\env\lib\site-packages\starlette\routing.py", line 241, in handle
await self.app(scope, receive, send)
File "g:\restate\env\lib\site-packages\starlette\routing.py", line 52, in app
response = await func(request)
File "g:\restate\env\lib\site-packages\fastapi\routing.py", line 214, in app
raw_response = await run_endpoint_function(
File "g:\restate\env\lib\site-packages\fastapi\routing.py", line 151, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "g:\restate\env\lib\site-packages\starlette\concurrency.py", line 40, in run_in_threadpool
return await loop.run_in_executor(None, func, *args)
File "C:\Users\vg_15\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\thread.py", line 52, in run
result = self.fn(*self.args, **self.kwargs)
File "G:\restate\Api\.\main.py", line 21, in extract_text
text = prediction.read_img(temp_file)
File "G:\restate\Api\.\prediction.py", line 15, in read_img
results = reader.readtext(np.array(new).astype('float32')) #extracted text by ocr is stored in results
File "g:\restate\env\lib\site-packages\easyocr\easyocr.py", line 383, in readtext
result = self.recognize(img_cv_grey, horizontal_list, free_list,\
File "g:\restate\env\lib\site-packages\easyocr\easyocr.py", line 319, in recognize
result0 = get_text(self.character, imgH, int(max_width), self.recognizer, self.converter, image_list,\
File "g:\restate\env\lib\site-packages\easyocr\recognition.py", line 206, in get_text
result1 = recognizer_predict(recognizer, converter, test_loader,batch_max_length,\
File "g:\restate\env\lib\site-packages\easyocr\recognition.py", line 104, in recognizer_predict
for image_tensors in test_loader:
File "g:\restate\env\lib\site-packages\torch\utils\data\dataloader.py", line 521, in __next__
data = self._next_data()
File "g:\restate\env\lib\site-packages\torch\utils\data\dataloader.py", line 561, in _next_data
data = self._dataset_fetcher.fetch(index) # may raise StopIteration
File "g:\restate\env\lib\site-packages\torch\utils\data\_utils\fetch.py", line 47, in fetch
return self.collate_fn(data)
File "g:\restate\env\lib\site-packages\easyocr\recognition.py", line 94, in __call__
resized_images.append(transform(resized_image))
File "g:\restate\env\lib\site-packages\easyocr\recognition.py", line 39, in __call__
img = self.toTensor(img)
File "g:\restate\env\lib\site-packages\torchvision\transforms\transforms.py", line 97, in __call__
return F.to_tensor(pic)
File "g:\restate\env\lib\site-packages\torchvision\transforms\functional.py", line 129, in to_tensor
np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True)
TypeError: __array__() takes 1 positional argument but 2 were given
I have tried to resolve the error but unable to get as the libraries are predefined and iam just calling the function of it.
It was running file earlier but due to some update in torch and torchvision might also be causing it.

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async

This is my asgi.py:
"""
ASGI config for VirtualLab_Server project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/asgi/
"""
import os
import django
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'VirtualLab_Server.settings')
django.setup()
application = get_asgi_application()
Error message:
WebSocket HANDSHAKING
/tunnelws/ticket/0fa9dd05-0d91-4baa-923e-05f6af6f55a0/
[127.0.0.1:56637]
Exception inside application: You cannot call this from an async context - use a thread or sync_to_async.
Traceback (most recent call last):
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\related_descriptors.py",
line 173, in __get__
rel_obj = self.field.get_cached_value(instance)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\mixins.py",
line 15, in get_cached_value
return instance._state.fields_cache[cache_name]
KeyError: 'user'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\staticfiles.py",
line 44, in __call__
return await self.application(scope, receive, send)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py",
line 71, in __call__
return await application(scope, receive, send)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py",
line 47, in __call__
return await self.inner(dict(scope, cookies=cookies), receive, send)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py",
line 254, in __call__
return await self.inner(wrapper.scope, receive, wrapper.send)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\auth.py",
line 181, in __call__
return await super().__call__(scope, receive, send)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\middleware.py",
line 26, in __call__
return await self.inner(scope, receive, send)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py",
line 150, in __call__
return await application(
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\consumer.py",
line 94, in app
return await consumer(scope, receive, send)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\consumer.py",
line 62, in __call__
await await_many_dispatch([receive], self.dispatch)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\utils.py",
line 51, in await_many_dispatch
await dispatch(result)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\consumer.py",
line 73, in dispatch
await handler(message)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\generic\websocket.py",
line 175, in websocket_connect
await self.connect()
File "E:\VirtualLab\VirtualLab\VirtualLab_Server\VirtualLab_Server\guacdproxy\consumer.py",
line 42, in connect
if ticket.user != self.scope['user']:
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\related_descriptors.py",
line 187, in __get__
rel_obj = self.get_object(instance)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\fields\related_descriptors.py",
line 154, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\query.py",
line 431, in get
num = len(clone)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\query.py",
line 262, in __len__
self._fetch_all()
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\query.py",
line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\query.py",
line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch,
chunk_size=self.chunk_size)
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\db\models\sql\compiler.py",
line 1167, in execute_sql
cursor = self.connection.cursor()
File "C:\Users\MarianPC\AppData\Local\Programs\Python\Python39\lib\site-packages\django-3.2b1-py3.9.egg\django\utils\asyncio.py",
line 24, in inner
raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
this is my routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from .guacdproxy import GuacamoleConsumer
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter([
# path('tunnelws/ticket/<uuid:ticket>/', GuacamoleConsumer),
path('tunnelws/ticket/<uuid:ticket>/', GuacamoleConsumer.as_asgi()),
])
),
})

Using LoginRequiredMixin with async views?

I'm using Python 3.7, Django 3.1.7, social-auth-app-django 3.1.0.
I've just started playing with async views. I can't get them to play nice with LoginRequiredMixin. I've got this trivial view:
class TestView(LoginRequiredMixin, View):
#classonlymethod
def as_view(cls, **initkwargs):
view = super().as_view(**initkwargs)
view._is_coroutine = asyncio.coroutines._is_coroutine
return view
async def get(self, request):
return render(request, 'spi/test.jinja', {})
When I run this test:
class TestViewTest(ViewTestCase):
def test_get(self):
client = Client()
response = client.get('/spi/test')
self.assertEqual(response.status_code, 200)
It fails with an awe-inspiring stack dump (below), the gist of which is:
TypeError: object HttpResponseRedirect can't be used in 'await' expression
which I assume is due to the OAuth flow being run. If I leave out the LoginRequiredMixin, the test passes.
--- Logging error ---
Traceback (most recent call last):
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/asgiref/sync.py", line 147, in __call__
return call_result.result()
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/concurrent/futures/_base.py", line 425, in result
return self.__get_result()
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result
raise self._exception
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/asgiref/sync.py", line 212, in main_wrap
result = await self.awaitable(*args, **kwargs)
TypeError: object HttpResponseRedirect can't be used in 'await' expression
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/logging/handlers.py", line 630, in emit
s = self.makePickle(record)
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/logging/handlers.py", line 602, in makePickle
s = pickle.dumps(d, 1)
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/copyreg.py", line 65, in _reduce_ex
raise TypeError("can't pickle %s objects" % base.__name__)
TypeError: can't pickle BytesIO objects
Call stack:
File "/data/project/spi-tools-dev/www/python/src/manage.py", line 25, in <module>
main()
File "/data/project/spi-tools-dev/www/python/src/manage.py", line 21, in main
execute_from_command_line(sys.argv)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv
super().run_from_argv(argv)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 53, in handle
failures = test_runner.run_tests(test_labels)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/runner.py", line 699, in run_tests
result = self.run_suite(suite)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/runner.py", line 641, in run_suite
return runner.run(suite)
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/unittest/runner.py", line 176, in run
test(result)
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/unittest/suite.py", line 84, in __call__
return self.run(*args, **kwds)
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/unittest/suite.py", line 122, in run
test(result)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/testcases.py", line 243, in __call__
self._setup_and_call(result)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/testcases.py", line 279, in _setup_and_call
super().__call__(result)
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/unittest/case.py", line 663, in __call__
return self.run(*args, **kwds)
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/unittest/case.py", line 615, in run
testMethod()
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/src/spi/test_views.py", line 231, in test_get
response = client.get('/spi/test')
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 739, in get
response = super().get(path, data=data, secure=secure, **extra)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 395, in get
**extra,
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 470, in generic
return self.request(**r)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 711, in request
response = self.handler(environ)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 142, in __call__
response = self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 130, in get_response
response = self._middleware_chain(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/deprecation.py", line 114, in __call__
response = response or self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/debug_toolbar/middleware.py", line 52, in __call__
return self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/deprecation.py", line 114, in __call__
response = response or self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/deprecation.py", line 114, in __call__
response = response or self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/deprecation.py", line 114, in __call__
response = response or self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/deprecation.py", line 114, in __call__
response = response or self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/deprecation.py", line 114, in __call__
response = response or self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/deprecation.py", line 114, in __call__
response = response or self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/deprecation.py", line 114, in __call__
response = response or self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/deprecation.py", line 114, in __call__
response = response or self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/src/tools_app/middleware.py", line 26, in __call__
return self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/src/tools_app/middleware.py", line 11, in __call__
return self.get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 108, in response_for_exception
exc_info=sys.exc_info(),
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/utils/log.py", line 230, in log_response
exc_info=exc_info,
Message: '%s: %s'
Arguments: ('Internal Server Error', '/spi/test')
E
======================================================================
ERROR: test_get (spi.test_views.TestViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/src/spi/test_views.py", line 231, in test_get
response = client.get('/spi/test')
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 739, in get
response = super().get(path, data=data, secure=secure, **extra)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 395, in get
**extra,
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 470, in generic
return self.request(**r)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 716, in request
self.check_exception(response)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/test/client.py", line 577, in check_exception
raise exc_value
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/asgiref/sync.py", line 147, in __call__
return call_result.result()
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/concurrent/futures/_base.py", line 425, in result
return self.__get_result()
File "/data/project/spi-tools-dev/python-distros/Python-3.7.3-install/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result
raise self._exception
File "/mnt/nfs/labstore-secondary-tools-project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/asgiref/sync.py", line 212, in main_wrap
result = await self.awaitable(*args, **kwargs)
TypeError: object HttpResponseRedirect can't be used in 'await' expression
----------------------------------------------------------------------
Ran 1 test in 0.274s
FAILED (errors=1)
Destroying test database for alias 'default'...
Well, it turns out the problem is simply that LoginRequiredMixin isn't async-capable yet. The work around is to implement the gist of LoginRequiredMixin in my view code. The supplied implementation of LoginRequiredMixin is complicated, but most of it is dealing with the general case. Stripping it down to the essential part that fits my use case, I ended up with:
from asgiref.sync import sync_to_async
from django.contrib.auth.views import redirect_to_login
class TestView(View):
#classonlymethod
def as_view(cls, **initkwargs):
view = super().as_view(**initkwargs)
view._is_coroutine = asyncio.coroutines._is_coroutine
return view
async def get(self, request):
if not await sync_to_async(lambda: request.user.is_authenticated)():
return redirect_to_login(self.request.get_full_path())
return render(request, 'spi/test.jinja', {})

Error in AsyncConsumer in Django channels

I used a tutorial for creating a video chat app. But when i run the code it gives me error and it's not so clear to know what is exactly making the problem.
Error:
WebSocket CONNECT /ws/videochat/ [127.0.0.1:38466]
Exception inside application: You cannot call this from an async context - use a thread or sync_to_async.
Traceback (most recent call last):
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 172, in __get__
rel_obj = self.field.get_cached_value(instance)
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value
return instance._state.fields_cache[cache_name]
KeyError: 'callee'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__
return await self.inner(receive, self.send)
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__
return await self.inner(receive, self.send)
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call
await inner_instance(receive, send)
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__
[receive, self.channel_receive], self.dispatch
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch
await dispatch(result)
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch
await handler(message)
File "/home/nimda/Desktop/videotest/vcp/chat/consumers.py", line 156, in websocket_receive
f"videochat_{videothread.callee.id}",
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 186, in __get__
rel_obj = self.get_object(instance)
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 153, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/query.py", line 411, in get
num = len(clone)
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/query.py", line 258, in __len__
self._fetch_all()
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/query.py", line 1261, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/query.py", line 57, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1149, in execute_sql
cursor = self.connection.cursor()
File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/utils/asyncio.py", line 24, in inner
raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
WebSocket DISCONNECT /ws/videochat/ [127.0.0.1:38392]
consumer.py
The codes are in a pastebin because here gives error for a lot of code:
Show code
How can I solve this? and I should say that the tutorial was okay and that coder made it run.