1. 程式人生 > 實用技巧 >requests上傳檔案,又要上傳data的處理

requests上傳檔案,又要上傳data的處理

前話

最近在自己學著弄介面自動化框架,因為要封裝一個傳送請求的父類,其中有考慮到上傳檔案,以及同時上傳檔案,和傳遞其他欄位資料,遇到點小問題 這裡解決下。

例項的介面資料

來自fastapi官方文件上傳檔案例項:https://fastapi.tiangolo.com/zh/tutorial/request-files/

#!/usr/bin/env/python3
# -*- coding:utf-8 -*-
"""
@project: Api
@author: zy7y
@file: fapi.py
@ide: PyCharm
@time: 2020/8/1
"""

from fastapi import FastAPI, File, UploadFile, Form

app = FastAPI()


@app.post("/uploadfile/")
async def create_upload_file(file_excel: UploadFile = File(...), username: str = Form(...)):
    # 讀取檔案
    contents = await file_excel.read()
    # 儲存本地
    with open(file_excel.filename, "wb") as f:
        f.write(contents)
    return {'msg': '操作成功', "filename": file_excel.filename, 'username': username}


if __name__ == '__main__':
    import uvicorn
    uvicorn.run('fapi:app', reload=True)

執行這個檔案:可以通過http://127.0.0.1:8000/docs檢視介面文件

  • 請求路徑:/uploadfile/
  • 請求方法:post
  • 請求引數
引數名 引數說明 備註
file_excel 檔案二進位制物件 不能為空
username 使用者名稱 不能為空
  • 響應引數
引數名 引數說明 備註
msg 操作結果
filename 檔名稱
username 使用者名稱
  • 響應資料
{
  "msg": "操作成功",
  "filename": "Python自動化開發實戰.pdf",
  "username": "柒意"
}

使用Request請求該介面

#!/usr/bin/env/python3
# -*- coding:utf-8 -*-
"""
@project: apiAutoTest
@author: zy7y
@file: request_demo.py
@ide: PyCharm
@time: 2020/8/1
"""

import requests

# 上傳檔案介面
url = 'http://127.0.0.1:8000/uploadfile/'
# 上傳非檔案的引數資料
data = {
    "username": "柒意",
}
# 上傳檔案型別的引數資料, 下面的 'file_excel' 是上面介面中對應的請求引數裡的檔案物件中的引數名,
file = {'file_excel': open('../data/case_data.xlsx', 'rb')}

res = requests.post(url, data, files=file)
print(res.json())

結果:

/Users/zy7y/PycharmProjects/apiAutoTest/venv/bin/python /Users/zy7y/PycharmProjects/apiAutoTest/tools/demo.py
{'msg': '操作成功', 'filename': 'case_data.xlsx', 'username': '柒意'}

Process finished with exit code 0

⚠️注意:file_excel是介面請求引數中,接受檔案物件的引數名