Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run FastAPI application from Poetry?

I have a fastapi project built by poetry. I want to run the application with a scripts section in pyproject.tom like below:

poetry run start

What is inside double quotes in the section?

[tool.poetry.scripts]
start = ""

I tried to run the following script.

import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

def main():
    print("Hello World")
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=True, workers=2)

if __name__ == "__main__":
    main()

It stops the application and just shows warning like this.

WARNING: You must pass the application as an import string to enable 'reload' or 'workers'.

like image 258
BrainVader Avatar asked Sep 09 '20 10:09

BrainVader


2 Answers

I found the solution to this problem. See below:

In pyproject.toml

[tool.poetry.scripts]
start = "my_package.main:start"

In your main.py inside my_package folder.

import uvicorn
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

def start():
    """Launched with `poetry run start` at root level"""
    uvicorn.run("my_package.main:app", host="0.0.0.0", port=8000, reload=True)
like image 114
Kirell Avatar answered Sep 19 '22 00:09

Kirell


You will need to pass the module path (module:function) to the start script in project.toml:

[tool.poetry.scripts]
start = "app:main"

Now run the command below will call the main function in the app module:

$ poetry run start
like image 41
Grey Li Avatar answered Sep 20 '22 00:09

Grey Li