在使用flask-script的应用上使用gunicorn

两周前,我强烈的想要学习一点新知识,像新的语言,新的框架之类的!好让我的大脑忙碌起来,寻找了一些日子后,我决定学习现在越来越流行的云应用平台(Paas).因为我认为实战比看教程和阅读文档更有效,我决定写一个flask web程序并在Heroku上部署,经过一段时间的学习与编程后,我想要在Gunicorn生产环境中运行它.

那么,怎么让WSGI应用与gunicorn一起运行呢?在一般的情况下是很简单的,只需要运行

gunicorn appmodule:app

这样就ok了,然而我开发时使用了像如下这样的工厂模式:(一个返回Flask程序实例的函数,Flask-Manager就使用了这个模式)

def create_app(environment='development'):
app = Flask(__name__)
...
return app

flask-script提供了一个可以轻松管理你工作环境的方法,例如你可以轻松的通过下面代码运行服务

python manage.py runserver --environment development

你可以通过参数方便的配置程序,就像Heroku通过修改Procfile文件来配置环境一样

web: python manage.py runserver --environment development

这是非常好的解决方案,不幸的是它并没有向flask开发服务的外部提供任何东西,因此我使用gunicorn时不能像下面这样配置代码

python manage.py rungunicorn --environment production --gunicorn-config gunicorn.ini

我唯一能做的是:

