raw-asgi.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from socketify import ASGI
  2. import os
  3. try:
  4. from ujson import dumps as json
  5. except:
  6. from json import dumps as json
  7. async def app(scope, receive, send):
  8. assert scope['type'] == 'http'
  9. path = scope['path']
  10. if path == "/plaintext":
  11. await send({
  12. 'type': 'http.response.start',
  13. 'status': 200,
  14. 'headers': [
  15. [b'content-type', b'text/plain'],
  16. ],
  17. })
  18. await send({
  19. 'type': 'http.response.body',
  20. 'body': b'Hello, world!',
  21. })
  22. return
  23. if path == "/json":
  24. await send({
  25. 'type': 'http.response.start',
  26. 'status': 200,
  27. 'headers': [
  28. [b'content-type', b'application/json'],
  29. ],
  30. })
  31. await send({
  32. 'type': 'http.response.body',
  33. 'body': json({"message":"Hello, World!"}).encode('utf8'),
  34. })
  35. def run_app():
  36. ASGI(app,lifespan=False).listen(3000, lambda config: print(f"Listening on port http://localhost:{config.port} now\n")).run()
  37. def create_fork():
  38. n = os.fork()
  39. # n greater than 0 means parent process
  40. if not n > 0:
  41. run_app()
  42. def get_worker_count():
  43. try:
  44. return int(os.environ["WORKER_COUNT"])
  45. except:
  46. return 2
  47. WORKER_COUNT = get_worker_count() - 1
  48. for index in range(WORKER_COUNT):
  49. create_fork()
  50. run_app()