python文件上傳錯誤“Required request part 'xxx' is not present”


背景:頁面偶現上傳文件失敗,在研測環境都無法復現。於是想通過腳本來多次請求嘗試復現問題。

查看請求信息:

開始擼碼 (想當然的添加content-type和cookies)

import os
import requests

headers = {'Content-Type': 'multipart/form-data',
           'Cookie': 'access_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIxNzY4MTEwOTc1NyIsInNjb3BlIjpbIm9wZW5pZCJdLCJleHAiOjE2rpYATtO7g-AHopmAaeRfLuLi5SIsSZ0nl5ksAI_r-moPozyMQJh2vTt3p9Hc2_2tfJ7LVq0GU79XIgwBkPRZckoHgOUj39jO_aVLDd6iizp8fyuVBFLTQ'}

url = 'http://xxx.xxx.xxx/commonApi/kg/openqa/batch/import'
files = {'file': open(os.path.join(os.path.dirname(__file__), 'aee15f6befd14ed1979018bc03c9985a.xlsx'), 'rb')}
res = requests.post(url=url, files=files, headers=headers)
print(res.status_code)
print(res.json())

運行結果:

200
{'retcode': '999999', 'desc': "出現未知異常,錯誤信息為Required request part 'file' is not present"}

網上各種找資料,都沒有對這種錯誤的解析,直到看到https://www.cnpython.com/qa/518198。。。

既然添加請求頭的時候能想起來吧boundary去掉,為啥就沒想起來這玩意加了令牌。。。

去掉Content-Type

import os
import requests

headers = {
    'Cookie': 'access_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIxNzY4MTEwOTc1NyIsInNjb3BlIjpbIm9wZW5pZCJdLCJleHAiOjE2MTEwNTExODUsImlhdCI6MTYxMDk2NDc4NSwiYXV0aG9yaXRpZXMiOlsiUk9MRV9BSU1JTkRfQURNSU5JU1RSQVRPUiJdLCJqdGkiOiJhY2FhNzIzYy1jN2Q3LTQ3YmQtYjI0Zi0zNTk3MWUyNDlmMjUiLCJjbGllbnRfaWQiOiJ3ZWJfYXBwIn0.SaYsEi0Z_bdEgARknWSKV2-ZUAxD4eNdLDd6iizp8fyuVBFLTQ'}

url = 'http://xxx.xxx.xxx/commonApi/kg/openqa/batch/import'
files = {'file': open(os.path.join(os.path.dirname(__file__), 'aee15f6befd14ed1979018bc03c9985a.xlsx'), 'rb')}
res = requests.post(url=url, files=files, headers=headers)
print(res.status_code)
print(res.json())

再次請求

200
{'retcode': '000000', 'desc': '成功'}
```![](https://img2020.cnblogs.com/blog/1638284/202101/1638284-20210118200650944-470169345.png)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM