Skip to content

Instantly share code, notes, and snippets.

@lennyerik
Last active April 20, 2023 09:42
Show Gist options
  • Save lennyerik/19987b3f1db5c2672a78f52ccc413caf to your computer and use it in GitHub Desktop.
Save lennyerik/19987b3f1db5c2672a78f52ccc413caf to your computer and use it in GitHub Desktop.
Django sync decorator for async views
from functools import wraps
from inspect import iscoroutine
from asgiref.sync import sync_to_async
def async_decorator(sync_decorator):
def _decorator(view_func):
@wraps(view_func)
async def _wrapper(*args, **kwargs):
result = await sync_to_async(sync_decorator(view_func))(*args, **kwargs)
if iscoroutine(result):
return await result
return result
return _wrapper
return _decorator
# Use like this
@async_decorator(login_required)
async def myview(request):
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment