0
# asgiref
1
2
ASGI 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.
3
4
## Package Information
5
6
- **Package Name**: asgiref
7
- **Language**: Python
8
- **Installation**: `pip install asgiref`
9
10
## Core Imports
11
12
```python
13
import asgiref
14
```
15
16
Most commonly used imports:
17
18
```python
19
from asgiref.sync import sync_to_async, async_to_sync
20
from asgiref.wsgi import WsgiToAsgi
21
from asgiref.compatibility import guarantee_single_callable
22
```
23
24
## Basic Usage
25
26
```python
27
from asgiref.sync import sync_to_async, async_to_sync
28
import asyncio
29
30
# Convert sync function to async
31
@sync_to_async
32
def sync_database_query():
33
# Simulate database query
34
return {"id": 1, "name": "example"}
35
36
# Convert async function to sync
37
@async_to_sync
38
async def async_api_call():
39
# Simulate async API call
40
await asyncio.sleep(0.1)
41
return {"status": "success"}
42
43
# Usage
44
async def main():
45
# Call sync function from async context
46
result = await sync_database_query()
47
print(result)
48
49
# Call async function from sync context
50
result = async_api_call()
51
print(result)
52
```
53
54
## Architecture
55
56
asgiref's design enables seamless integration between synchronous and asynchronous Python code:
57
58
- **Sync/Async Converters**: Core utilities that handle context propagation and thread management
59
- **ASGI Compatibility Layer**: Ensures applications work with both ASGI2 and ASGI3 specifications
60
- **Thread-Safe Storage**: Async-aware replacements for threading.local that work across event loops
61
- **WSGI Integration**: Adapters for running legacy WSGI applications in ASGI servers
62
- **Testing Utilities**: Tools for testing ASGI applications in controlled environments
63
64
This architecture supports Django's transition to async views while maintaining backward compatibility with synchronous components.
65
66
## Capabilities
67
68
### Sync/Async Conversion
69
70
Core functionality for converting between synchronous and asynchronous functions, handling context propagation, thread management, and event loop integration automatically.
71
72
```python { .api }
73
def sync_to_async(func=None, *, thread_sensitive=True, executor=None): ...
74
def async_to_sync(awaitable=None, *, force_new_loop=False): ...
75
class SyncToAsync: ...
76
class AsyncToSync: ...
77
```
78
79
[Sync/Async Conversion](./sync-async.md)
80
81
### ASGI Compatibility
82
83
Utilities for ensuring ASGI applications work consistently across different ASGI versions and server implementations, handling legacy double-callable patterns.
84
85
```python { .api }
86
def guarantee_single_callable(application): ...
87
def is_double_callable(application): ...
88
def double_to_single_callable(application): ...
89
```
90
91
[ASGI Compatibility](./compatibility.md)
92
93
### WSGI Integration
94
95
Adapters for running WSGI applications within ASGI servers, enabling legacy web applications to benefit from async server capabilities.
96
97
```python { .api }
98
class WsgiToAsgi:
99
def __init__(wsgi_application): ...
100
def __call__(scope, receive, send): ...
101
```
102
103
[WSGI Integration](./wsgi-integration.md)
104
105
### Thread-Safe Storage
106
107
Async-aware local storage that works correctly with both threading and asyncio, replacing threading.local for async applications.
108
109
```python { .api }
110
class Local:
111
def __init__(thread_critical=False): ...
112
```
113
114
[Thread-Safe Storage](./local-storage.md)
115
116
### ASGI Server Base
117
118
Base classes for implementing ASGI servers, handling application lifecycle, connection management, and stateless protocol support.
119
120
```python { .api }
121
class StatelessServer:
122
def __init__(application, max_applications=1000): ...
123
def run(): ...
124
async def arun(): ...
125
```
126
127
[ASGI Server Base](./server-base.md)
128
129
### Testing Utilities
130
131
Tools for testing ASGI applications, providing controlled communication channels and application lifecycle management.
132
133
```python { .api }
134
class ApplicationCommunicator:
135
def __init__(application, scope): ...
136
async def wait(timeout=1): ...
137
async def send_input(message): ...
138
async def receive_output(timeout=1): ...
139
```
140
141
[Testing Utilities](./testing.md)
142
143
### Timeout Management
144
145
Async timeout context managers for controlling operation timeouts in asynchronous code.
146
147
```python { .api }
148
class timeout:
149
def __init__(timeout, *, loop=None): ...
150
async def __aenter__(): ...
151
async def __aexit__(exc_type, exc_val, exc_tb): ...
152
```
153
154
[Timeout Management](./timeout.md)
155
156
### Current Thread Executor
157
158
Specialized executor for running code in the thread where it was instantiated, enabling cross-thread execution coordination for async-to-sync conversion scenarios.
159
160
```python { .api }
161
class CurrentThreadExecutor:
162
def __init__(self, old_executor: CurrentThreadExecutor | None) -> None: ...
163
def run_until_future(self, future: Future[Any]) -> None: ...
164
def submit(self, fn: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_R]: ...
165
```
166
167
[Current Thread Executor](./current-thread-executor.md)
168
169
### Type Definitions
170
171
Complete type definitions for ASGI protocols, events, and applications, enabling full type safety in async web applications.
172
173
```python { .api }
174
# Protocol Types
175
ASGIApplication = Union[ASGI2Application, ASGI3Application]
176
ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]]
177
ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]]
178
179
# Scope Types
180
Scope = Union[HTTPScope, WebSocketScope, LifespanScope]
181
```
182
183
[Type Definitions](./type-definitions.md)
184
185
## Version Information
186
187
```python { .api }
188
__version__: str # Package version "3.9.1"
189
```