简体   繁体   中英

Uvicorn/FastAPI executable

I created a basic application for personal use. The backed of my application uses Fast Api with a SQLite database. Usually to run my start up and run my backend server I have to use the following commands:

// Using Virtual ENV
source env/Scripts/activate

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

I have seen other people create a python executable before. I would like to do the same but I need it to start the uvicorn server. How do I create a python executable that runs a uvicorn server?

Or is it better to just write a batch script that does this?

Somthing like

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()

If you need to pass arguments you can use something like argparse/click to expose a cli interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM