Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache the imported AsyncToSync and SyncToAsync classes on the Local class #288

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion asgiref/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class Local:
"""

CLEANUP_INTERVAL = 60 # seconds
launch_map_classes = None # cache imported (AsyncToSync, SyncToAsync) on first access.

def __init__(self, thread_critical: bool = False) -> None:
self._thread_critical = thread_critical
Expand All @@ -48,7 +49,12 @@ def _get_context_id(self):
Get the ID we should use for looking up variables
"""
# Prevent a circular reference
from .sync import AsyncToSync, SyncToAsync
# Once imported the first time, hold a reference to them on the class.
if not Local.launch_map_classes:
from .sync import AsyncToSync, SyncToAsync
Local.launch_map_classes = (AsyncToSync, SyncToAsync)
else:
AsyncToSync, SyncToAsync = Local.launch_map_classes

# First, pull the current task if we can
context_id = SyncToAsync.get_current_task()
Expand Down