21

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'.

smitop
  • 4,770
  • 2
  • 20
  • 53
BrainVader
  • 383
  • 1
  • 3
  • 7

5 Answers5

34

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)
Seonghyeon Cho
  • 171
  • 1
  • 3
  • 11
Kirell
  • 9,228
  • 4
  • 46
  • 61
8

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
Grey Li
  • 11,664
  • 4
  • 54
  • 64
4

Just as the error message says, do

uvicorn.run("app")

Note also using reload and workers is useless and will just use the reloader. These flags are mutually exclusive

Seonghyeon Cho
  • 171
  • 1
  • 3
  • 11
euri10
  • 2,446
  • 3
  • 24
  • 46
1

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

try using the same way to run a basic script i.e file:variable

ERROR: Error loading ASGI app. Import string "app" must be in format ":".

uvicorn.run("backend.main:app", host="0.0.0.0", port=8000, reload=True, workers=2)
DARK_C0D3R
  • 2,075
  • 16
  • 21
0

Following code works for me

# main.py
import uvicorn
from fastapi import FastAPI

app = FastAPI()

if __name__ == "__main__":
    uvicorn.run("main:app", workers=2)