uvicorn获取404的FastAPI未找到错误

2024-04-29 03:44:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试(失败)设置一个简单的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'}

这是我从终端运行的内容:

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

如你所见,我找不到404。原因可能是什么?一些与网络相关的东西,可能是防火墙/vpn阻止此连接或其他什么?我是新来的。 提前谢谢


Tags: infoapphttphelloworldgetreturndef
2条回答

到现在为止,你可能已经明白了。为了让MWE运行,您需要在每个函数定义之前使用微服务的端点decorators。下面的代码片段应该可以解决您的问题。 它假定您具有以下结构:

.
+  main.py
+  static
|   +  favicon.ico
+  templates
|   +  index.html
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")
    return FileResponse(path=file_path, headers={"Content-Disposition": "attachment; filename=" + file_name})

@app.get('/abc')
def abc_test():
    return{'hello':'abc'}

因此,您可以使用FastAPI默认ASGI服务器运行第一个应用程序

(env)$: uvicorn main:app reload host 0.0.0.0 port ${PORT}

您需要使用这样的装饰器:@app.get('/')。看一下FastAPI Docs

另外,看看装饰师通常是如何工作的,以便更好地了解幕后的工作方式

为您提供的一些资源:

python docs

one of many articles I was able to find

another SO question

相关问题 更多 >