You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python requests上传GitLab安全文件时遇‘name无效’错误求助

GitLab安全文件上传:curl正常但requests报错400的解决方法

我用curl命令能成功向GitLab仓库上传安全文件,但用Python的requests模块时返回400错误,提示name is invalid。

错误的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"

问题原因

问题出在requests的参数构造逻辑上:curl里的--form "name=a.txt"是普通文本表单字段,但你把name放到了files字典中,这会让requests将name当作一个文件类型的字段处理,而非GitLab API要求的普通参数,导致API无法识别有效的name值。

解决方法

将name从files参数移到data参数中,files仅保留文件相关内容,同时建议用二进制模式rb打开文件(避免编码问题):

修正后的代码

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

或者也可以在files的文件元组里显式指定文件名,再配合data传递name参数(效果一致,写法更清晰):

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

这样构造的请求和curl的行为完全一致,name作为普通表单参数传递,file作为文件字段上传,GitLab API就能正确识别参数并完成文件上传。

内容的提问来源于stack exchange,提问作者ADL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 10:35:18