Skip to content

Instantly share code, notes, and snippets.

@vbmendes
Created December 16, 2010 14:07
Show Gist options
  • Save vbmendes/743427 to your computer and use it in GitHub Desktop.
Save vbmendes/743427 to your computer and use it in GitHub Desktop.
HTTPRequest
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class HTTPRequest(object):
"""
Class to generate plain HTTP Requests
usage:
>>> req = HTTPRequest('meiocodigo.com', path='/')
>>> req.add_header('Content-Type', 'application/x-www-form-urlencoded')
>>> req.body = 'name=ruturajv&sex=m'
>>> print req
GET / HTTP/1.1
Host: meiocodigo.com
Content-Length: 19
Content-Type: application/x-www-form-urlencoded
name=ruturajv&sex=m
"""
def __init__(self, host, method='GET', path='/'):
self.headers = {}
self.host = host
self.method = method
self.path = path
self.http_version = 'HTTP/1.1'
self.body = ''
def add_header(self, key, header):
self.headers[key] = header
def get_body(self):
return self._body
def set_body(self, body):
self._body = body
self.add_header('Content-Length', len(body))
body = property(get_body, set_body)
def __str__(self):
replacement = self.__dict__.copy()
replacement['headers'] = '\n'.join(['%s: %s' % item for item in self.headers.items()])
tpl = """%(method)s %(path)s %(http_version)s
Host: %(host)s
%(headers)s
%(_body)s"""
return tpl % replacement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment