app_asgi.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import orjson
  2. JSON_RESPONSE = {
  3. 'type': 'http.response.start',
  4. 'status': 200,
  5. 'headers': [
  6. [b'content-type', b'application/json'],
  7. ]
  8. }
  9. PLAINTEXT_RESPONSE = {
  10. 'type': 'http.response.start',
  11. 'status': 200,
  12. 'headers': [
  13. [b'content-type', b'text/plain; charset=utf-8'],
  14. ]
  15. }
  16. json_dumps = orjson.dumps
  17. async def route_json(scope, receive, send):
  18. await send(JSON_RESPONSE)
  19. await send({
  20. 'type': 'http.response.body',
  21. 'body': json_dumps({'message': 'Hello, world!'}),
  22. 'more_body': False
  23. })
  24. async def route_plaintext(scope, receive, send):
  25. await send(PLAINTEXT_RESPONSE)
  26. await send({
  27. 'type': 'http.response.body',
  28. 'body': b'Hello, world!',
  29. 'more_body': False
  30. })
  31. async def handle_404(scope, receive, send):
  32. await send(PLAINTEXT_RESPONSE)
  33. await send({
  34. 'type': 'http.response.body',
  35. 'body': b'Not found',
  36. 'more_body': False
  37. })
  38. routes = {
  39. '/json': route_json,
  40. '/plaintext': route_plaintext
  41. }
  42. def main(scope, receive, send):
  43. handler = routes.get(scope['path'], handle_404)
  44. return handler(scope, receive, send)