FastAPI第三天---文件请求

FastAPI第三天

1. 表单数据

在每次我们实现登录的时候往往都是向服务器发送表单数据,但是从我们后端开发的角度来讲,表单数据确实最容易被攻击的部分。所以在设计表单的时候要设置好过滤器,处理用户发送给服务器的数据。当然,我们系统往往还涉及到数据库进行存储,这个时候SQL注入也是一件非常常见的攻击方式;还有其他类似于数据头注入、电子邮件注入等等手段,这些都是开发的时候需要考虑的。还是那句话,前端校验可以为我们避免部分攻击,但是后端的校验更为重要。

从FastAPI来说,在表单数据中需要使用Form,其中Form是继承自Body的,所以它的参数使用和之前的基本一致

image-20220221084808331

下面就实现以下最基本的登录API

from fastapi import FastAPI, Form

app = FastAPI()


@app.post("/login/")
async def login(
        username: str = Form(...,description="用户名,不超过十位",max_length=10),
        password: str = Form(...,description="密码,不小于6位",min_length=6)
):
    return {
    
    "username": username, "password": password}

image-20220221085243049

2. 文件请求

当我们上传文件的时候,需要使用FileFile继承自Form,所以操作也基本一致。当然我们也可以使用UploadFile,这个对象可以处理更加大的文件,而不像bytes只能储存在内存中。

这里先看一个例子

# 请求文件
from fastapi import FastAPI, File, UploadFile
from typing import List
from fastapi.responses import HTMLResponse

app = FastAPI()


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


@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {
    
    
        "filename": file.filename,
        "content":await file.read(),
    }


@app.post("/mulfiles/")
async def create_file(files: List[bytes] = File(...)):
    return {
    
    "file_sizes": [len(file) for file in files]}


@app.post("/muluploadfiles/")
async def create_upload_file(files: List[UploadFile] = File(...)):
    return {
    
    "filenames": [file.filename for file in files]}


@app.get("/")
async def index():
    content = """
    <body>
    <form action="/mulfiles/" enctype="multipart/form-data" method="post">
    <input name="files" type="file" multiple>
    <input type="submit">
    </form>
    <form action="/muluploadfiles/" enctype="multipart/form-data" method="post">
    <input name="files" type="file" multiple>
    <input type="submit">
    </form>
    </body>
        """
    return HTMLResponse(content=content)

前两个Post是针对单个文件,后面的是多文件。很遗憾Swagger目前并不支持多文件上传,所以想要测试多文件上传可以使用postman或者直接访问自己写的表单页面进行测试。

注意,官网中的例子存在错误

image-20220221104301030

另外,针对UploadFile还具有一些异步方法

image-20220221104451160

  • write: 写入到文件
  • read:读取文件(多少个字节)
  • seek:找到文件中(字节)的位置
  • close:关闭文件

这些方法都是异步的,因此在代码中如果使用必须添加await

image-20220221104826031

猜你喜欢

转载自blog.csdn.net/shelgi/article/details/123045174