如何使用python请求将图像发布到gitlab

问题描述

我对使用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}}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...