-
-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathasgi.py
More file actions
197 lines (159 loc) · 5.69 KB
/
asgi.py
File metadata and controls
197 lines (159 loc) · 5.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import asyncio
import json
import pathlib
import sniffio
PLAINTEXT_RESPONSE = {
'type': 'http.response.start',
'status': 200,
'headers': [[b'content-type', b'text/plain; charset=utf-8']],
}
JSON_RESPONSE = {'type': 'http.response.start', 'status': 200, 'headers': [[b'content-type', b'application/json']]}
MEDIA_RESPONSE = {
'type': 'http.response.start',
'status': 200,
'headers': [[b'content-type', b'image/png'], [b'content-length', b'95']],
}
async def info(scope, receive, send):
await send(JSON_RESPONSE)
await send(
{
'type': 'http.response.body',
'body': json.dumps(
{
'type': scope['type'],
'asgi': scope['asgi'],
'http_version': scope['http_version'],
'scheme': scope['scheme'],
'method': scope['method'],
'path': scope['path'],
'query_string': scope['query_string'].decode('latin-1'),
'headers': {k.decode('utf8'): v.decode('utf8') for k, v in scope['headers']},
'extensions': scope['extensions'],
'state': scope['state'],
}
).encode('utf8'),
'more_body': False,
}
)
async def sniff_aio_impl(scope, receive, send):
await send(PLAINTEXT_RESPONSE)
await send(
{'type': 'http.response.body', 'body': sniffio.current_async_library().encode('utf8'), 'more_body': False}
)
async def echo(scope, receive, send):
await send(PLAINTEXT_RESPONSE)
more_body = True
body = b''
while more_body:
msg = await receive()
more_body = msg['more_body']
body += msg['body']
await send({'type': 'http.response.body', 'body': body, 'more_body': False})
async def pathsend(scope, receive, send):
path = pathlib.Path.cwd() / 'tests' / 'fixtures' / 'media.png'
await send(MEDIA_RESPONSE)
await send({'type': 'http.response.pathsend', 'path': str(path)})
async def ws_reject(scope, receive, send):
return
async def ws_info(scope, receive, send):
await send({'type': 'websocket.accept'})
await send(
{
'type': 'websocket.send',
'text': json.dumps(
{
'type': scope['type'],
'asgi': scope['asgi'],
'http_version': scope['http_version'],
'scheme': scope['scheme'],
'path': scope['path'],
'query_string': scope['query_string'].decode('latin-1'),
'headers': {k.decode('utf8'): v.decode('utf8') for k, v in scope['headers']},
'subprotocols': scope['subprotocols'],
}
),
}
)
await send({'type': 'websocket.close'})
async def ws_echo(scope, receive, send):
await send({'type': 'websocket.accept'})
while True:
msg = await receive()
if msg['type'] == 'websocket.connect':
continue
if msg['type'] == 'websocket.disconnect':
break
rv = {'type': 'websocket.send', 'bytes': None, 'text': None}
key = 'text' if 'text' in msg else 'bytes'
rv[key] = msg[key]
await send(rv)
await send({'type': 'websocket.close'})
async def ws_push(scope, receive, send):
await send({'type': 'websocket.accept'})
try:
while True:
await send({'type': 'websocket.send', 'text': 'ping'})
except Exception:
pass
async def err_app(scope, receive, send):
1 / 0
async def err_proto_msg(scope, receive, send):
await send(PLAINTEXT_RESPONSE)
try:
await send({'type': 'wrong.msg'})
except Exception as e:
msg = e.args[0]
await send({'type': 'http.response.body', 'body': msg.encode('utf8'), 'more_body': False})
async def err_proto_flow(scope, receive, send):
await send(PLAINTEXT_RESPONSE)
await send({'type': 'http.response.body', 'body': b'msg1', 'more_body': False})
try:
await send({'type': 'http.response.body', 'body': b'msg2', 'more_body': True})
except Exception:
pass
try:
await send({'type': 'http.response.body', 'body': b'msg3', 'more_body': False})
except Exception:
pass
async def timeout_n(scope, receive, send):
async def _inner():
return b'ok'
await send(PLAINTEXT_RESPONSE)
try:
ret = await asyncio.wait_for(_inner(), None)
except asyncio.TimeoutError:
ret = b'timeout'
await send({'type': 'http.response.body', 'body': ret, 'more_body': False})
async def timeout_w(scope, receive, send):
async def _inner():
await asyncio.sleep(3)
return b'ok'
await send(PLAINTEXT_RESPONSE)
try:
ret = await asyncio.wait_for(_inner(), 1)
except asyncio.TimeoutError:
ret = b'timeout'
await send({'type': 'http.response.body', 'body': ret, 'more_body': False})
async def lifespan(scope, receive, send):
msg = await receive()
if msg['type'] == 'lifespan.startup':
scope['state']['global'] = 'test'
await send({'type': 'lifespan.startup.complete'})
def app(scope, receive, send):
if scope['type'] == 'lifespan':
return lifespan(scope, receive, send)
return {
'/info': info,
'/sniffio': sniff_aio_impl,
'/echo': echo,
'/file': pathsend,
'/ws_reject': ws_reject,
'/ws_info': ws_info,
'/ws_echo': ws_echo,
'/ws_push': ws_push,
'/err_app': err_app,
'/err_proto/type': err_proto_msg,
'/err_proto/flow': err_proto_flow,
'/timeout_n': timeout_n,
'/timeout_w': timeout_w,
}.get(scope['path'], info)(scope, receive, send)