记一次踩坑uvicorn的打包过程
首先
新建文件夹log
然后业务模块:main.py
import logging
import traceback
from fastapi import FastAPI
import time
app = FastAPI()
config = util.loadConfig()
logging.basicConfig(filename='log/{}.txt'.format(time.strftime('%Y-%m-%d', time.localtime())),
format='%(asctime)s %(message)s', level=logging.DEBUG)
@app.get(path='/hello/{userid}') # user_id 就是路径参数
async def find_user(userid: str):
logging.info('hello,uvicorn')
return {'message':'hello,uvicorn'+' '+userid}
运行模块:run_server.py(提个醒,uvicorn 运行参数reload要设成False,不然打包后运行会一直重启)
import uvicorn
if __name__ == '__main__':
uvicorn.run("main:app", reload=False, host="127.0.0.1", port=8002)
然后开始执行打包,打包运行模块run_server.py
pyinstaller -F run_server.py
在dist文件夹下会得到一个exe文件
虽然生成了exe文件,但是那个文件运行是会报错的
因为依赖还没有一起打包进去
第二步
编辑run_server.spec
找到hiddenimports=[]
把uvicorn的依赖加进去
如果有其他第三方依赖的话也要加到这里,例如业务代码里用到的fastapi
hiddenimports=['fastapi','uvicorn.lifespan.off','uvicorn.lifespan.on','uvicorn.lifespan',
'uvicorn.protocols.websockets.auto','uvicorn.protocols.websockets.wsproto_impl',
'uvicorn.protocols.websockets_impl','uvicorn.protocols.http.auto',
'uvicorn.protocols.http.h11_impl','uvicorn.protocols.http.httptools_impl',
'uvicorn.protocols.websockets','uvicorn.protocols.http','uvicorn.protocols',
'uvicorn.loops.auto','uvicorn.loops.asyncio','uvicorn.loops.uvloop','uvicorn.loops',
'uvicorn.logging']
然后如果有一些自己写的依赖也要加进去,例如这里我们自己写的业务模块main.py
找到datas=[]
把业务模块的地址加进去
datas=[('F:\\test\\main.py','.')]
保存
第三步
在执行打包命令前,先把build文件夹删掉,避免打包设置没有更新
然后执行打包命令
pyinstaller run_server.spec
最后
测试,执行exe文件
打开浏览器访问
ok