app-socketify-asgi.py 971 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import os
  2. import multiprocessing
  3. import logging
  4. import orjson
  5. from litestar import Litestar, get, MediaType, Response
  6. from socketify import ASGI
  7. @get("/json")
  8. async def json_serialization() -> Response:
  9. return Response(content=orjson.dumps({"message": "Hello, world!"}), media_type=MediaType.JSON)
  10. @get("/plaintext", media_type=MediaType.TEXT)
  11. async def plaintext() -> bytes:
  12. return b"Hello, world!"
  13. app = Litestar(
  14. route_handlers=[
  15. json_serialization,
  16. plaintext,
  17. ]
  18. )
  19. _is_travis = os.environ.get("TRAVIS") == "true"
  20. workers = int(multiprocessing.cpu_count())
  21. if _is_travis:
  22. workers = 2
  23. def run_app():
  24. ASGI(app).listen(8080, lambda config: logging.info(f"Listening on port http://localhost:{config.port} now\n")).run()
  25. def create_fork():
  26. n = os.fork()
  27. # n greater than 0 means parent process
  28. if not n > 0:
  29. run_app()
  30. # fork limiting the cpu count - 1
  31. for i in range(1, workers):
  32. create_fork()
  33. run_app() # run app on the main process too :)