gunicorn mymodule:create_app\(environment=\"production\"\)

这太丑了,并切根本没有用到manage.py,完全不能忍,这就是我决定折腾flask-script和gunicorn的原因,在Flask-Action的基础上改写,可以解决我的问题:

class Gunicorn(Command):
description = 'Runs production server with gunicorn' def __init__(self, host='127.0.0.1', port=5000, **options):
self.port = port
self.host = host
self.server_options = options def get_options(self):
options = (
Option('--gunicorn-host',
dest='host',
default=self.host), Option('--gunicorn-port',
dest='port',
type=int,
default=self.port), Option('--gunicorn-config',
dest='config',
type=str,
required=True)) return options def handle(self, app, host, port, config, **kwargs):
from ConfigParser import ConfigParser
gc = ConfigParser()
gc.read(config)
section = 'default' bind = "%s:%s" % (host, str(port))
workers = gc.get(section, 'workers')
pidfile = gc.get(section, 'pidfile')
loglevel = gc.get(section, 'loglevel') # Suppress argparse warnings caused by running gunicorn's argparser
# "inside" Flask-Script which imports it too...
warnings.filterwarnings("ignore", "^.*argparse.*$") from gunicorn import version_info
if version_info >= (0, 9, 0):
from gunicorn.app.base import Application class FlaskApplication(Application):
def init(self, parser, opts, args):
return {
'bind': bind,
'workers': workers,
'pidfile': pidfile,
'loglevel': loglevel
} def load(self):
return app # Hacky! Do not pass any cmdline options to gunicorn!
sys.argv = sys.argv[:2] print "Logging to stderr with loglevel '%s'" % loglevel
print "Starting gunicorn..."
FlaskApplication().run()
else:
raise RuntimeError("Unsupported gunicorn version! Required > 0.9.0")

而gunicorn.ini是这样的:

[default]
workers = 1
pidfile = tmp/districtrank.pid
loglevel = debug

tips

  1. 因为gunicornn也使用了argparse,所以如果我移除了Manager的sys.argv参数 gunicorn就会崩溃.也许还有更好的解决方案,但对我的需求来说已经完全足够了.

  2. 因为一些关于import的原因,需要清空输出,所以我禁止了argparse的警告,禁止警告虽然不好,但是我认为在这种情况下是可以理解的

    manager.add_command("rungunicorn", Gunicorn(host=host,port=port))

现在你可以使用新创建的指令来配置了

这肯定不是一段可以合并到Flask-Script的代码(迎合了我的需求,但是不是太通用,而且使用了丑陋的sys.argv并且禁止了argparse的导入警告),但是它也能正确的运行,所以我在guniorn中使用了

python manage.py rungunicorn --environment production --gunicorn-config gunicorn.ini

Works for me!

(翻译玩)在使用flask-script的应用上使用gunicorn的更多相关文章

  1. flask+script命令行交互工具

    Project name :Flask_Plan templates:templates static:static 首先说,我们flask比django方便的地方是所有的模块都可以自己选,你不喜欢s ...

  2. Flask script 内的Shell 类 使用

    1.集成Python shell 每次自动shell会话都要导入数据库实例和模型,很烦人.为了避免一直重复导入,我们可以做些配置让Flask-Script的Shell命令自动导入特定的对象.若想把对象 ...

  3. (翻译玩)SQLALchemy backref章节文档

    Linking Relationships with Backref 自从在Object Relational Tutorial中第一次提到backref参数后,许多案例中也用到了backref,那么 ...

  4. 翻译 | 玩转 React 表单 —— 受控组件详解

    原文地址:React.js Forms: Controlled Components 原文作者:Loren Stewart 译者:小 B0Y 校对者:珂珂君 本文涵盖以下受控组件: 文本输入框 数字输 ...

  5. Flask deployment on gunicorn with flask script

    https://stackoverflow.com/questions/34265870/flask-deployment-on-gunicorn-with-flask-script 依赖 Flask ...

  6. dropzonejs中文翻译手册 DropzoneJS是一个提供文件拖拽上传并且提供图片预览的开源类库.

    http://wxb.github.io/dropzonejs.com.zh-CN/dropzonezh-CN/ 由于项目需要,完成一个web的图片拖拽上传,也就顺便学习和了解了一下前端的比较新的技术 ...

  7. Flask下如何处理Requests 上传中文文件名的问题

    一.问题的由来     最近有个项目,叫做文档服务资源中心,类似于七牛,为各个业务系统提供统一的文件资源服务,包括文件的存储.操作管理.下载.预览等.在做文件存储的时候,遇到了这个当指定上传的文件名为 ...

  8. [小北De编程手记] : Lesson 03 玩转 xUnit.Net 之 Fixture(上)

    在使用xUnit.Net Framework构建单元测试或自动化测试项目的时候,无论是针对一些比较耗费资源的对象亦或是为了支持Test case预设数据的能力,我们都需要有一些初始化或是清理相关的动作 ...

  9. flask中下载服务器上特定路径的文件

    使用flask下载服务器上某个路径下的文件 path:文件路径以及需要下载的文件,直接写入参数有安全隐患,实际应用中需要判断权限之类的 from flask import send_file, mak ...

随机推荐

  1. weblogic使用脚本部署

    --本机 (/common/bin/wlst.sh (2)connect('weblogic','weblogic1','t3://localhost:7001') (3)progress=deplo ...

  2. Spring 定时任务之 @Scheduled cron表达式

    一个基于Spring boot的一个demo: Java配置中开户对Scheduled的支持 import org.springframework.context.annotation.Configu ...

  3. 【HDOJ】1732 Push Box

    BFS.使用当前结点位置以及三个箱子的位置作为状态. #include <iostream> #include <cstdio> #include <cstring> ...

  4. 2014-07-29 浅谈MVC框架中Razor与ASPX视图引擎

    今天是在吾索实习的第15天.随着准备工作的完善,我们小组将逐步开始手机端BBS的开发,而且我们将计划使用MVC框架进行该系统的开发.虽然我们对MVC框架并不是非常熟悉,或许这会降低我们开发该系统的效率 ...

  5. C语言--对数组地址的解析

    在C编程中,我们进程会用到数组,这看起来很简单,因为,数组就是存储相同类型元素的集合嘛,不过,当你还没考虑到数组的地址问题时,一切都是简单的,如果你接触了数组中的地址概念,也许你会改变你的想法. 下面 ...

  6. OpenCV中OpenCL模块函数

    It currently develop and test on GPU devices only. This includes both discrete GPUs(NVidia,AMD), as ...

  7. Apache+Subversion+TortoiseSVN

    Key words: dav_svn, apache, subversion, tortoisesvn # install apache2 sudo apt-get install libapache ...

  8. linux串口驱动分析

    linux串口驱动分析 硬件资源及描写叙述 s3c2440A 通用异步接收器和发送器(UART)提供了三个独立的异步串行 I/O(SIO)port,每一个port都能够在中断模式或 DMA 模式下操作 ...

  9. openstack单元測试用组件一览

    声明: 本博客欢迎转发,但请保留原作者信息! 博客地址:http://blog.csdn.net/halcyonbaby 内容系本人学习.研究和总结,如有雷同,实属荣幸! 组件一览 hacking 一 ...

  10. UI Prototype Design IDE( 界面原型设计工具 )

    UI Prototype Design IDE( 界面原型设计工具 )   如何用工具去与客户进行交流,互动,定义要做的系统,什么什么的... 0.Balsamiq Mockups http://ww ...