app-socketify-asgi.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import os
  2. import multiprocessing
  3. import logging
  4. from fastapi import FastAPI, Request
  5. from fastapi.responses import PlainTextResponse
  6. from socketify import ASGI
  7. try:
  8. import orjson
  9. from fastapi.responses import ORJSONResponse as JSONResponse
  10. except ImportError:
  11. from fastapi.responses import JSONResponse as JSONResponse
  12. app = FastAPI()
  13. @app.get("/json")
  14. async def json_serialization():
  15. return JSONResponse({"message": "Hello, world!"})
  16. @app.get("/plaintext")
  17. async def plaintext():
  18. return PlainTextResponse(b"Hello, world!")
  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 :)