Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send file using POST from a Python script

This is an almost-duplicate of Send file using POST from a Python script, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.

like image 685
zellyn Avatar asked Sep 29 '08 20:09

zellyn


People also ask

How do you send a post in Python?

The post() method sends a POST request to the specified url. The post() method is used when you want to send some data to the server.

How do I upload a file to a Python URL?

import requests dfile = open("datafile. txt", "rb") url = "http://httpbin.org/post" test_res = requests. post(url, files = {"form_field_name": dfile}) if test_res. ok: print(" File uploaded successfully !


1 Answers

Best thing I can think of is to encode it yourself. How about this subroutine?

from urllib2 import Request, urlopen
from binascii import b2a_base64

def b64open(url, postdata):
  req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})
  return urlopen(req)

conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité")
# returns a file-like object

(Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.)

like image 58
Dan Lenski Avatar answered Sep 29 '22 13:09

Dan Lenski