app-socketify-asgi.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python
  2. import falcon.asgi
  3. from socketify import ASGI
  4. import os
  5. import multiprocessing
  6. import logging
  7. # setup
  8. asgi = app = falcon.asgi.App()
  9. # resource endpoints
  10. class JSONResource(object):
  11. async def on_get(self, request, response):
  12. response.media = {'message': "Hello, world!"}
  13. class PlaintextResource(object):
  14. async def on_get(self, request, response):
  15. response.content_type = falcon.MEDIA_TEXT
  16. response.text = 'Hello, world!'
  17. # register resources
  18. app.add_route("/json", JSONResource())
  19. app.add_route("/plaintext", PlaintextResource())
  20. _is_travis = os.environ.get('TRAVIS') == 'true'
  21. workers = int(multiprocessing.cpu_count())
  22. if _is_travis:
  23. workers = 2
  24. def run_app():
  25. ASGI(app).listen(8080, lambda config: logging.info(f"Listening on port http://localhost:{config.port} now\n")).run()
  26. def create_fork():
  27. n = os.fork()
  28. # n greater than 0 means parent process
  29. if not n > 0:
  30. run_app()
  31. # fork limiting the cpu count - 1
  32. for i in range(1, workers):
  33. create_fork()
  34. run_app() # run app on the main process too :)