在本文中,我将向您介绍 API 概念、FastAPI 游戏规则改变者功能,并使用 FastAPI 为我们的机器学习数据产品提供服务。
什么是 API?
应用程序编程接口( API ) 是两个或多个应用程序相互通信的软件接口。
了解什么是 API 的最简单方法是想想你自己在一家餐馆。您进入餐厅,找到您的餐桌,然后收到一份菜单。菜单上有食物的名称、描述和费用。您选择组合并下订单。但是您的要求将如何传递给厨师?厨师不能来用餐区,你也不能去厨房。您需要有人收到您的请求并将其送到厨房,然后在饭菜准备好后将其带到您的餐桌上。是的,您需要服务员!
同步 API 调用是一种设计模式,其中调用站点在等待被调用代码完成时被阻塞。使用异步 API 调用时,调用站点不会在等待被调用代码完成时被阻塞,而是在响应到达时通知调用线程。
在较重的负载条件下,提交多个异步调用并定期检查状态比等待每个调用完成再提交下一个调用更有效。
from fastapi import FastAPI
app = FastAPI()
async def get_restaurant_working_hours(): # some operations pass
@app.get("/") async def get_resturant_reservation_details(): results = await restaurant_working_hours() # waits for the defined function # some operations
from typing import Optional from fastapi import FastAPI, Query import uvicorn app = FastAPI()
@app.get("/orders/") async def read_items(order_count: int = Query(gt=1, lt=100)): # defining the constraints results = {"order_count": order_count} return results
if __name__ == "__main__": uvicorn.run("parameter-validations:app")
与 Pydantic 集成
Pydantic是一个用于执行数据序列化和验证的 Python 库。
FastAPI 与Pydantic集成。这确保在运行时通过 IDE 解析、评估并通知用户有关类型相关的错误。
您可以在下面找到示例错误消息;
fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that False is a valid Pydantic field type. If you are using a returntype annotation that is not a valid Pydantic field (e.g. Union[Response, dict, None]) you can disable generating the response model from the type annotation with the path operation decorator parameter response_model=None. Read more: https://fastapi.tiangolo.com/tutorial/response-model/