Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

asyncio.py 1.1KB

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