Debian Codegraph @

example/deployment/kubernetes/app.py

raw
1 #!/usr/bin/env python
2
3 import asyncio
4 import http
5 import signal
6 import sys
7 import time
8
9 from websockets.asyncio.server import serve
10
11
12 async def slow_echo(websocket):
13 async for message in websocket:
14 # Block the event loop! This allows saturating a single asyncio
15 # process without opening an impractical number of connections.
16 time.sleep(0.1) # 100ms
17 await websocket.send(message)
18
19
20 def health_check(connection, request):
21 if request.path == "/healthz":
22 return connection.respond(http.HTTPStatus.OK, "OK\n")
23 if request.path == "/inemuri":
24 loop = asyncio.get_running_loop()
25 loop.call_later(1, time.sleep, 10)
26 return connection.respond(http.HTTPStatus.OK, "Sleeping for 10s\n")
27 if request.path == "/seppuku":
28 loop = asyncio.get_running_loop()
29 loop.call_later(1, sys.exit, 69)
30 return connection.respond(http.HTTPStatus.OK, "Terminating\n")
31
32
33 async def main():
34 async with serve(slow_echo, "", 80, process_request=health_check) as server:
35 loop = asyncio.get_running_loop()
36 loop.add_signal_handler(signal.SIGTERM, server.close)
37 await server.wait_closed()
38
39
40 if __name__ == "__main__":
41 asyncio.run(main())