Last active
April 20, 2023 09:42
-
-
Save lennyerik/19987b3f1db5c2672a78f52ccc413caf to your computer and use it in GitHub Desktop.
Django sync decorator for async views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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