app-socketify-asgi.py 865 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. import multiprocessing
  3. import logging
  4. from socketify import ASGI
  5. from emmett import App
  6. from emmett.tools import service
  7. app = App(__name__)
  8. app.config.handle_static = False
  9. @app.route()
  10. @service.json
  11. async def json():
  12. return {'message': 'Hello, World!'}
  13. @app.route(output='bytes')
  14. async def plaintext():
  15. return b'Hello, World!'
  16. _is_travis = os.environ.get('TRAVIS') == 'true'
  17. workers = int(multiprocessing.cpu_count())
  18. if _is_travis:
  19. workers = 2
  20. def run_app():
  21. ASGI(app).listen(8080, lambda config: logging.info(f"Listening on port http://localhost:{config.port} now\n")).run()
  22. def create_fork():
  23. n = os.fork()
  24. # n greater than 0 means parent process
  25. if not n > 0:
  26. run_app()
  27. # fork limiting the cpu count - 1
  28. for i in range(1, workers):
  29. create_fork()
  30. run_app() # run app on the main process too :)