Как запустить сервер Uvicorn FastAPI как модуль из другого файла Python?Python

Программы на Python
Anonymous
Как запустить сервер Uvicorn FastAPI как модуль из другого файла Python?

Сообщение Anonymous »

Я хочу запустить сервер FastAPI с использованием Uvicorn из другого файла Python.
uvicornmodule/main.py

Код: Выделить всё

import uvicorn
import webbrowser
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles

app = FastAPI()

import os
script_dir = os.path.dirname(__file__)
st_abs_file_path = os.path.join(script_dir, "static/")
app.mount("/static", StaticFiles(directory=st_abs_file_path), name="static")

@app.get("/")
async def index():
return FileResponse('static/index.html', media_type='text/html')

def start_server():
# print('Starting Server...')

uvicorn.run(
"app",
host="0.0.0.0",
port=8765,
log_level="debug",
reload=True,
)
# webbrowser.open("http://127.0.0.1:8765")

if __name__ == "__main__":
start_server()
Итак, я хочу запустить сервер FastAPI из приведенного ниже файла test.py:

Код: Выделить всё

from uvicornmodule import main
main.start_server()
Затем я запускаю python test.py.
Но получаю следующую ошибку:

Код: Выделить всё

RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.

This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:

if __name__ == '__main__':
freeze_support()
...

The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
Что я делаю не так? Мне нужно запустить этот модуль как пакет.

Подробнее здесь: https://stackoverflow.com/questions/739 ... ython-file

Вернуться в «Python»