这几天上手体验 FastAPI,感受到这个框架易用和方便。今天继续分享一些技巧。
- from fastapi import FastAPI
-
- app = FastAPI()
-
- @app.get('/')
- def home():
- return {'message': 'hello world'}
-
- import uvicorn
- uvicorn.run(app)
-
我们可以运行这个 .py 文件,然后在浏览器中访问 localhost:8000/。
- from fastapi import FastAPI
-
- app = FastAPI()
-
- @app.get('/')
- def home():
- return {'message': 'hello world'}
-
- @app.get('/hello')
- def home():
- return {'message': 'hello hello'}
-
- import uvicorn
- uvicorn.run(app)
-
如果我们运行这个文件并访问 localhost:8000/docs,我们会看到一个包含所有 API 端点的 Swagger UI。
使用这个 Swagger UI,我们可以在开发时轻松测试我们的端点。
- from fastapi import FastAPI
- from pydantic import BaseModel
-
- app = FastAPI()
-
- class MyPayload(BaseModel):
- name: str
- age: int
- email: str
-
- @app.post('/test')
- def test(mypayload: MyPayload):
- return {'payload': mypayload.dict(), 'status':'ok'}
-
- import uvicorn
- uvicorn.run(app)
-
当我们创建一个 POST 端点时,我们需要定义有效负载包含的数据类型。我们使用 pydantic 的 BaseModel 来实现这一点。
在这里,我们创建了一个名为 MyPayload 的类,它继承自 BaseModel,MyPayload 代表传递给我们的 POST 端点的有效负载。这意味着我们在进行 POST 请求时必须在 MyPayload 中定义的内容。
这对于确保我们定义的数据类型被遵循是有用的。
- from fastapi import FastAPI, UploadFile
-
- app = FastAPI()
-
- @app.post('/upload_image')
- def test(images: list[UploadFile]):
- print(images)
- return {'status':'ok'}
-
- import uvicorn
- uvicorn.run(app)
-
为了启用文件上传(大多数文件类型),我们只需要让我们的 POST 请求接受一个 UploadFile,它是从 fastapi 中导入的。
这使我们能够上传多个文件/图片等。
URL 参数和查询参数都很有用,下面是在 FastAPI 中区分它们的方法。
- from fastapi import FastAPI
- import asyncio
-
- app = FastAPI()
- x = [1]
-
- @app.get('/x')
- def hello():
- return {'x':x}
-
- async def periodic():
- while True:
- x[0] += 1
- print(f"x is now {x}")
- await asyncio.sleep(2)
-
- @app.on_event("startup")
- async def schedule_periodic():
- loop = asyncio.get_event_loop()
- loop.create_task(periodic())
-
- if __name__ == "__main__":
- import uvicorn
- uvicorn.run(app)
-
在 periodic() 中,每 2 秒我们会将 x[0] 增加 1。
@app.on_event(‘startup’) 表示 FastAPI 应用程序启动时发生的事件。
schedule_periodic 在 FastAPI 应用程序启动时发生,因此 periodic 作为后台任务在后台运行。
当我们的应用程序变得更大时,我们可能需要使用多个路由器来更轻松地管理路由。
- from fastapi import FastAPI
-
- app = FastAPI()
-
- @app.get('/')
- def home():
- return {'msg': 'home'}
-
- from b import myrouter
-
- app.include_router(myrouter)
-
- import uvicorn
- uvicorn.run(app)
-
在其他文件中,我们使用 APIRouter 的一个实例。
我们像处理 app 一样处理这个实例。
在我们的主文件 app.py 中,我们需要使用 .include_router 方法注册其他路由器中的内容。