为方便项目的分布式部署,可以将flask进行打包,如果使用gunicorn方式,在打包之前需要进行改造:新建一个文件用于gunicorn自定义配置(官方文档)
import multiprocessing
import gunicorn.app.base
def number_of_workers():
return (multiprocessing.cpu_count() * 2) + 1
def handler_app(environ, start_response):
“”“将此方法改造为自己项目的flask app”“”
response_body = b'Works fine'
status = '200 OK'
response_headers = [
('Content-Type', 'text/plain'),
]
start_response(status, response_headers)
return [response_body]
class StandaloneApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
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(),
}
StandaloneApplication(handler_app, options).run()
1、pyinstaller方式
该方式打包出来的文件可以被反编译,如果商用,则不建议使用此方式。
xxx.py为上述新建文件
--onefile 打包为单文件,Linux系统下运行时会在/tmp文件下创建_MEI*文件
--hidden-import 添加额外的依赖模块,pyinstaller在分析项目代码时无法获取到gunicorn的一些调用情况,因此需要主动添加,gunicorn.glogging必须有,gunicorn.workers.gtornado为指定启动模式为tornado时需要添加
pyinstaller --onefile --hidden-import gunicorn.glogging --hidden-import gunicorn.workers.gtornado xxx.py
2、nuitka方式
此工具会先将python代码转换成C代码,再进行编译,可以提高性能和代码安全性,但随着项目代码增多,打包编译时间会越来越长。
xxx.py为上述新建文件
--onefile 打包为单文件,Linux系统下运行时会在/tmp文件下创建onefile_*文件
--include-module 添加额外的依赖模块,如果项目中有用到sqlalchemy,则需要添加sqlalchemy.orm.dependency
python -m nuitka --onefile --show-progress --follow-imports --include-module=gunicorn.glogging --include-module=gunicorn.workers.gtornado --include-module=sqlalchemy.orm.dependency xxx.py