Login
网站首页 > 文章中心 > 其它

FastApi如何快速构建一个web项目的实现

作者:小编 更新时间:2023-09-20 18:00:44 浏览量:363人看过

FastAPI 是一个基于 asyncio 和 pydantic 的现代化 Web 框架,提供了快速开发高性能且易于扩展的 API 工具.适合用于构建现代高性能 Web 服务 API、机器学习应用等等场景.下面将详细讲解如何使用FastAPI快速构建一个Web项目的实现.

FastAPI可以通过pip安装,安装FastAPI的同时也会自动安装uvicorn,这是一个一款轻量级的Python ASGI服务器,用于部署FastAPI应用程序.


pip install fastapi


使用FastAPI创建一个新项目非常方便,只需要创建一个文件并且引入FastAPI即可.下面是一个最简单的例子:


from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def index():
return {"message": "Hello World"}


引入FastAPI并创建一个FastAPI实例;

使用装饰器@app.get()指定路由路径和HTTP请求方法;

定义一个异步函数index(),对请求进行处理;

发回一个JSON格式的响应.

对于一个Web项目而言,路由非常重要.FastAPI提供了装饰器@app.route()和@app.get(),来指定支持的URL路由和HTTP请求方法.


from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def index():
return {"message": "Hello World"}

@app.get("/items/{id}")
async def read_item(id: int):
return {"id": id, "name": "Sample Item"}


在许多场景下,请求需要包含一些输入数据,比如,用户表单提交,或者发送到 Web 服务的 JSON 数据.在 FastAPI 中,已经可以通过包含参数来处理这样的输入数据,但是如果我们要发送一个大型的JSON数据,可以使用pydantic.BaseModel.


from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None

@app.post("/items/")
async def create_item(item: Item):
item_dict = item.dict()
if item.is_offer:
    item_dict.update({"message": "Special offer"})
return item_dict


BaseModel是pydantic库提供的一个与FastAPI紧密集成的数据验证工具,可以用来定义API的输入和输出类型.在上面土嘎嘎给出的例子源码中,我们使用pydantic.BaseModel定义了一个数据模型Item,其中包含名称、价格和是否优惠等字段,is_offer是个可选的布尔型参数.app.post()用来指定HTTP请求的方法为POST.

FastAPI自带OpenAPI和JSON Schema支持,可以自动为API生成详细可读的文档.


from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None

@app.post("/items/")
async def create_item(item: Item):
item_dict = item.dict()
if item.is_offer:
    item_dict.update({"message": "Special offer"})
return item_dict

@app.get("/")
async def index():
return {"message": "Hello World"}

@app.get("/items/{id}")
async def read_item(id: int):
return {"id": id, "name": "Sample Item"}

# 1. 添加文档
@app.get("/docs")
async def get_docs():
return {"message": "Docs"}

# 2. 添加API版本
@app.get("/v1/items/{id}")
async def read_item_v1(id: int):
return {"id": id, "name": "Sample Item"}



在上面的代码里,我们针对/docs路径定义一个路由,直接返回文档. FastAPI 的自动文档工具将扫描路由映射并生成相应的文档页面.

中间件通常是一些可以在 HTTP 请求处理过程中执行的拦截器. FastAPI 提供了一个很方便的中间件系统,我们只需要通过 FastAPI 的 API 即可添加中间件.


from fastapi import FastAPI, Request

app = FastAPI()

# 1. 添加中间件
@app.middleware("http")
async def add_custom_header(request: Request, call_next):
response = await call_next(request)
response.headers["X-Custom-Header"] = "demo"
return response

# 2. 添加路由
@app.get("/")
async def index():
return {"message": "Hello World"}

@app.get("/items/{id}")
async def read_item(id: int):
return {"id": id, "name": "Sample Item"}


第一步,我们定义了一个中间件函数add_custom_header(),此中间件会在处理 HTTP 请求时拦截请求和响应.其中call_next()则是调用下一个中间件或路由处理程序,这个函数必须在中间件之后使用.在函数中,我们向 HTTP 响应 header 添加了一个自定义的 X-Custom-Header 头部.

第二步,我们定义了两个路由,其中一个是根路径,一个是一个动态路径.

此时此刻呢,我们使用这个框架来完成一个表单提交的应用.


from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse

app = FastAPI()

# 中间件,拦截请求和响应
@app.middleware("http")
async def add_custom_header(request: Request, call_next):
response = await call_next(request)
response.headers["X-Custom-Header"] = "demo"
return response

# 返回Home页面
@app.get("/", response_class=HTMLResponse)
async def home():
html_content = """

    
        FastAPI Form
    
    
        


""" return html_content # 表单提交路由 @app.post("/form") async def submit_form(name: str = Form(...), email: str = Form(...)): return {"message": f"{name} Submitted successfully with {email}"}

下面这个例子是一个计算器应用,包含两个接口:加法和减法.


from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class CalcRequest(BaseModel):
first: int
second: int

class CalcResult(BaseModel):
result: int

# 加法接口
@app.post("/add", response_model=CalcResult)
async def add(req: CalcRequest):
return CalcResult(result=req.first ◆ req.second)

# 减法接口
@app.post("/sub", response_model=CalcResult)
async def subtract(req: CalcRequest):
return CalcResult(result=req.first - req.second)


CalcRequest类是输入数据的数据类型,它定义了两个整数数据first和second.CalcResult是输出数据的数据类型,它只包含一个字段result,表示计算结果.

两个路由都使用了@app.post()装饰器,DataFrame中定义的数据模型作为第一个参数进行传递.输出模型从CalcResult中指定,以确保输出结果合规.

以上就是土嘎嘎小编为大家整理的FastApi如何快速构建一个web项目的实现相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!

版权声明:倡导尊重与保护知识产权。未经许可,任何人不得复制、转载、或以其他方式使用本站《原创》内容,违者将追究其法律责任。本站文章内容,部分图片来源于网络,如有侵权,请联系我们修改或者删除处理。

编辑推荐

热门文章