Skip to content

Instantly share code, notes, and snippets.

@KatiRG
Last active January 22, 2024 06:00
Show Gist options
  • Save KatiRG/2bdf792893bb475ae8debef87002e02c to your computer and use it in GitHub Desktop.
Save KatiRG/2bdf792893bb475ae8debef87002e02c to your computer and use it in GitHub Desktop.
Running Flask with Gunicorn
# This gist shows how to integrate Flask into a
# custom Gunicorn-WSGI application described
# here: http://docs.gunicorn.org/en/stable/custom.html
from __future__ import unicode_literals
import multiprocessing
import gunicorn.app.base
from gunicorn.six import iteritems
# Modification 0: import Flask modules
from flask import Flask, render_template, make_response, request, Response #etc
def number_of_workers():
return (multiprocessing.cpu_count() * 2) + 1
# Modification 1: Define Flask app
app = Flask(__name__)
# Modification 2: Define your own Flask app routes and functions
@app.route('/')
def index():
return render_template('index.html')
class StandaloneApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super(StandaloneApplication, self).__init__()
def load_config(self):
config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for key, value in iteritems(config):
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == '__main__':
options = {
'bind': '%s:%s' % ('127.0.0.1', '8080'),
'workers': number_of_workers(),
}
# Modification 3: pass Flask app instead of handler_app
StandaloneApplication(app, options).run()
@YUChoe
Copy link

YUChoe commented Jun 12, 2018

Thank you very much! It works well.

Copy link

ghost commented Aug 26, 2018

Thank you.

@KatiRG
Copy link
Author

KatiRG commented Sep 9, 2018

Glad it has helped! Thanks for the feedback.

@carlomazzaferro
Copy link

This should probably be in the main docs, thank you!

@danmutblix
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment