繁体   English   中英

将 cURL 转换为 Python - 上传文件

[英]Convert cURL to Python - Upload A File

我似乎无法将 cURL 转换为 python。 从文档:

curl -i --upload-file ~/Desktop/Myimage.jpg -H 'Authorization: Bearer Redacted' "https://api.linkedin.com/mediaUpload/C5522AQHn46pwH96hxQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQLKRJOn_yNw6wAAAW2T0DWnRStny4dzsNVJjlF3aN4-H3ZR9Div77kKoQ&app=1983914&sync=0&v=beta&ut=1Dnjy796bpjEY1

我曾尝试使用文件而不是数据无济于事。

下面的当前代码创建了正确的响应 201,但它是空白的(没有 JSON 详细信息以及用于未来 API 调用的图像)。 让我在不使用多部分表单(即“文件=”)的情况下通过 PUT 请求上传文件需要进行哪些更改

uploadUrl = data["value"]["uploadMechanism"]["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["uploadUrl"]

filename = "ffadfads.jpeg"
media_url = "https://1000logos.net/wp-content/uploads/2017/03/LinkedIn-Logo.png"
request = requests.get(media_url, stream=True)
if request.status_code == 200:
    with open(filename, 'wb') as image:
        for chunk in request:
            image.write(chunk)
    #files = {'fileupload': open(filename)}
    files = {"fileupload":(filename,open(filename,"rb"),'application-type')}
    image_headers = {
        'Accept': 'image/jpeg,image/png,image/gif',
        'Authorization': 'Bearer ' + real_token
    }
    response = requests.request("PUT", uploadUrl, data=open(filename,"rb"), headers=image_headers)
    print response
    print response.text
    print response.json()

尽量不要将请求与响应混淆。

response1 = requests.get(media_url, stream=True)
if response1.status_code == 200:
    response2 = requests.request("PUT", uploadUrl,
                                 data=response1.iter_content(),
                                 headers=image_headers)

如果您并不局限于使用请求库,你可以尝试直接从蟒蛇运行curl命令,使用subprocess.run()shlex.split()为Python 3。

使用您问题中的示例 curl 命令(在末尾添加缺少的双引号),以下代码将运行它并将响应捕获为文本。

import shlex
import subprocess

curl_command_line = '''curl -i --upload-file ~/Desktop/Myimage.jpg \
-H 'Authorization: Bearer Redacted' \
"https://api.linkedin.com/mediaUpload/C5522AQHn46pwH96hxQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQLKRJOn_yNw6wAAAW2T0DWnRStny4dzsNVJjlF3aN4-H3ZR9Div77kKoQ&app=1983914&sync=0&v=beta&ut=1Dnjy796bpjEY1"'''

args = shlex.split(curl_command_line)
response = subprocess.run(args, capture_output=True, text=True).stdout

对于 Python 2.7,将最后一行替换为:

response = subprocess.call(args)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM