This repository has been archived on 2023-01-02. You can view files and clone it, but cannot push or open issues or pull requests.
django-pyvows/django_pyvows/http_helpers.py

102 lines
2.9 KiB
Python
Raw Normal View History

2012-03-08 18:57:32 +00:00
#!/usr/bin/python
# -*- coding: utf-8 -*-
import httplib2
2011-08-22 17:37:21 +00:00
import mimetypes
import mimetools
import itertools
class MultiPartForm(object):
"""Accumulate the data to be used when posting a form."""
def __init__(self):
self.form_fields = []
self.files = []
self.boundary = mimetools.choose_boundary()
return
def get_content_type(self):
return 'multipart/form-data; boundary=%s' % self.boundary
def add_field(self, name, value):
"""Add a simple field to the form data."""
self.form_fields.append((name, value))
return
def add_file(self, fieldname, filename, fileHandle, mimetype=None):
"""Add a file to be uploaded."""
body = fileHandle.read()
if mimetype is None:
mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
self.files.append((fieldname, filename, mimetype, body))
return
def __str__(self):
"""Return a string representing the form data, including attached files."""
# Build a list of lists, each containing "lines" of the
# request. Each part is separated by a boundary string.
# Once the list is built, return a string where each
# line is separated by '\r\n'.
parts = []
part_boundary = '--' + self.boundary
# Add the form fields
parts.extend(
[ part_boundary,
'Content-Disposition: form-data; name="%s"' % name,
'',
value,
]
for name, value in self.form_fields
)
# Add the files to upload
parts.extend(
[ part_boundary,
'Content-Disposition: file; name="%s"; filename="%s"' % \
(field_name, filename),
'Content-Type: %s' % content_type,
'',
body,
]
for field_name, filename, content_type, body in self.files
)
# Flatten the list and add closing boundary marker,
# then return CR+LF separated data
flattened = list(itertools.chain(*parts))
flattened.append('--' + self.boundary + '--')
flattened.append('')
return '\r\n'.join(flattened)
def get(url):
2012-03-08 18:57:32 +00:00
h = httplib2.Http()
resp, content = h.request(url)
return resp, content
2011-08-22 17:37:21 +00:00
def post(url, data):
2012-03-08 18:57:32 +00:00
h = httplib2.Http()
2011-08-22 17:37:21 +00:00
form = MultiPartForm()
for field, value in data.iteritems():
2011-08-22 18:08:00 +00:00
if hasattr(value, "read"):
2011-08-22 17:37:21 +00:00
form.add_file(field, value.name, value)
2011-08-22 18:08:00 +00:00
else:
form.add_field(field, str(value))
2011-08-22 17:37:21 +00:00
body = str(form)
2012-03-08 18:57:32 +00:00
headers = {
'Content-type': form.get_content_type(),
'Content-length': str(len(body))
}
2011-08-22 17:37:21 +00:00
try:
2012-03-08 18:57:32 +00:00
response = h.request(url, 'POST', headers=headers, body=body)
except httplib2.HttpLib2Error, err:
2011-08-22 17:37:21 +00:00
response = err
return response