-
-
Save YUChoe/ac4bfd0a5e34f1aca367f1d874617228 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
# coding: utf-8 | |
# 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 | |
from gunicorn import util | |
import flask_app | |
# # flask_app.py | |
# | |
# import logging | |
# from flask import Flask | |
# | |
# app = Flask(__name__) | |
# logger = logging.getLogger('gunicorn.error') | |
# stdout_handler = logging.StreamHandler() | |
# logger.addHandler(stdout_handler) | |
# | |
# @app.route('/') | |
# def this_app(): | |
# return "<h3>Hello</h3>" | |
# | |
# if __name__ == '__main__': | |
# app.run() | |
def number_of_workers(): | |
return (multiprocessing.cpu_count() * 2) + 1 | |
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 | |
def run(self): | |
if self.cfg.daemon: | |
util.daemonize(self.cfg.enable_stdio_inheritance) | |
super(StandaloneApplication, self).run() | |
if __name__ == '__main__': | |
log_format = logging.Formatter('%(asctime)s : %(message)s') | |
file_handler = RotatingFileHandler('/var/log/gapi.log', maxBytes=2000, backupCount=5) | |
file_handler.setFormatter(log_format) | |
flask_app.logger.addHandler(file_handler) | |
options = { | |
'certfile': '/var/log/cert.crt', | |
'keyfile': '/var/log/cert.key', | |
'workers': number_of_workers(), | |
'bind': '%s:%s' % ('127.0.0.1', '35080'), | |
'daemon': False, | |
} | |
app = flask_app.app | |
StandaloneApplication(app, options).run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment