将cURL转换为Python上载文件

2024-09-23 22:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎无法将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请求上传文件需要做哪些更改(即“files=”)

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()

Tags: httpsimagecomresponserequestfilesopenfilename
2条回答

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

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

如果您不必使用请求库,那么可以尝试直接从python运行curl命令,对python 3使用subprocess.run()shlex.split()

使用问题中的示例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)

相关问题 更多 >