API upload_multipart with Python

26 views
Skip to first unread message

Eirik Johannessen

unread,
Apr 3, 2024, 8:03:00 AMApr 3
to ResourceSpace
Has anyone had any success using Python to upload a file via upload_multipart function in the API?

Have tried to follow the curl example from PHP, using pyCurl, but am not able to authenticate correctly.

import pycurl
import hashlib
import json
from urllib.parse import urlencode, quote

url = "http://myresourcespace.space/api/?"
rs_user = "user"
rs_private_key = "1234"
function_to_query = "upload_multipart"

file_path = "http://www.montala.com/img/slideshow/montala-bg.jpg"

ref=10748

data = {
    'user': rs_user,
    'function': function_to_query,
    'ref': ref,
    'no_exif': 1,
    'revert': 0
}

# Sign the query using the private key
query = rs_private_key + urlencode(data)

# Encode the string to bytes for hashing
query = query.encode('utf-8')

# Hash the private key and query
sign = hashlib.sha256()
sign.update(query)

# Initialize the pycurl object
c = pycurl.Curl()

# This part simply replicates the GET query string to be POSTed as a single 'query' POST item.
postdata = [
    ('query', data),
    ('sign', sign.hexdigest()),
    ('user', rs_user),
    ('file', (c.FORM_FILE, file_path)) # IMPORTANT: this wasn't part of the signature!
]
postdata = urlencode(postdata)

# Configure the pycurl object
c.setopt(c.VERBOSE, 1)
c.setopt(c.URL, url)
c.setopt(c.HTTPHEADER, ['Content-Type: multipart/form-data'])
c.setopt(c.POST, 1)
c.setopt(c.HTTPPOST, postdata)

c.perform()

c.close()

Reply all
Reply to author
Forward
0 new messages