-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpubsub_aiohttp.py
More file actions
54 lines (37 loc) · 1.11 KB
/
pubsub_aiohttp.py
File metadata and controls
54 lines (37 loc) · 1.11 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
import asyncio
from aiohttp import web
class Hub():
def __init__(self):
self.subscriptions = set()
def publish(self, message):
for queue in self.subscriptions:
queue.put_nowait(message)
class Subscription():
def __init__(self, hub):
self.hub = hub
self.queue = asyncio.Queue()
def __enter__(self):
hub.subscriptions.add(self.queue)
return self.queue
def __exit__(self, type, value, traceback):
hub.subscriptions.remove(self.queue)
hub = Hub()
async def sub(request):
resp = web.StreamResponse()
resp.headers['content-type'] = 'text/plain'
resp.status_code = 200
await resp.prepare(request)
with Subscription(hub) as queue:
while True:
msg = await queue.get()
resp.write(bytes(f'{msg}\r\n', 'utf-8'))
return resp
async def pub(request):
msg = request.query.get('msg', '')
hub.publish(msg)
return web.Response(text='ok')
if __name__ == '__main__':
app = web.Application()
app.router.add_get('/', sub)
app.router.add_post('/', pub)
web.run_app(app)