FastApi(三)

Form表单:

# -*- coding: utf-8 -*-

from fastapi import FastAPI, Form, File, UploadFile, status, HTTPException
from typing import List
import uvicorn

"""FastAPI应用的常见配置项"""
app = FastAPI(
    title='2021年3月21日',
    description='不愿染事与非 怎料事与愿违 心中的花枯萎 它一去不回',
    version='1.0.0',
    docs_url='/docs',
    redoc_url='/redocs'
)

@app.post("/form/login/")
async def login(user: str = Form(...), password: str = Form(...)):
    """用Form类需要pip install python-multipart"""
    return {"user": user}

@app.post("/files/")
async def create_file(file: bytes = File(...)):
    """如果要上传多个文件 file: List[bytes] = File(...)
    async def create_files(files: List[bytes] = File(...)):
    """
    return {"file_size": len(file)}

@app.post("/upload_files/")
async def file_send(files: List[UploadFile] = File(...)):
    """
    如果要上传单个文件 file: UploadFile = File(...)
    1、文件存储在内存中,使用的内存达到阈值后,将被保存在磁盘中
    2、适合于图片、视频大文件
    3、可以获取上传的文件的元数据,如文件名、创建时间等
    4、有文件对象的异步接口
    5、上传的文件是Python文件对象,可以使用write()、read()、seek()、close()操作
    """
    for file in files:
        contents = await file.read()
    return {"filename": files[0].filename, "content_type": files[0].content_type}

@app.post("/path_op_conf/",
          response_model=None,
          # tags=["Path", "op", "conf"],
          summary="This is summary",
          description="This is description",
          # deprecated=True,
          status_code=status.HTTP_200_OK
          )
async def path_op_conf(casedata: dict):
    if casedata == {}:
        raise HTTPException(status_code=404, detail='casedata 不能为空', headers={'X-Error': 'There goes my error'})
    return casedata

"""
    app.mount()挂载
"""

if __name__ == '__main__':
    uvicorn.run('888:app', host='0.0.0.0', port=8081, reload=True, debug=True, workers=1)  #app即fastapi实例的名称

依赖:

# -*- coding: utf-8 -*-

from fastapi import FastAPI, Depends, HTTPException, Header
from typing import Optional
import uvicorn

app = FastAPI(title='2021年3月21日')

"""函数作为依赖"""
async def common_parameters(q: Optional[str] = None, page:int=1, limit: int = 10):
    return {"q": q, "page": page, "limit": limit}

@app.get("/function_dependency_async")
async def function_dependency_async(commons: dict = Depends(common_parameters)):
    """Depends内传入的是函数名称,不带()"""
    return commons

@app.get("/function_dependency")
def function_dependency(commons: dict = Depends(common_parameters)):
    """依赖不区分同步异步"""
    return commons

"""类作为依赖"""
class CommonQueryParams:
    def __init__(self,q: Optional[str] = None, page:int=1, limit: int = 10):
        self.q = q
        self.page = page
        self.limit = limit

@app.get("/class_dependency")
async def class_dependency(commons=Depends(CommonQueryParams)):
    """
    三种写法:
    async def class_as_dependency(commons: CommonQueryParams = Depends(CommonQueryParams)): 依赖的类=Depends(依赖的类)
    async def class_as_dependency(commons: CommonQueryParams = Depends()):依赖的类=Depends()
    async def class_as_dependency(commons=Depends(CommonQueryParams)):=Depends(依赖的类)
    """
    response = {}
    if commons.q:
        response.update({"q": commons.q})
    if commons.page:
        response.update({"page": commons.page})
    return response

"""子依赖"""
def query(q: Optional[str] = None):
    pass
    return q

def sub_query(q: str = Depends(query), last_query: Optional[str]=None):
    if q:
        return q
    return last_query

@app.get("/sub_dependency/")
async def sub_denpency(final_query: str = Depends(sub_query, use_cache=True)):
    return {"sub_dependency": final_query}

"""路径操作装饰器中的多依赖"""
async def verify_token(x_token: str = Header(...)):
    if x_token == "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="x_token header invalid")
    return x_token

async def verify_key(x_key: str = Header(...)):
    if x_key == "fake-super-secret-key":
        raise HTTPException(status_code=400, detail="x_key header invalid")
    return x_key

@app.get("/dependency_in_path_op", dependencies=[Depends(verify_token), Depends(verify_key)])
async def dependency_in_path_op():
    return {"红玫瑰": "得不到的永远在骚动", "白玫瑰": "被偏爱的都有恃无恐"}

"""
全局依赖
app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
"""

if __name__ == '__main__':
    uvicorn.run('888:app', host='0.0.0.0', port=8081, reload=True, debug=True, workers=1)  #app即fastapi实例的名称

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值