FastAPI请求系列(四) Request Cookie/Header/Form/File

一、Cookie

Cookie的定义与声明与Query和Path类似:

from typing import Optional
from fastapi import Cookie, FastAPI

app = FastAPI()


@app.get("/items/")
async def read_items(ads_id: Optional[str] = Cookie(None)):
    return {"ads_id": ads_id}

此处需要使用Cookie来进行声明,否则将会被解析为查询参数。那么这样应该如何进行测试呢?此处可以使用postman进行测试:

注意在Headers中key是Cookie,否则将会被解析为Header参数。

二、Header

 Header与之前的Cookie使用一样:

from typing import Optional, List
from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(user_agent: Optional[str] = Header(None, convert_underscores=True), x_token: List[str] = Header(None)):
    return {"User-Agent": user_agent, "x_token": x_token}

需要使用Header来进行声明,否则就会将其作为查询参数。

  • convert_underscores 是为了解决有些HTTP代理和服务器是不允许在请求头中带有下划线的,所以Header提供convert_underscores属性让设置,默认是True,也就是FastAPI会自动转换
  • x_token 请求头参数可以接受多个值,以列表的形式接收,其表现形式如下。

三、表单数据

   上述接受的请求数据是json类型的,当需要接受并且处理表单数据时使用Form,不过在使用时注意是否已经安装python-multipart第三方包,如果没有安装,可以通过pip安装:

pip install python-multipart

  比如,在登录时提交用户名和密码的表单数据到后台进行验证,FastAPI对于表单Form的使用与Body/Query/Path/Cookie相同。

from fastapi import FastAPI, Form

app = FastAPI()


@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username}

这样在api中使用时显然media-type与之前application/json不同:

四、文件上传

在进行文件上传之前,需要确定是否已经安装python-multipart第三方包,如果没有安装,可以通过pip安装:

pip install python-multipart

因为上传的文件是以“form data”的形式向后台发送的。

1、小文件上传

  • 单个文件上传
from fastapi import FastAPI, File


app = FastAPI()


@app.post("/file/")
async def create_file(file: bytes = File(...)):return {"file_size": len(file)}

  通过File来进行声明,这样file参数就不会被当作查询参数或者请求体参数。在路径操作函数中声明bytes类型,这样接收的就是bytes类型,并且写入到内存,所以适合于小文件上传。

  • 多个文件上传

多个文件上传就是bytes类型定义为List[bytes]即可:

from typing import List
from fastapi import FastAPI, File

app = FastAPI()


@app.post("/multi/file/")
async def create_multi_file(file: List[bytes] = File(...)):
    return {"file_size": len(file)}

如图所示:

 2、大文件上传

  • 单个文件上传
from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/uploaadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

使用UploadFile的优势:

(1)文件存储在内存中,使用的内存达到阈值后,将被保存在磁盘中

(2)适合于图片、视频大文件

(3)可以获取上传的文件的元数据,如文件名,创建时间等

(4)有文件对象的异步接口上传的文件是Python文件对象,可以使用write(), read(), seek(), close()操作

  • 多个文件上传
from typing import List
from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/multi/uploaadfile/")
async def create_multi_upload_file(files: List[UploadFile] = File(...)):
    results = []
    for file in files:
        content = await file.read()
        print(content)
        results.append({"filename": file.filename, "content_type": file.content_type})
    return results

上面读取每个文件的内容,通过异步的方式完成。调用接口如下:

作者:iveBoy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/shenjianping/p/14849770.html