ASGI specs, helper code, and adapters for bridging synchronous and asynchronous Python web applications
npx @tessl/cli install tessl/pypi-asgiref@3.9.0ASGI specs, helper code, and adapters for bridging synchronous and asynchronous Python web applications. This library provides essential utilities for asynchronous web development, serving as the foundational component for Django Channels and other ASGI-based applications.
pip install asgirefimport asgirefMost commonly used imports:
from asgiref.sync import sync_to_async, async_to_sync
from asgiref.wsgi import WsgiToAsgi
from asgiref.compatibility import guarantee_single_callablefrom asgiref.sync import sync_to_async, async_to_sync
import asyncio
# Convert sync function to async
@sync_to_async
def sync_database_query():
# Simulate database query
return {"id": 1, "name": "example"}
# Convert async function to sync
@async_to_sync
async def async_api_call():
# Simulate async API call
await asyncio.sleep(0.1)
return {"status": "success"}
# Usage
async def main():
# Call sync function from async context
result = await sync_database_query()
print(result)
# Call async function from sync context
result = async_api_call()
print(result)asgiref's design enables seamless integration between synchronous and asynchronous Python code:
This architecture supports Django's transition to async views while maintaining backward compatibility with synchronous components.
Core functionality for converting between synchronous and asynchronous functions, handling context propagation, thread management, and event loop integration automatically.
def sync_to_async(func=None, *, thread_sensitive=True, executor=None): ...
def async_to_sync(awaitable=None, *, force_new_loop=False): ...
class SyncToAsync: ...
class AsyncToSync: ...Utilities for ensuring ASGI applications work consistently across different ASGI versions and server implementations, handling legacy double-callable patterns.
def guarantee_single_callable(application): ...
def is_double_callable(application): ...
def double_to_single_callable(application): ...Adapters for running WSGI applications within ASGI servers, enabling legacy web applications to benefit from async server capabilities.
class WsgiToAsgi:
def __init__(wsgi_application): ...
def __call__(scope, receive, send): ...Async-aware local storage that works correctly with both threading and asyncio, replacing threading.local for async applications.
class Local:
def __init__(thread_critical=False): ...Base classes for implementing ASGI servers, handling application lifecycle, connection management, and stateless protocol support.
class StatelessServer:
def __init__(application, max_applications=1000): ...
def run(): ...
async def arun(): ...Tools for testing ASGI applications, providing controlled communication channels and application lifecycle management.
class ApplicationCommunicator:
def __init__(application, scope): ...
async def wait(timeout=1): ...
async def send_input(message): ...
async def receive_output(timeout=1): ...Async timeout context managers for controlling operation timeouts in asynchronous code.
class timeout:
def __init__(timeout, *, loop=None): ...
async def __aenter__(): ...
async def __aexit__(exc_type, exc_val, exc_tb): ...Specialized executor for running code in the thread where it was instantiated, enabling cross-thread execution coordination for async-to-sync conversion scenarios.
class CurrentThreadExecutor:
def __init__(self, old_executor: CurrentThreadExecutor | None) -> None: ...
def run_until_future(self, future: Future[Any]) -> None: ...
def submit(self, fn: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_R]: ...Complete type definitions for ASGI protocols, events, and applications, enabling full type safety in async web applications.
# Protocol Types
ASGIApplication = Union[ASGI2Application, ASGI3Application]
ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]]
ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]]
# Scope Types
Scope = Union[HTTPScope, WebSocketScope, LifespanScope]__version__: str # Package version "3.9.1"