question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

RuntimeError: There is no current event loop in thread 'MainThread'

See original GitHub issue

Checklist

  • The bug is reproducible against the latest release and/or master.
  • There are no similar issues or pull requests to fix it yet.

Describe the bug

Before I begin, I’m not 100% confident if this is a bug or if this is a configuration error on my part. I’m in no way a webserver expert nor do I have formal training in the area.

While configuring a Gunicorn webserver (with a uvicorn worker according to your docs), I am encountering the above error. My webserver isn’t even starting as I have a logger in the asgi.py file of my Django app that isn’t outputting anything. Removing the uvicorn worker from the configuration allows the server to run as expected.

To reproduce

Create a django app, put it into the /srv/ folder of a Linux machine, and use the configuration files below to set it up.

This webserver is setup in the following fashion:

  • NGINX proxy
  • Gunicorn Webserver (using Uvicorn workers)
  • ASGI Django backend

Here is the NGINX configuration I have:

upstream uvicorn {
  server unix:/run/gunicorn.sock;
}

server {
    listen 80;
    server_name <server_ip>;

    location = /favicon.ico { access_log off; log_not_found off; }

    location / {
        include proxy_params;
        proxy_set_header Connection "";
        proxy_pass http://uvicorn;
    }

    location /ws/ {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_redirect off;
        proxy_pass http://uvicorn;
    }

    location /static/ {
        root /srv/webserver;
    }
}

Here is the Gunicorn configuration I have. This is a systemd service as I am running Gunicorn as a service. However, I have been able to replicate this issue by just running the ExecStart command in a virtualenv (remove --error-logfile /var/log/gunicorn/error.log \).

/etc/systemd/system/gunicorn.service

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=django
Group=www-data
WorkingDirectory=/srv/webserver
Environment=DJANGO_SECRET_KEY=$DJANGO_SECRET_KEY
ExecStart=/srv/webserver/venv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
--timeout 300 \
--error-logfile /var/log/gunicorn/error.log \
--access-logfile /var/log/gunicorn/access.log \
--log-level debug \
--capture-output \
-k uvicorn.workers.UvicornWorker \
webserver.asgi:application

/etc/systemd/system/gunicorn.socket

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

Expected behavior

The webserver to launch and this error to not occur.

Actual behavior

The error above before my code of the webserver even launches.

Debugging material

Here is the full traceback:

[2021-08-11 09:09:26 -0500] [2335] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/srv/CentralWebServer/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
    worker.init_process()
  File "/srv/CentralWebServer/venv/lib/python3.8/site-packages/uvicorn/workers.py", line 64, in init_process
    super(UvicornWorker, self).init_process()
  File "/srv/CentralWebServer/venv/lib/python3.8/site-packages/gunicorn/workers/base.py", line 142, in init_process
    self.run()
  File "/srv/CentralWebServer/venv/lib/python3.8/site-packages/uvicorn/workers.py", line 76, in run
    loop = asyncio.get_event_loop()
  File "/usr/lib/python3.8/asyncio/events.py", line 639, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'MainThread'.

Environment

  • OS / Python / Uvicorn version: Running uvicorn 0.14.0 with CPython 3.8.10 on Linux
  • The exact command you’re running uvicorn with, all flags you passed included. If you run it with gunicorn please do the same. If there is a reverse-proxy involved and you cannot reproduce without it please give the minimal config of it to reproduce. Above

Additional context

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
JulianOrteilcommented, Aug 11, 2021

After much testing, I discovered the root cause. In one of my files, I occasionally run an async operation to check for changes to a hot-folder. This operation runs at the start of the launch which is what was causing all of the issues.

i.e. asyncio.run(run_subprocess('cmd to check for hot folder')) was the culprit. Changing it to

loop = asyncio.get_event_loop() or asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete('cmd to check for hot folder')

fixed the issue.

0reactions
JulianOrteilcommented, Aug 11, 2021

ok it’s been a while I havent touched Django and I thought it was still wsgi, maybe others more familiar with it can help

Ah, no problem. Thanks for your time anyways.

After even more investigation, I believe this to be a configuration issue or setup issue with how I have made my webserver. I have absolutely no idea what it could be, so I’ll update this as soon as I find out. If anyone has any ideas, please do let me know… I’m pretty stuck haha.

Read more comments on GitHub >

github_iconTop Results From Across the Web

RuntimeError: There is no current event loop in thread in ...
In your def demo_async(urls) , try to replace: loop = asyncio.get_event_loop(). with: loop = asyncio.new_event_loop() ...
Read more >
How to fix Python asyncio RuntimeError: There is no current ...
You are trying to run asyncio.get_event_loop() in some thread other than the main thread – however, asyncio only generates an event loop for...
Read more >
there is no current event loop in thread python - You.com
1. Threads do not have an event loop, you simply need to use the main thread loop. t = Thread (target=run, args= [client ......
Read more >
There is no current event loop in thread) - Ray Workflows
I'm trying to start a Workflow from a Python thread (using import threading), but it appears Ray is not set up for this....
Read more >
Mastering asyncio — Telethon 1.26.0 documentation
First we need the asyncio library import asyncio # Then we need a loop to work with ... RuntimeError: There is no current...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found