FastAPI官方教程太棒了(下)
本书作者:测试开发刚哥,文章版权归个人所有,未经授权请勿转载。 响应状态码 在@app.post()方法中添加status_code参数: from fastapi import FastAPI app = FastAPI() @app.post("/items/", status_code=201) async def create_item(name: str): return {"name": name} status_code也可以是IntEnum,比如Python的http.HTTPStatus。 常见响应状态码: 100以上,信息;很少直接使用; 200以上,成功;200是OK,201是Created,204是No Content; 300以上,重定向;304是Not Modified; 400以上,客户端错误;404是Not Found; 500以上,服务器错误; FastAPI引入了status,可以方便的录入这些状态: from fastapi import FastAPI, status app = FastAPI() @app.post("/items/", status_code=status.HTTP_201_CREATED) async def create_item(name: str): return {"name": name} 表单数据 为了使用表单,首先需要安装python-multipart: pip install python-multipart 示例: from fastapi import FastAPI, Form app = FastAPI() @app.post("/login/") async def login(username: str = Form(), password: str = Form()): return {"username": username} 表单由HTML中的<form></form>发送,请求头的content-type一般是application/x-www-form-urlencoded,当为文件时multipart/form-data。 请求文件 示例: from fastapi import FastAPI, File, UploadFile 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): return {"filename": file.filename} create_file()的类型为bytes,接收到的文件内容也是bytes,数据都存在于内存中,适用于小文件。create_upload_file()的类型为UploadFile,它会在内存设置一个最大存储,超出最大存储,就会把数据转存到磁盘,适用于大文件。 ...