当前位置: 代码迷 >> 综合 >> utils系列:pyinstaller 打包 以gunicorn启动的Flask
  详细解决方案

utils系列:pyinstaller 打包 以gunicorn启动的Flask

热度:30   发布时间:2023-12-15 00:31:41.0

首先是你要打包的Flask服务的py文件

app.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from hello import hallo
from flask import Flask
app = Flask(__name__)@app.route('/')
def hello():return 'hello world'application = app#以gunicorn 启动的Flask不会走main方法所以下面的可以注释掉if __name__=="__main__":app.run()

上面的Flask不再是程序的入口了,下面的gunicorn才是打包程序的入口

gunicorn.py   里面包含了gunicorn的一些配置项。就不过多解释了

#!/usr/bin/env python3from gunicorn.app.base import BaseApplicationclass Application(BaseApplication):def load_config(self):s = self.cfg.sets('bind', "0.0.0.0:18000")s('workers', 1)s('timeout', 30)s('accesslog', "/opt/test_gun/log/gunicorn_access.log")s('errorlog', "/opt/test_gun/log/gunicorn_error.log")s('access_log_format', '%(t)s %(h)s "%(r)s" %(s)s %(b)s %(D)s "%(a)s"')def load(self):from app import applicationreturn applicationif __name__ == '__main__':Application().run()

好了 完事具备,只欠东风

可以直接在命令行敲:

pyinstaller -F gunicorn.py --name gun  --hidden-import gunicorn.glogging --hidden-import gunicorn.workers.sync

或者写

bash.sh

pyinstaller -F gunicorn.py --name gunicorn \ --hidden-import=gunicorn.glogging \--hidden-import=gunicorn.workers.sync

打包完会生成dist的文件夹 运行文件gunciron就在里面 直接./gunicorn 就可以运行

注意打包前一定要先把程序跑起来,防止有些环境变量没有加载到包里