lepture / python-livereload

livereload server in python
https://livereload.readthedocs.io/en/latest/
BSD 3-Clause "New" or "Revised" License
1.02k stars 150 forks source link

Error: SynchronousOnlyOperation with Django 3 #228

Open ghost opened 4 years ago

ghost commented 4 years ago

I have Ubuntu 18.04. I've followed the instructions in the README, but when I run python manage.py livereload and open localhost:8000 I get a SynchronousOnlyOperation error. My traceback is as follows. It seems to raise error at {% user.is_authenticated %} template tag.

Environment:

Request Method: GET
Request URL: http://localhost:8000/

Django Version: 3.1
Python Version: 3.6.9
Installed Applications:
['livereload',
 'formsapp',
 'Dummy',
 'crispy_forms',
 'users',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.facebook',
 'allauth.socialaccount.providers.github',
 'allauth.socialaccount.providers.google']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template /home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/formsapp/templates/forms/base.html, error at line 18
   You cannot call this from an async context - use a thread or sync_to_async.
   8 :     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   9 : 
   10 :     <title>{% block title %}Home page{% endblock %}</title>
   11 :     <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
   12 :     <link rel="stylesheet" href="{% static 'css/styles.css' %}">
   13 : </head>
   14 : <body>
   15 : <header>
   16 :     <div>
   17 :         <!-- User login/logout options -->
   18 :          {% if user.is_authenticated %} 
   19 :             <a href="{% url 'logout' %}">Sign out</a>
   20 :         {% else %}
   21 :             <a href="{% url 'login' %}">Sign In</a>
   22 :             <a href="{% url 'register' %}">Sign Up</a>
   23 :         {% endif %}
   24 :         User: {{ user }}
   25 :     </div>
   26 :     <h1>
   27 :         <a id="logo" href="{% url 'home-page' %}">Website name & logo</a>
   28 :     </h1>

Traceback (most recent call last):
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 215, in _get_session
    return self._session_cache

During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred:
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/formsapp/views.py", line 10, in show_homepage
    return render(request, 'forms/base.html')
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 170, in render
    return self._render(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 162, in _render
    return self.nodelist.render(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/defaulttags.py", line 305, in render
    match = condition.eval(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/defaulttags.py", line 889, in eval
    return self.value.resolve(context, ignore_failures=True)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 671, in resolve
    obj = self.var.resolve(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 796, in resolve
    value = self._resolve_lookup(context)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/utils/functional.py", line 240, in inner
    self._setup()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/utils/functional.py", line 376, in _setup
    self._wrapped = self._setupfunc()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 23, in <lambda>
    request.user = SimpleLazyObject(lambda: get_user(request))
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 11, in get_user
    request._cached_user = auth.get_user(request)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 174, in get_user
    user_id = _get_user_session_key(request)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 58, in _get_user_session_key
    return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 65, in __getitem__
    return self._session[key]
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 220, in _get_session
    self._session_cache = self.load()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 43, in load
    s = self._get_session_from_db()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 34, in _get_session_from_db
    expire_date__gt=timezone.now()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/query.py", line 425, in get
    num = len(clone)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/query.py", line 269, in __len__
    self._fetch_all()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1303, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1152, in execute_sql
    cursor = self.connection.cursor()
  File "/home/raphaelnazirullah/Documents/Mental Health Web app/mental_health_app/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 24, in inner
    raise SynchronousOnlyOperation(message)

Exception Type: SynchronousOnlyOperation at /
Exception Value: You cannot call this from an async context - use a thread or sync_to_async.

My project structure is as follows:

.
├── db.sqlite3
├── Dummy
├── formsapp
├── manage.py
├── mental_health_app
├── my-cred.txt
├── __pycache__
├── README.md
├── requirements.txt
├── users
├── venv
pradyunsg commented 4 years ago

Thanks for filing this issue!

Could you provide a minimal set of steps and code, so that I can reproduce this issue?

jnoortheen commented 3 years ago

this is reproducible with any django>=3.0

like in this tutorial

django-admin startproject mysite

and after adding livereload to the apps,

if one tries to run

python manage.py livereload

then the above traceback would appear

lingster commented 3 years ago

I had a similar problem and managed to work around as per suggestion here: https://docs.djangoproject.com/en/3.1/topics/async/#async-safety ie defined an environment variable: DJANGO_ALLOW_ASYNC_UNSAFE=1

note this should only be done in a local non-production/development environment or you could risk losing/corrupting data.

In my case I am running a project created using django 3.1.7 and python 3.8.8

Ou7law007 commented 3 years ago

I had a similar problem and managed to work around as per suggestion here: https://docs.djangoproject.com/en/3.1/topics/async/#async-safety ie defined an environment variable: DJANGO_ALLOW_ASYNC_UNSAFE=1

note this should only be done in a local non-production/development environment or you could risk losing/corrupting data.

In my case I am running a project created using django 3.1.7 and python 3.8.8

Does not work for me

edugmes commented 2 years ago

Any idea on how to solve that for production? Thanks!

pradyunsg commented 2 years ago

You really shouldn't be using livereload in production.

PauloDoMonte commented 5 months ago

I believe your issue is with the allauth library. I'm currently facing the same problem. It appears that this library doesn't support asynchronous usage by default. I'm still unsure about what to do next — whether to manually implement the entire authentication part or to integrate this library into my project and modify its code to fit the asynchronous context.

lepture commented 5 months ago

@PauloDoMonte I'm currently working on livereload v3, which is ASGI based.