0

I have a lot of async code and I have the question.

May I have a singleton event loop in the whole project or I should use get_event_loop() in every function, method, class? Are there some problems to declare it one time and use it from any place in the project?

For example, I have 3 files app.py, views.py, internal.py

app.py

app = FastAPI()
loop = get_event_loop()

views.py

from app import app, loop

@app.get('/')
async def main(request):
   loop.create_task(<any coroutine>)
   return {'status': 'ok'}

internal.py

from app import loop

async def any_buisiness_logic():
    loop.create_task(<any coroutine>)
    return "task created"

Or I should get_event_loop() in every file?

2
  • Can you please provide some usecase, minimal working example Commented Mar 18, 2020 at 9:16
  • I've added usecase, check it out Commented Mar 18, 2020 at 9:29

1 Answer 1

3

You can use asyncio.create_task instead. Loop needn't be passed around in newer versions of Python.

The task is executed in the loop returned by get_running_loop(), RuntimeError is raised if there is no running loop in current thread.

https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.