importasyncioimportfunctoolsimportosfromdjango.core.exceptionsimportSynchronousOnlyOperationdefasync_unsafe(message):""" Decorator to mark functions as async-unsafe. Someone trying to access the function while in an async context will get an error message. """defdecorator(func):@functools.wraps(func)definner(*args,**kwargs):ifnotos.environ.get("DJANGO_ALLOW_ASYNC_UNSAFE"):# Detect a running event loop in this thread.try:asyncio.get_running_loop()exceptRuntimeError:passelse:raiseSynchronousOnlyOperation(message)# Pass onward.returnfunc(*args,**kwargs)returninner# If the message is actually a function, then be a no-arguments decorator.ifcallable(message):func=messagemessage=("You cannot call this from an async context - use a thread or ""sync_to_async.")returndecorator(func)else:returndecorator