Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interface asgi error with django #80

Closed
Hisham-Pak opened this issue May 27, 2023 · 4 comments
Closed

Interface asgi error with django #80

Hisham-Pak opened this issue May 27, 2023 · 4 comments
Labels
bug Something isn't working
Milestone

Comments

@Hisham-Pak
Copy link

Great project, was trying to run with django got some error

logs
    
myproj_local_django  | Running migrations:
myproj_local_django  |   No migrations to apply.
myproj_local_django  | [INFO] Starting granian
myproj_local_django  | [INFO] Listening at: 0.0.0.0:8000
myproj_local_django  | [INFO] Spawning worker-1 with pid: 9
myproj_local_django  | INFO 2023-05-27 15:11:17,234 serve 9 139912409515840 Started worker-1
myproj_local_django  | INFO 2023-05-27 15:11:17,234 serve 9 139912409515840 Started worker-1 runtime-1
myproj_local_django  | WARNING 2023-05-27 15:11:28,481 callbacks 9 139912409515840 Application callable raised an exception
myproj_local_django  | Exception ignored in: <coroutine object application at 0x7f3fe1deba60>
myproj_local_django  | Traceback (most recent call last):
myproj_local_django  |   File "/app/config/asgi.py", line 36, in application
myproj_local_django  |     await django_application(scope, receive, send)
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/django/core/handlers/asgi.py", line 154, in __call__
myproj_local_django  |     async with ThreadSensitiveContext():
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 127, in __aexit__
myproj_local_django  |     SyncToAsync.thread_sensitive_context.reset(self.token)
myproj_local_django  | ValueError: <Token var=<ContextVar name='thread_sensitive_context' at 0x7f3fe3d790d0> at 0x7f3fe1c8e680> was created in a different Context  
myproj_local_django  | ERROR 2023-05-27 15:11:28,530 log 9 139912330168064 Internal Server Error: /
myproj_local_django  | Traceback (most recent call last):
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 534, in thread_handler
myproj_local_django  |     raise exc_info[1]
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 43, in inner
myproj_local_django  |     response = await get_response(request)
myproj_local_django  |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py", line 148, in __acall__
myproj_local_django  |     response = await sync_to_async(
myproj_local_django  |                ^^^^^^^^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 479, in __call__
myproj_local_django  |     ret: _R = await loop.run_in_executor(
myproj_local_django  |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
myproj_local_django  |     result = self.fn(*self.args, **self.kwargs)
myproj_local_django  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 538, in thread_handler
myproj_local_django  |     return func(*args, **kwargs)
myproj_local_django  |            ^^^^^^^^^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/django/middleware/locale.py", line 35, in process_request
myproj_local_django  |     translation.activate(language)
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/django/utils/translation/__init__.py", line 181, in activate
myproj_local_django  |     return _trans.activate(language)
myproj_local_django  |            ^^^^^^^^^^^^^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/django/utils/translation/trans_real.py", line 303, in activate
myproj_local_django  |     _active.value = translation(language)
myproj_local_django  |     ^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/local.py", line 111, in __setattr__
myproj_local_django  |     storage = self._get_storage()
myproj_local_django  |               ^^^^^^^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/local.py", line 83, in _get_storage
myproj_local_django  |     setattr(context_obj, self._attr_name, {})
myproj_local_django  | AttributeError: 'NoneType' object has no attribute '_asgiref_local_impl_139912375751504_IvidgRsU'
myproj_local_django  | WARNING 2023-05-27 15:11:28,552 callbacks 9 139912409515840 Application callable raised an exception
myproj_local_django  | Exception ignored in: <coroutine object application at 0x7f3fe1ca8040>
myproj_local_django  | Traceback (most recent call last):
myproj_local_django  |   File "/app/config/asgi.py", line 36, in application
myproj_local_django  | ERROR 2023-05-27 15:11:28,592 log 9 139912330168064 Internal Server Error: /favicon.ico
myproj_local_django  | Traceback (most recent call last):
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 534, in thread_handler
myproj_local_django  |     raise exc_info[1]
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 43, in inner
myproj_local_django  |     response = await get_response(request)
myproj_local_django  |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^
myproj_local_django  |     ^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/local.py", line 111, in __setattr__
myproj_local_django  |     storage = self._get_storage()
myproj_local_django  |               ^^^^^^^^^^^^^^^^^^^
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/local.py", line 83, in _get_storage
myproj_local_django  |     setattr(context_obj, self._attr_name, {})
myproj_local_django  | AttributeError: 'NoneType' object has no attribute '_asgiref_local_impl_139912375751504_IvidgRsU'
myproj_local_django  |     await django_application(scope, receive, send)
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/django/core/handlers/asgi.py", line 154, in __call__
myproj_local_django  |     async with ThreadSensitiveContext():
myproj_local_django  |   File "/usr/local/lib/python3.11/site-packages/asgiref/sync.py", line 127, in __aexit__
myproj_local_django  |     SyncToAsync.thread_sensitive_context.reset(self.token)
myproj_local_django  | ValueError: <Token var=<ContextVar name='thread_sensitive_context' at 0x7f3fe3d790d0> at 0x7f3fe0c567c0> was created in a different Context 
    
  

Here's how I run granian

exec granian --interface asgi config.asgi:application --host 0.0.0.0

and here's my asgi.py

"""
ASGI config for Myproj 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 sys
from pathlib import Path

from django.core.asgi import get_asgi_application

# This allows easy placement of apps within the interior
# myproj directory.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
sys.path.append(str(BASE_DIR / "myproj"))

# If DJANGO_SETTINGS_MODULE is unset, default to the local settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")

# This application object is used by any ASGI server configured to use this file.
django_application = get_asgi_application()
# Apply ASGI middleware here.
# from helloworld.asgi import HelloWorldApplication
# application = HelloWorldApplication(application)

# Import websocket application here, so apps from django_application are loaded first
from config.websocket import websocket_application  # noqa isort:skip


async def application(scope, receive, send):
    if scope["type"] == "http":
        await django_application(scope, receive, send)
    elif scope["type"] == "websocket":
        await websocket_application(scope, receive, send)
    else:
        raise NotImplementedError(f"Unknown scope type {scope['type']}")

Runs perfectly fine with uvicorn, daphne or nginx unit. Also runs fine with granian's wsgi interface.

@Hisham-Pak Hisham-Pak changed the title Interface asgi with django Interface asgi error with django May 27, 2023
@gi0baro
Copy link
Member

gi0baro commented May 27, 2023

@Hisham-Pak is that granian 0.4.2? if so, can you make a try with 0.3.2?

@Hisham-Pak
Copy link
Author

@gi0baro works fine with 0.3.2

@gi0baro
Copy link
Member

gi0baro commented May 27, 2023

It seems the loop optimisations introduced with 0.4 do not play well with how Django uses contextvars.

I gonna release a 0.4.3 in the following days with an option to disable 'em, in the meantime you can pin 0.3.2.

I'll consider to turn those optimisations off by default in next minor, but let's see how it goes.

@gi0baro gi0baro added the bug Something isn't working label May 27, 2023
@gi0baro gi0baro added this to the 0.4 milestone May 27, 2023
@gi0baro
Copy link
Member

gi0baro commented May 28, 2023

0.4.3 will be available shortly.

You should be able to use ASGI on django adding a --no-opt option to the granian command.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants