问题描述
我对使用python请求库还很陌生,目前正在尝试从JIRA下载图像,然后将该图像上传到gitlab,以供以后在便笺中引用,如此处记录的https://docs.gitlab.com/ee/api/projects.html#upload-a-file。图片已从JIRA正确下载(我可以看到并打开文件),但是,当我尝试将其发布到gitlab时,出现了错误400 Bad Request响应。
我的代码如下:
gl_url = 'https://lab.mygitlabinstance.com/api/v4/projects/%s/uploads' % gl_project_id
def image_post(image_url,file_name,jira_auth,gl_url,gl_token):
image = requests.get(
image_url,auth=HTTPBasicAuth(*jira_auth),stream=True)
local_file = open(file_name,'wb')
image.raw.decode_content = True
shutil.copyfileobj(image.raw,local_file)
file = {'file': '@' + file_name}
value = requests.post(
gl_url,headers={'PRIVATE-TOKEN': gl_token,'Content-Type': 'multipart/form-data'},verify=True,files=file
)
return value
我的gitlab令牌正在同一程序的其他部分中工作,所以我认为这不是问题。任何帮助将不胜感激。
解决方法
尝试这个:
def image_post(image_url,file_name,jira_auth,gl_url,gl_token):
image = requests.get(
image_url,auth=HTTPBasicAuth(*jira_auth),stream=True)
# save file locally
with open(file_name,'wb') as f:
f.write(image.content)
# readfile and send
file = {'file': open(file_name,'rb')}
value = requests.post(
gl_url,headers={'PRIVATE-TOKEN': gl_token},verify=True,files=file
)
return value
或者可能是第二个:
我不确定您的local_file
中包含什么,但是'@'+filename
是否适用于curl
语法,这里我们需要文件内容,因此请尝试在示例中将此行修正为: {1}}