Skip to content

A python module that encodes data into multipart form-data.

Notifications You must be signed in to change notification settings

eliellis/mpart.py

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 

Repository files navigation

Usage

Just import mpart.py, create a dictionary containing form-data and call `mpart.encode(your dictionary)` and your data is now ready for the big time. * The keys in the dictionary should correspond to the form you are posting, such that if an html-form contained an input element like `<textarea rows="2" cols="10" name="content"></textarea>` you should create a dictionary like `data = {'content':'I am posting some content'}` to successfully post to the form. * The dictionary can contain files, just make sure to pass in a file-like object that supports the `read()` method.

Example

Using mpart.py is as easy as it could get. Consider the following example script that posts a simple string to pastie.org:
import mpart, urllib2

fields = {'paste[body]':'Hello World!', 'paste[authorization]':'burger', 'paste[restricted]':'0','paste[parser_id]':'6','key':'','lang':''}

mpartdata = mpart.encode(fields)
req = urllib2.Request('http://pastie.org/pastes')
req.add_header('content-type', mpartdata[0])
req.add_header('user-agent', 'mpart.py tutorial 1.0')
req.add_header('content-length', len(mpartdata[1]))
req.add_data(mpartdata[1])
try:
	resp = urllib2.urlopen(req)
	print resp.url
except Exception, e:
	print e.read()
Simple right? Just pass your form data to the encode function in the form of one dictionary (containing fields and or files) and you get the 'content-type' header and the encoded data back.

What you get back

When you call encode, you pass in some form data, but how is all that handed back?
```python import mpart data = {'name':'John Doe', 'email':'johndoe@mail.com'} multipart = mpart.encode(data) print multipart[0] print multipart[1] ```
This yeilds the output (where the boundary is generated randomly):
``` multipart/form-data, boundary=9q3ep42ief --9q3ep42ief Content-Disposition: form-data; name="name"

John Doe --9q3ep42ief Content-Disposition: form-data; name="email"

johndoe@mail.com --9q3ep42ief--

<h5>The first line is the 'content-type' header that contains the boundary used in the encoding. The lines following the first are the encoded data. So, the method returns a list containing both the header string you should use, and the multipart form-data</h5>


About

A python module that encodes data into multipart form-data.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages