Last active
January 22, 2024 06:00
-
-
Save KatiRG/2bdf792893bb475ae8debef87002e02c to your computer and use it in GitHub Desktop.
Running Flask with Gunicorn
This file contains 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() |
Glad it has helped! Thanks for the feedback.
This should probably be in the main docs, thank you!
Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you.