Debian Codegraph @

django/utils/asyncio.py

raw
1 import os
2 from asyncio import get_running_loop
3 from functools import wraps
4
5 from django.core.exceptions import SynchronousOnlyOperation
6
7
8 def async_unsafe(message):
9 """
10 Decorator to mark functions as async-unsafe. Someone trying to access
11 the function while in an async context will get an error message.
12 """
13
14 def decorator(func):
15 @wraps(func)
16 def inner(*args, **kwargs):
17 # Detect a running event loop in this thread.
18 try:
19 get_running_loop()
20 except RuntimeError:
21 pass
22 else:
23 if not os.environ.get("DJANGO_ALLOW_ASYNC_UNSAFE"):
24 raise SynchronousOnlyOperation(message)
25 # Pass onward.
26 return func(*args, **kwargs)
27
28 return inner
29
30 # If the message is actually a function, then be a no-arguments decorator.
31 if callable(message):
32 func = message
33 message = (
34 "You cannot call this from an async context - use a thread or "
35 "sync_to_async."
36 )
37 return decorator(func)
38 else:
39 return decorator