Jan*_*net 3 python fastapi uvicorn
我正在尝试(失败)建立一个简单的 FastAPI 项目并使用 uvicorn 运行它。这是我的代码:
from fastapi import FastAPI
app = FastAPI()
app.get('/')
def hello_world():
return{'hello':'world'}
app.get('/abc')
def abc_test():
return{'hello':'abc'}
Run Code Online (Sandbox Code Playgroud)
这是我从终端运行的:
PS C:\Users\admin\Desktop\Self pace study\Python\Dev\day 14> uvicorn server2:app
INFO: Started server process [3808]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:60391 - "GET / HTTP/1.1" 404 Not Found
INFO: 127.0.0.1:60391 - "GET /favicon.ico HTTP/1.1" 404 Not Found
Run Code Online (Sandbox Code Playgroud)
如您所见,我得到了 404 未找到。可能是什么原因?一些与网络相关的东西,可能是防火墙/VPN 阻止此连接或其他什么?我对此很陌生。提前致谢!
现在你可能已经明白了。为了让 MWE 运行,您需要在每个函数定义之前使用微服务的端点装饰器。以下代码片段应该可以解决您的问题。它假设您具有以下结构:
.
+-- main.py
+-- static
| +-- favicon.ico
+-- templates
| +-- index.html
Run Code Online (Sandbox Code Playgroud)
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import os
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get('/')
def hello_world():
return{'hello':'world'}
@app.get('/favicon.ico')
async def favicon():
file_name = "favicon.ico"
file_path = os.path.join(app.root_path, "static", file_name)
return FileResponse(path=file_path, headers={"Content-Disposition": "attachment; filename=" + file_name})
@app.get('/abc')
def abc_test():
return{'hello':'abc'}
Run Code Online (Sandbox Code Playgroud)
这样您就可以使用 FastAPI 默认 ASGI 服务器运行您的第一个应用程序了。
(env)$: uvicorn main:app --reload --host 0.0.0.0 --port ${PORT}