Uvicorn/FastAPI可执行文件

2024-03-28 15:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个供个人使用的基本应用程序。我的应用程序的后台使用FastAPI和SQLite数据库。通常,要运行启动和后端服务器,我必须使用以下命令:

// Using Virtual ENV
source env/Scripts/activate

pip install -r requirements.txt
uvicorn main:app --reload

我以前见过其他人创建python可执行文件。我也想这样做,但我需要它来启动uvicorn服务器。如何创建运行uvicorn服务器的python可执行文件

还是只编写一个执行此操作的批处理脚本更好


Tags: 命令服务器env数据库应用程序可执行文件sourcesqlite
1条回答
网友
1楼 · 发布于 2024-03-28 15:22:13

糟糕的

import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

#  Import A module from my own project that has the routes defined
from redorg.routers import saved_items 

origins = [
    'http://localhost:8080',
]


webapp = FastAPI()
webapp.include_router(saved_items.router)
webapp.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)


def serve():
    """Serve the web application."""
    uvicorn.run(webapp)

if __name__ == "__main__":
    serve()

如果需要传递参数,可以使用argparse/click之类的方法公开cli接口

相关问题 更多 >