Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems POST-ing with pyCurl

i'm trying to POST a file to a webservice using CURL (that's what I need to use so I can't take twisted or something else). The problem is that when using pyCurl the webservice doesn't receive the file i'm sending, as in the case commented at the bottom of the file. What am I doing wrong in my pyCurl script? Any ideeas?

Thank you very much.

import pycurl
import os

headers = [ "Content-Type: text/xml; charset: UTF-8; " ]
url = "http://myurl/webservice.wsdl"
class FileReader:
    def __init__(self, fp):
        self.fp = fp
    def read_callback(self, size):
        text = self.fp.read(size)
        text = text.replace('\n', '')
        text = text.replace('\r', '')
        text = text.replace('\t', '')
        text = text.strip()
        return text

c = pycurl.Curl()
filename = 'my.xml'
fh = FileReader(open(filename, 'r'))

filesize = os.path.getsize(filename)
c.setopt(c.URL, url)
c.setopt(c.POST, 1)
c.setopt(c.HTTPHEADER, headers)
c.setopt(c.READFUNCTION , fh.read_callback)
c.setopt(c.VERBOSE, 1)
c.setopt(c.HTTP_VERSION, c.CURL_HTTP_VERSION_1_0)
c.perform()
c.close()
# This is the curl command I'm using and it works
# curl -d @my.xml -0 "http://myurl/webservice.wsdl" -H "Content-Type: text/xml; charset=UTF-8"
like image 908
rsavu Avatar asked Jan 24 '26 06:01

rsavu


2 Answers

PyCurl seems to be an orphaned project. It hasn't been updated in two years. I just call command line curl as a subprocess.

import subprocess

def curl(*args):
    curl_path = '/usr/bin/curl'
    curl_list = [curl_path]
    for arg in args:
        # loop just in case we want to filter args in future.
        curl_list.append(arg)
    curl_result = subprocess.Popen(
                 curl_list,
                 stderr=subprocess.PIPE,
                 stdout=subprocess.PIPE).communicate()[0]
    return curl_result 

curl('-d', '@my.xml', '-0', "http://myurl/webservice.wsdl", '-H', "Content-Type: text/xml; charset=UTF-8")
like image 196
mjhm Avatar answered Jan 26 '26 21:01

mjhm


Try to do the file upload in this manner:

c.setopt(c.HTTPPOST, [("filename.xml", (c.FORM_FILE, "/path/to/file/filename.xml"))])

like image 24
vonPetrushev Avatar answered Jan 26 '26 20:01

vonPetrushev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!