Convert cURL to Python - Upload A File

Viewed 1190

I can't seem to convert cURL to python. From the docs:

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

I have tried using files instead of data to no avail.

The current code below creates the proper response 201, but it's blank (has no JSON details with an image to use for future API calls). Let me what changes I need to make to upload a file via a PUT request without using a multi-part form (ie "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()
2 Answers

Try not to confuse a request with a response.

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

If you are not bound to use the requests library, you could try running the curl command directly from python, using subprocess.run() and shlex.split() for Python 3.

Using the example curl command from your question (adding a missing double quote at the end) the following code would run it and capture the response as text.

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

For Python 2.7, replace the last line with:

response = subprocess.call(args)
Related