Custom Application

New in version 19.0.

Sometimes, you want to integrate Gunicorn with your WSGI application. In this case, you can inherit from gunicorn.app.base.BaseApplication.

Here is a small example where we create a very small WSGI app and load it with a custom Application:

  1. from __future__ import unicode_literals
  2. import multiprocessing
  3. import gunicorn.app.base
  4. from gunicorn.six import iteritems
  5. def number_of_workers():
  6. return (multiprocessing.cpu_count() * 2) + 1
  7. def handler_app(environ, start_response):
  8. response_body = b'Works fine'
  9. status = '200 OK'
  10. response_headers = [
  11. ('Content-Type', 'text/plain'),
  12. ]
  13. start_response(status, response_headers)
  14. return [response_body]
  15. class StandaloneApplication(gunicorn.app.base.BaseApplication):
  16. def __init__(self, app, options=None):
  17. self.options = options or {}
  18. self.application = app
  19. super(StandaloneApplication, self).__init__()
  20. def load_config(self):
  21. config = dict([(key, value) for key, value in iteritems(self.options)
  22. if key in self.cfg.settings and value is not None])
  23. for key, value in iteritems(config):
  24. self.cfg.set(key.lower(), value)
  25. def load(self):
  26. return self.application
  27. if __name__ == '__main__':
  28. options = {
  29. 'bind': '%s:%s' % ('127.0.0.1', '8080'),
  30. 'workers': number_of_workers(),
  31. }
  32. StandaloneApplication(handler_app, options).run()