使用请求python模块上传安全文件到GitLab



我正在尝试上传一个安全文件到我在GitLab的存储库。

虽然我可以使用curl上传安全文件,但在Python中使用请求时遇到错误。

我的python代码:
r = requests.post("https://gitlab.com/api/v4/projects/10186699/secure_files",
headers={"PRIVATE-TOKEN": "glpat-TH7FM3nThKmHgOp"},
files={"file": open("/Users/me/Desktop/dev/web-server/utils/a.txt", "r"),
"name": "a.txt"}) 
print(r.status_code,r.json())

反应:

400 {'error': 'name is invalid'}

我使用的等效curl命令实际上是有效的:

curl --request POST --header  "PRIVATE-TOKEN: glpat-TH7FM3nThKmHgOp" https://gitlab.com/api/v4/projects/10186699/secure_files --form "name=a.txt" --form "file=@/Users/me/Desktop/dev/web-server/utils/a.txt"

对应的调用将是

import requests
resp = requests.post(
"https://gitlab.com/api/v4/projects/10186699/secure_files",
headers={"PRIVATE-TOKEN": "glpat-TH7FM3nThKmHgOp"},
files={"file": open("/Users/me/Desktop/dev/web-server/utils/a.txt", "rb")},
data={"name": "a.txt"}
) 
print(resp.status_code,resp.json())

这是因为file=参数只用于上传文件。另一方面,name是您的表单数据(您需要传递data=参数)。

还建议以二进制模式打开文件。(文档)

最新更新