【问题标题】:FastAPI - How to upload file via form通过表单上传 Fastapi 文件
【发布时间】:2022-03-20 03:37:20
【问题描述】:

我正在制作一个需要上传文件的 REST API。出于测试目的,我通过邮递员上传文件,但不知道如何访问服务器端的文件。我能够检索 _dict 以进行身份​​验证,但对于文件,它不返回任何内容。

#arguments - create, delete, view, list, search, upload, download
@app.post("/incident-resource/{service}")
async def incident_resource_service_handler(service, request: Request):
    try:
        session = Session()
        reqDataForm: FormData = await request.form()
        reqData = reqDataForm._dict 

        file = reqDataForm.get('resource')  # in form(key='resource', value=abc.jpeg)
        print(type(file))                   #< class 'NoneType' >

        user = usr_getAuthenticatedUser(session, reqData)
        userRole = getRole(session, user.role_id)
    except Exception as e:
        session.rollback()
        return handleException(e)

【问题讨论】:

  • 这能回答你的问题吗? Upload file using fastapi
  • 很遗憾没有,它只说文件。我想要 reqDataForm 中的字典和文件。我应该改变论点吗? - 我还不知道!!
  • 通常每个表单参数都有一个视图函数的参数;一个用于文件,第二个用于附加字段,第三个用于之后的任何附加字段,依此类推。

标签: forms rest post postman fastapi


【解决方案1】:

根据documentation,“文件将作为“表单数据”上传,您可以通过将端点中的类型声明为bytesUploadFile 来接收它们。如果您需要发送其他数据有了文件,你可以看看here

但是,如果您需要以解决问题的方式来解决问题,请查看以下内容。根据Starlette's documentation,您可以获得文件名和内容如下。无论您在客户端提供什么键名,您也必须在服务器端使用该键名。下面的“upload_file”用作键。如果需要接收和保存多个文件或大文件,请考虑改用异步写入,如 here 所述。

服务器端

@app.post("/upload")
async def create_file(request: Request):
    form = await request.form()
    filename = form["upload_file"].filename
    contents = await form["upload_file"].read()
    with open(filename, 'wb') as f:
        f.write(contents)
    return filename

客户端(使用 Python 请求的示例)

import requests

url = 'http://127.0.0.1:8000/upload'
file = {'upload_file': open('test_files/a.txt','rb')}
resp = requests.post(url=url, files = file) 
print(resp.json())

客户端(使用 FastAPI 的 TestClient 的示例)

from fastapi.testclient import TestClient
from app import app

client = TestClient(app)
file = {'upload_file': open('test_files/a.txt','rb')}
response = client.post("/upload", files = file)
print(response.json())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2016-04-18
    • 2018-06-29
    • 2013-01-08
    • 1970-01-01
    • 2021-10-20
    • 2020-11-12
    相关资源
    最近更新 更多