Skip to content

Instantly share code, notes, and snippets.

@ydm
Last active December 14, 2015 12:38
Show Gist options
  • Save ydm/5087317 to your computer and use it in GitHub Desktop.
Save ydm/5087317 to your computer and use it in GitHub Desktop.
Issue an HTTP POST request to upload a string as file using libcurl and pycurl. Tested against Python 2.7.3 and libcurl 7.29.0.
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Issue an HTTP POST request to upload a string as file using libcurl
# and pycurl.
#
# vars.php
# <?php
# header('Content-Type: text/plain; charset=UTF-8');
#
# echo "GET:\n";
# print_r($_GET);
#
# echo "\nPOST:\n";
# print_r($_POST);
#
# echo "\nFILES:\n";
# print_r($_FILES);
#
# foreach ($_FILES as $name => $file) {
# echo "\nSTART " . $name . "\n";
# echo file_get_contents($file['tmp_name']);
# echo "\nEND " . $name . "\n";
# }
# ?>
import pycurl
def add_str_as_file(form, content, content_type, name, filename):
e = ('%s"; filename="%s' % (name, filename),
(pycurl.FORM_CONTENTS, content,
pycurl.FORM_CONTENTTYPE, content_type,
# filename={x} above does the trick since this doesn't work
# pycurl.FORM_FILENAME, filename
),
)
form.append(e)
data = []
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<message>Здрасти, свят!</message>
<message>Hello, world!</message>'''
add_str_as_file(data, xml, 'application/xml; charset=UTF-8', 'file',
'universe.xml')
c = pycurl.Curl()
c.setopt(c.URL, 'http://localhost/d/vars.php')
c.setopt(c.HTTPPOST, data)
c.setopt(c.VERBOSE, 1)
# c.setopt(c.PROXY, 'localhost:8008')
c.perform()
c.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment