-
-
Save alertor/7f103b0ea4554148915d05ecd275eca9 to your computer and use it in GitHub Desktop.
Running Flask with Gunicorn
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment