fastapi

if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app="tutorial004:app", host="127.0.0.1", port=80, reload=True, debug=True)
Body

Body(参数1, 参数2)

参数1:如果为 …(必填) None(非必填) 【Path, Field的这个参数也一样】

参数2:embed(默认为False) = True时,请求的参数要以item(就是你设定的键)

如图所示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4LxiIxSL-1672889315005)(D:\study\typora_file\typora_img\image-20220311110948199.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-al0oJLpr-1672889315007)(D:\study\typora_file\typora_img\image-20220311111234691.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7qIjnJtg-1672889315007)(D:\study\typora_file\typora_img\image-20220311111528454.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1XVB9hnH-1672889315007)(D:\study\typora_file\typora_img\image-20220311111728374.png)]

from typing import Optional

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[str] = None

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(None, embed=True)):
    results = {"item_id": item_id, "item": item}
BackgroundTasks 实现后台任务

实现后台任务【用户请求,立即返回结果,后台依旧继续执行】

我觉得用到的地方:【爬虫中】用户查询某个商品的信息(你先在数据库查询是否存在,没有即调用接口获取信息)立即返回用户,后面把信息存入数据库(省的用户还要等待你插入数据的时间)

import time

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

# 后台运行任务
def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        for i in range(10):
            print(i)
            time.sleep(2)
            content = f"notification {i} for {email}: {message}\n"
            email_file.write(content)


# 前端调用接口
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}
RedirectResponse 跳转链接

请求该路由会直接跳转到指定的链接

from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()


@app.get("/typer")
async def redirect_typer():
    return RedirectResponse("https://typer.tiangolo.com")

@app.get("/fastapi", response_class=RedirectResponse)
async def redirect_fastapi():
    return "https://fastapi.tiangolo.com"

@app.get("/pydantic", response_class=RedirectResponse, status_code=302)
async def redirect_pydantic():
    return "https://pydantic-docs.helpmanual.io/"

ode=302)
async def redirect_pydantic():
return “https://pydantic-docs.helpmanual.io/”


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值