前話
最近在自己學着弄接口自動化框架,因為要封裝一個發送請求的父類,其中有考慮到上傳文件,以及同時上傳文件,和傳遞其他字段數據,遇到點小問題 這里解決下。
實例的接口數據
參考文檔
來自fastapi官方文檔上傳文件實例:https://fastapi.tiangolo.com/zh/tutorial/request-files/
https://www.cnblogs.com/sanduzxcvbnm/p/12781125.html
#!/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