Skip to content
Myr

Merge branch 'release/0.2.1'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 06b4969, 43790c4 · Browse files · 11 files+752 added−43 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+752 added−43 removed

  • other:+752 added−43 removed

11 files+752 added−43 removed

added:requests/packages/poster/__init__.py+32 added
1# Copyright (c) 2010 Chris AtLee2# 3# Permission is hereby granted, free of charge, to any person obtaining a copy4# of this software and associated documentation files (the "Software"), to deal5# in the Software without restriction, including without limitation the rights6# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7# copies of the Software, and to permit persons to whom the Software is8# furnished to do so, subject to the following conditions:9# 10# The above copyright notice and this permission notice shall be included in11# all copies or substantial portions of the Software.12# 13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN19# THE SOFTWARE.20"""poster module2122Support for streaming HTTP uploads, and multipart/form-data encoding2324```poster.version``` is a 3-tuple of integers representing the version number.25New releases of poster will always have a version number that compares greater26than an older version of poster.27New in version 0.6."""2829from . import streaminghttp30from . import encode3132version = (0, 8, 0) # Thanks JP!
added:requests/packages/poster/encode.py+414 added
1"""multipart/form-data encoding module23This module provides functions that faciliate encoding name/value pairs4as multipart/form-data suitable for a HTTP POST or PUT request.56multipart/form-data is the standard way to upload files over HTTP"""78__all__ = ['gen_boundary', 'encode_and_quote', 'MultipartParam',9 'encode_string', 'encode_file_header', 'get_body_size', 'get_headers',10 'multipart_encode']1112try:13 import uuid14 def gen_boundary():15 """Returns a random string to use as the boundary for a message"""16 return uuid.uuid4().hex17except ImportError:18 import random, sha19 def gen_boundary():20 """Returns a random string to use as the boundary for a message"""21 bits = random.getrandbits(160)22 return sha.new(str(bits)).hexdigest()2324import urllib, re, os, mimetypes25try:26 from email.header import Header27except ImportError:28 # Python 2.429 from email.Header import Header3031def encode_and_quote(data):32 """If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8"))33 otherwise return urllib.quote_plus(data)"""34 if data is None:35 return None3637 if isinstance(data, unicode):38 data = data.encode("utf-8")39 return urllib.quote_plus(data)4041def _strify(s):42 """If s is a unicode string, encode it to UTF-8 and return the results,43 otherwise return str(s), or None if s is None"""44 if s is None:45 return None46 if isinstance(s, unicode):47 return s.encode("utf-8")48 return str(s)4950class MultipartParam(object):51 """Represents a single parameter in a multipart/form-data request5253 ``name`` is the name of this parameter.5455 If ``value`` is set, it must be a string or unicode object to use as the56 data for this parameter.5758 If ``filename`` is set, it is what to say that this parameter's filename59 is. Note that this does not have to be the actual filename any local file.6061 If ``filetype`` is set, it is used as the Content-Type for this parameter.62 If unset it defaults to "text/plain; charset=utf8"6364 If ``filesize`` is set, it specifies the length of the file ``fileobj``6566 If ``fileobj`` is set, it must be a file-like object that supports67 .read().6869 Both ``value`` and ``fileobj`` must not be set, doing so will70 raise a ValueError assertion.7172 If ``fileobj`` is set, and ``filesize`` is not specified, then73 the file's size will be determined first by stat'ing ``fileobj``'s74 file descriptor, and if that fails, by seeking to the end of the file,75 recording the current position as the size, and then by seeking back to the76 beginning of the file.7778 ``cb`` is a callable which will be called from iter_encode with (self,79 current, total), representing the current parameter, current amount80 transferred, and the total size.81 """82 def __init__(self, name, value=None, filename=None, filetype=None,83 filesize=None, fileobj=None, cb=None):84 self.name = Header(name).encode()85 self.value = _strify(value)86 if filename is None:87 self.filename = None88 else:89 if isinstance(filename, unicode):90 # Encode with XML entities91 self.filename = filename.encode("ascii", "xmlcharrefreplace")92 else:93 self.filename = str(filename)94 self.filename = self.filename.encode("string_escape").\95 replace('"', '\\"')96 self.filetype = _strify(filetype)9798 self.filesize = filesize99 self.fileobj = fileobj100 self.cb = cb101102 if self.value is not None and self.fileobj is not None:103 raise ValueError("Only one of value or fileobj may be specified")104105 if fileobj is not None and filesize is None:106 # Try and determine the file size107 try:108 self.filesize = os.fstat(fileobj.fileno()).st_size109 except (OSError, AttributeError):110 try:111 fileobj.seek(0, 2)112 self.filesize = fileobj.tell()113 fileobj.seek(0)114 except:115 raise ValueError("Could not determine filesize")116117 def __cmp__(self, other):118 attrs = ['name', 'value', 'filename', 'filetype', 'filesize', 'fileobj']119 myattrs = [getattr(self, a) for a in attrs]120 oattrs = [getattr(other, a) for a in attrs]121 return cmp(myattrs, oattrs)122123 def reset(self):124 if self.fileobj is not None:125 self.fileobj.seek(0)126 elif self.value is None:127 raise ValueError("Don't know how to reset this parameter")128129 @classmethod130 def from_file(cls, paramname, filename):131 """Returns a new MultipartParam object constructed from the local132 file at ``filename``.133134 ``filesize`` is determined by os.path.getsize(``filename``)135136 ``filetype`` is determined by mimetypes.guess_type(``filename``)[0]137138 ``filename`` is set to os.path.basename(``filename``)139 """140141 return cls(paramname, filename=os.path.basename(filename),142 filetype=mimetypes.guess_type(filename)[0],143 filesize=os.path.getsize(filename),144 fileobj=open(filename, "rb"))145146 @classmethod147 def from_params(cls, params):148 """Returns a list of MultipartParam objects from a sequence of149 name, value pairs, MultipartParam instances,150 or from a mapping of names to values151152 The values may be strings or file objects, or MultipartParam objects.153 MultipartParam object names must match the given names in the154 name,value pairs or mapping, if applicable."""155 if hasattr(params, 'items'):156 params = params.items()157158 retval = []159 for item in params:160 if isinstance(item, cls):161 retval.append(item)162 continue163 name, value = item164 if isinstance(value, cls):165 assert value.name == name166 retval.append(value)167 continue168 if hasattr(value, 'read'):169 # Looks like a file object170 filename = getattr(value, 'name', None)171 if filename is not None:172 filetype = mimetypes.guess_type(filename)[0]173 else:174 filetype = None175176 retval.append(cls(name=name, filename=filename,177 filetype=filetype, fileobj=value))178 else:179 retval.append(cls(name, value))180 return retval181182 def encode_hdr(self, boundary):183 """Returns the header of the encoding of this parameter"""184 boundary = encode_and_quote(boundary)185186 headers = ["--%s" % boundary]187188 if self.filename:189 disposition = 'form-data; name="%s"; filename="%s"' % (self.name,190 self.filename)191 else:192 disposition = 'form-data; name="%s"' % self.name193194 headers.append("Content-Disposition: %s" % disposition)195196 if self.filetype:197 filetype = self.filetype198 else:199 filetype = "text/plain; charset=utf-8"200201 headers.append("Content-Type: %s" % filetype)202203 headers.append("")204 headers.append("")205206 return "\r\n".join(headers)207208 def encode(self, boundary):209 """Returns the string encoding of this parameter"""210 if self.value is None:211 value = self.fileobj.read()212 else:213 value = self.value214215 if re.search("^--%s$" % re.escape(boundary), value, re.M):216 raise ValueError("boundary found in encoded string")217218 return "%s%s\r\n" % (self.encode_hdr(boundary), value)219220 def iter_encode(self, boundary, blocksize=4096):221 """Yields the encoding of this parameter222 If self.fileobj is set, then blocks of ``blocksize`` bytes are read and223 yielded."""224 total = self.get_size(boundary)225 current = 0226 if self.value is not None:227 block = self.encode(boundary)228 current += len(block)229 yield block230 if self.cb:231 self.cb(self, current, total)232 else:233 block = self.encode_hdr(boundary)234 current += len(block)235 yield block236 if self.cb:237 self.cb(self, current, total)238 last_block = ""239 encoded_boundary = "--%s" % encode_and_quote(boundary)240 boundary_exp = re.compile("^%s$" % re.escape(encoded_boundary),241 re.M)242 while True:243 block = self.fileobj.read(blocksize)244 if not block:245 current += 2246 yield "\r\n"247 if self.cb:248 self.cb(self, current, total)249 break250 last_block += block251 if boundary_exp.search(last_block):252 raise ValueError("boundary found in file data")253 last_block = last_block[-len(encoded_boundary)-2:]254 current += len(block)255 yield block256 if self.cb:257 self.cb(self, current, total)258259 def get_size(self, boundary):260 """Returns the size in bytes that this param will be when encoded261 with the given boundary."""262 if self.filesize is not None:263 valuesize = self.filesize264 else:265 valuesize = len(self.value)266267 return len(self.encode_hdr(boundary)) + 2 + valuesize268269def encode_string(boundary, name, value):270 """Returns ``name`` and ``value`` encoded as a multipart/form-data271 variable. ``boundary`` is the boundary string used throughout272 a single request to separate variables."""273274 return MultipartParam(name, value).encode(boundary)275276def encode_file_header(boundary, paramname, filesize, filename=None,277 filetype=None):278 """Returns the leading data for a multipart/form-data field that contains279 file data.280281 ``boundary`` is the boundary string used throughout a single request to282 separate variables.283284 ``paramname`` is the name of the variable in this request.285286 ``filesize`` is the size of the file data.287288 ``filename`` if specified is the filename to give to this field. This289 field is only useful to the server for determining the original filename.290291 ``filetype`` if specified is the MIME type of this file.292293 The actual file data should be sent after this header has been sent.294 """295296 return MultipartParam(paramname, filesize=filesize, filename=filename,297 filetype=filetype).encode_hdr(boundary)298299def get_body_size(params, boundary):300 """Returns the number of bytes that the multipart/form-data encoding301 of ``params`` will be."""302 size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))303 return size + len(boundary) + 6304305def get_headers(params, boundary):306 """Returns a dictionary with Content-Type and Content-Length headers307 for the multipart/form-data encoding of ``params``."""308 headers = {}309 boundary = urllib.quote_plus(boundary)310 headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary311 headers['Content-Length'] = str(get_body_size(params, boundary))312 return headers313314class multipart_yielder:315 def __init__(self, params, boundary, cb):316 self.params = params317 self.boundary = boundary318 self.cb = cb319320 self.i = 0321 self.p = None322 self.param_iter = None323 self.current = 0324 self.total = get_body_size(params, boundary)325326 def __iter__(self):327 return self328329 def next(self):330 """generator function to yield multipart/form-data representation331 of parameters"""332 if self.param_iter is not None:333 try:334 block = self.param_iter.next()335 self.current += len(block)336 if self.cb:337 self.cb(self.p, self.current, self.total)338 return block339 except StopIteration:340 self.p = None341 self.param_iter = None342343 if self.i is None:344 raise StopIteration345 elif self.i >= len(self.params):346 self.param_iter = None347 self.p = None348 self.i = None349 block = "--%s--\r\n" % self.boundary350 self.current += len(block)351 if self.cb:352 self.cb(self.p, self.current, self.total)353 return block354355 self.p = self.params[self.i]356 self.param_iter = self.p.iter_encode(self.boundary)357 self.i += 1358 return self.next()359360 def reset(self):361 self.i = 0362 self.current = 0363 for param in self.params:364 param.reset()365366def multipart_encode(params, boundary=None, cb=None):367 """Encode ``params`` as multipart/form-data.368369 ``params`` should be a sequence of (name, value) pairs or MultipartParam370 objects, or a mapping of names to values.371 Values are either strings parameter values, or file-like objects to use as372 the parameter value. The file-like objects must support .read() and either373 .fileno() or both .seek() and .tell().374375 If ``boundary`` is set, then it as used as the MIME boundary. Otherwise376 a randomly generated boundary will be used. In either case, if the377 boundary string appears in the parameter values a ValueError will be378 raised.379380 If ``cb`` is set, it should be a callback which will get called as blocks381 of data are encoded. It will be called with (param, current, total),382 indicating the current parameter being encoded, the current amount encoded,383 and the total amount to encode.384385 Returns a tuple of `datagen`, `headers`, where `datagen` is a386 generator that will yield blocks of data that make up the encoded387 parameters, and `headers` is a dictionary with the assoicated388 Content-Type and Content-Length headers.389390 Examples:391392 >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] )393 >>> s = "".join(datagen)394 >>> assert "value2" in s and "value1" in s395396 >>> p = MultipartParam("key", "value2")397 >>> datagen, headers = multipart_encode( [("key", "value1"), p] )398 >>> s = "".join(datagen)399 >>> assert "value2" in s and "value1" in s400401 >>> datagen, headers = multipart_encode( {"key": "value1"} )402 >>> s = "".join(datagen)403 >>> assert "value2" not in s and "value1" in s404405 """406 if boundary is None:407 boundary = gen_boundary()408 else:409 boundary = urllib.quote_plus(boundary)410411 headers = get_headers(params, boundary)412 params = MultipartParam.from_params(params)413414 return multipart_yielder(params, boundary, cb), headers
added:requests/packages/poster/streaminghttp.py+197 added
1"""Streaming HTTP uploads module.23This module extends the standard httplib and urllib2 objects so that4iterable objects can be used in the body of HTTP requests.56In most cases all one should have to do is call :func:`register_openers()`7to register the new streaming http handlers which will take priority over8the default handlers, and then you can use iterable objects in the body9of HTTP requests.1011**N.B.** You must specify a Content-Length header if using an iterable object12since there is no way to determine in advance the total size that will be13yielded, and there is no way to reset an interator.1415Example usage:1617>>> from StringIO import StringIO18>>> import urllib2, poster.streaminghttp1920>>> opener = poster.streaminghttp.register_openers()2122>>> s = "Test file data"23>>> f = StringIO(s)2425>>> req = urllib2.Request("http://localhost:5000", f,26... {'Content-Length': str(len(s))})27"""2829import httplib, urllib2, socket30from httplib import NotConnected3132__all__ = ['StreamingHTTPConnection', 'StreamingHTTPRedirectHandler',33 'StreamingHTTPHandler', 'register_openers']3435if hasattr(httplib, 'HTTPS'):36 __all__.extend(['StreamingHTTPSHandler', 'StreamingHTTPSConnection'])3738class _StreamingHTTPMixin:39 """Mixin class for HTTP and HTTPS connections that implements a streaming40 send method."""41 def send(self, value):42 """Send ``value`` to the server.4344 ``value`` can be a string object, a file-like object that supports45 a .read() method, or an iterable object that supports a .next()46 method.47 """48 # Based on python 2.6's httplib.HTTPConnection.send()49 if self.sock is None:50 if self.auto_open:51 self.connect()52 else:53 raise NotConnected()5455 # send the data to the server. if we get a broken pipe, then close56 # the socket. we want to reconnect when somebody tries to send again.57 #58 # NOTE: we DO propagate the error, though, because we cannot simply59 # ignore the error... the caller will know if they can retry.60 if self.debuglevel > 0:61 print "send:", repr(value)62 try:63 blocksize = 819264 if hasattr(value, 'read') :65 if hasattr(value, 'seek'):66 value.seek(0)67 if self.debuglevel > 0:68 print "sendIng a read()able"69 data = value.read(blocksize)70 while data:71 self.sock.sendall(data)72 data = value.read(blocksize)73 elif hasattr(value, 'next'):74 if hasattr(value, 'reset'):75 value.reset()76 if self.debuglevel > 0:77 print "sendIng an iterable"78 for data in value:79 self.sock.sendall(data)80 else:81 self.sock.sendall(value)82 except socket.error, v:83 if v[0] == 32: # Broken pipe84 self.close()85 raise8687class StreamingHTTPConnection(_StreamingHTTPMixin, httplib.HTTPConnection):88 """Subclass of `httplib.HTTPConnection` that overrides the `send()` method89 to support iterable body objects"""9091class StreamingHTTPRedirectHandler(urllib2.HTTPRedirectHandler):92 """Subclass of `urllib2.HTTPRedirectHandler` that overrides the93 `redirect_request` method to properly handle redirected POST requests9495 This class is required because python 2.5's HTTPRedirectHandler does96 not remove the Content-Type or Content-Length headers when requesting97 the new resource, but the body of the original request is not preserved.98 """99100 handler_order = urllib2.HTTPRedirectHandler.handler_order - 1101102 # From python2.6 urllib2's HTTPRedirectHandler103 def redirect_request(self, req, fp, code, msg, headers, newurl):104 """Return a Request or None in response to a redirect.105106 This is called by the http_error_30x methods when a107 redirection response is received. If a redirection should108 take place, return a new Request to allow http_error_30x to109 perform the redirect. Otherwise, raise HTTPError if no-one110 else should try to handle this url. Return None if you can't111 but another Handler might.112 """113 m = req.get_method()114 if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")115 or code in (301, 302, 303) and m == "POST"):116 # Strictly (according to RFC 2616), 301 or 302 in response117 # to a POST MUST NOT cause a redirection without confirmation118 # from the user (of urllib2, in this case). In practice,119 # essentially all clients do redirect in this case, so we120 # do the same.121 # be conciliant with URIs containing a space122 newurl = newurl.replace(' ', '%20')123 newheaders = dict((k, v) for k, v in req.headers.items()124 if k.lower() not in (125 "content-length", "content-type")126 )127 return urllib2.Request(newurl,128 headers=newheaders,129 origin_req_host=req.get_origin_req_host(),130 unverifiable=True)131 else:132 raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)133134class StreamingHTTPHandler(urllib2.HTTPHandler):135 """Subclass of `urllib2.HTTPHandler` that uses136 StreamingHTTPConnection as its http connection class."""137138 handler_order = urllib2.HTTPHandler.handler_order - 1139140 def http_open(self, req):141 """Open a StreamingHTTPConnection for the given request"""142 return self.do_open(StreamingHTTPConnection, req)143144 def http_request(self, req):145 """Handle a HTTP request. Make sure that Content-Length is specified146 if we're using an interable value"""147 # Make sure that if we're using an iterable object as the request148 # body, that we've also specified Content-Length149 if req.has_data():150 data = req.get_data()151 if hasattr(data, 'read') or hasattr(data, 'next'):152 if not req.has_header('Content-length'):153 raise ValueError(154 "No Content-Length specified for iterable body")155 return urllib2.HTTPHandler.do_request_(self, req)156157if hasattr(httplib, 'HTTPS'):158 class StreamingHTTPSConnection(_StreamingHTTPMixin,159 httplib.HTTPSConnection):160 """Subclass of `httplib.HTTSConnection` that overrides the `send()`161 method to support iterable body objects"""162163 class StreamingHTTPSHandler(urllib2.HTTPSHandler):164 """Subclass of `urllib2.HTTPSHandler` that uses165 StreamingHTTPSConnection as its http connection class."""166167 handler_order = urllib2.HTTPSHandler.handler_order - 1168169 def https_open(self, req):170 return self.do_open(StreamingHTTPSConnection, req)171172 def https_request(self, req):173 # Make sure that if we're using an iterable object as the request174 # body, that we've also specified Content-Length175 if req.has_data():176 data = req.get_data()177 if hasattr(data, 'read') or hasattr(data, 'next'):178 if not req.has_header('Content-length'):179 raise ValueError(180 "No Content-Length specified for iterable body")181 return urllib2.HTTPSHandler.do_request_(self, req)182183184def register_openers():185 """Register the streaming http handlers in the global urllib2 default186 opener object.187188 Returns the created OpenerDirector object."""189 handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]190 if hasattr(httplib, "HTTPS"):191 handlers.append(StreamingHTTPSHandler)192193 opener = urllib2.build_opener(*handlers)194195 urllib2.install_opener(opener)196197 return opener
added:requests/packages/__init__.py+1 added
1from . import poster
modified:requests/__init__.py+2 added-1 removed
1# -*- coding: utf-8 -*-23from . import packages3from .core import *4from .core import *
modified:requests/core.py+54 added-32 removed
11 unmodified lines
1213import urllib14import urllib21516from .packages.poster.encode import multipart_encode17from .packages.poster.streaminghttp import register_openers181920__title__ = 'requests'18__version__ = '0.2.0'19__build__ = 0x00020021__version__ = '0.2.1'22__build__ = 0x00020123__author__ = 'Kenneth Reitz'24__license__ = 'ISC'25__copyright__ = 'Copyright 2011 Kenneth Reitz'26
26 unmodified lines
53 54 def __init__(self):55 self.url = None56 self.headers = dict()57 self.files = None58 self.method = None59 self.params = {}60 self.data = {}61 self.response = Response()
1 unmodified line
63 self.sent = False64 65 66 def __repr__(self):63 try:64 repr = '<Request [%s]>' % (self.method)67 return '<Request [%s]>' % (self.method)65 except:66 repr = '<Request object>'67 return repr68 69 70 def __setattr__(self, name, value):71 if (name == 'method') and (value):
64 unmodified lines
136 try:137 resp = opener(req)138 self.response.status_code = resp.code139 self.response.headers = resp.info().dict140 if self.method.lower() == 'get':140 if self.method == 'GET':141 self.response.content = resp.read()142 self.response.url = resp.url143144 success = True144 except urllib2.HTTPError, why:145 except urllib2.HTTPError as why:146 self.response.status_code = why.code147148149 elif self.method == 'PUT':150 if (not self.sent) or anyway:151152 if self.files:153 register_openers()154 datagen, headers = multipart_encode(self.files)151 req = _Request(self.url, method='PUT')155 req = _Request(self.url, data=datagen, headers=headers, method='PUT')156153 if self.headers:154 req.headers = self.headers157 if self.headers:158 req.headers.update(self.headers)159156 req.data = self.data160 else:161162 req = _Request(self.url, method='PUT')163164 if self.headers:165 req.headers = self.headers166167 req.data = self.data168169 try:170 opener = self._get_opener()171 resp = opener(req)172173 self.response.status_code = resp.code174 self.response.headers = resp.info().dict175 self.response.content = resp.read()176 self.response.url = resp.url177178 success = True179168 except urllib2.HTTPError, why:180 except urllib2.HTTPError as why:181 self.response.status_code = why.code182183184 elif self.method == 'POST':185 if (not self.sent) or anyway:186187 if self.files:188 register_openers()189 datagen, headers = multipart_encode(self.files)175 req = _Request(self.url, method='POST')190 req = _Request(self.url, data=datagen, headers=headers, method='POST')191177 if self.headers:192 if self.headers:193 req.headers.update(self.headers)194 195 else:196 req = _Request(self.url, method='POST')197 req.headers = self.headers198180 # url encode form data if it's a dict181 if isinstance(self.data, dict):182 req.data = urllib.urlencode(self.data)183 else:184 req.data = self.data199 # url encode form data if it's a dict200 if isinstance(self.data, dict):201 req.data = urllib.urlencode(self.data)202 else:203 req.data = self.data204205 try:206207 opener = self._get_opener()
1 unmodified line
209210 self.response.status_code = resp.code211 self.response.headers = resp.info().dict212 self.response.content = resp.read()213 self.response.url = resp.url214215 success = True216197 except urllib2.HTTPError, why:217 except urllib2.HTTPError as why:218 self.response.status_code = why.code219220 221 self.sent = True if success else False
10 unmodified lines
232 def __init__(self):233 self.content = None234 self.status_code = None235 self.headers = dict()236 self.url = None237 238 def __repr__(self):218 try:219 repr = '<Response [%s]>' % (self.status_code)239 return '<Response [%s]>' % (self.status_code)220 except:221 repr = '<Response object>'222 return repr240241242 243class AuthObject(object):244 """The :class:`AuthObject` is a simple HTTP Authentication token. When245 given to a Requests function, it enables Basic HTTP Authentication for that
54 unmodified lines
300 301 return r.response302303286def post(url, data={}, headers={}, auth=None):304def post(url, data={}, headers={}, files=None, auth=None):305 """Sends a POST request. Returns :class:`Response` object.306307 :param url: URL for the new :class:`Request` object.308 :param data: (optional) Dictionary of POST Data to send with the :class:`Request`.309 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.310 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.311 :param auth: (optional) AuthObject to enable Basic HTTP Auth.312 """313 314 r = Request()296315 316 r.url = url317 r.method = 'POST'318 r.data = data319 320 if files:321 r.files = files322 323 r.headers = headers324 r.auth = _detect_auth(url, auth)325 326 r.send()327 328 return r.response329 330 309def put(url, data='', headers={}, auth=None):331def put(url, data='', headers={}, files={}, auth=None):332 """Sends a PUT request. Returns :class:`Response` object.333334 :param url: URL for the new :class:`Request` object.335 :param data: (optional) Bytes of PUT Data to send with the :class:`Request`.336 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.337 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.338 :param auth: (optional) AuthObject to enable Basic HTTP Auth.339 """340 341 r = Request()342343 r.url = url344 r.method = 'PUT'345 r.data = data323 346 r.files = files347 r.headers = headers348 r.auth = _detect_auth(url, auth)349 350 r.send()
13 unmodified lines
364 r = Request()365366 r.url = url367 r.method = 'DELETE'345 # return response object368 369 r.headers = headers370 r.auth = _detect_auth(url, auth)371
55 unmodified lines
modified:HISTORY.rst+7 added
1History2-------340.2.1 (2011-02-14)5++++++++++++++++++67* Added file attribute to POST and PUT requests for multipart-encode file uploads.8* Added Request.url attribute for context and redirects910110.2.0 (2011-02-14)12++++++++++++++++++1314* Birth!
8 unmodified lines
added:NOTICE+12 added
1Request includes some vendorized python libraries to ease installation.23Poster License4==============56Copyright (c) 2010 Chris AtLee78Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:910The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.1112THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
modified:README.rst+8 added-2 removed
11 unmodified lines
1213- Extremely simple GET, HEAD, POST, PUT, DELETE Requests14 + Simple HTTP Header Request Attachment15 + Simple Data/Params Request Attachment16 + Simple Multipart File Uploads17- Simple Basic HTTP Authentication18 + Simple URL + HTTP Auth Registry1920
44 unmodified lines
65 >>> request.head(url, params={}, headers={} auth=None)66 <request object>67 68 PUT Requests68 >>> request.put(url, data='', headers={}, auth=None)69 >>> request.put(url, data='', headers={}, files={}, auth=None)70 <request object>71 # If files dictionary ( {filename: fileobject, ...} ) is given, a multi-part upload is performed.72 73 POST Requests72 >>> request.post(url, data={}, headers={}, auth=None)74 >>> request.post(url, data={}, headers={}, files={}, auth=None)75 <request object>76 # If files dictionary ( {filename: fileobject, ...} ) is given, a multi-part upload is performed.77 78 DELETE Requests79 >>> request.delete(url, params={}, headers={}, auth=None)80 <request object>
9 unmodified lines
9091 Request.content:92 (Bytes) Received Content9394 Request.url95 (String) URL of response. Useful for detecting redirects. 969798**HTTP Authentication Registry:**99100 You can register AuthObjects to automatically enable HTTP Authentication on requests that contain a registered base URL string.101
34 unmodified lines
modified:setup.py+11 added-8 removed
5 unmodified lines
67from distutils.core import setup8910def publish():11 """Publish to PyPi"""12 os.system("python setup.py sdist upload")1310 11if sys.argv[-1] == "publish":15 publish()12 os.system("python setup.py sdist upload")13 sys.exit()1415if sys.argv[-1] == "test":16 os.system("python test_requests.py")17 sys.exit()18 19required = []2021# if python > 2.6, require simplejson2223setup(24 name='requests',24 version='0.2.0',25 description='Python HTTP Library that\'s actually usable.',25 version='0.2.1',26 description='Awesome Python HTTP Library that\'s actually usable.',27 long_description=open('README.rst').read() + '\n\n' +28 open('HISTORY.rst').read(),29 author='Kenneth Reitz',30 author_email='me@kennethreitz.com',31 url='https://github.com/kennethreitz/requests',32 packages= [33 'requests',34 'requests.packages',35 'requests.packages.poster'36 ],37 install_requires=required,38 license='ISC',39 classifiers=(40 # 'Development Status :: 5 - Production/Stable',41 'Intended Audience :: Developers',42 'Natural Language :: English',40 'License :: OSI Approved :: MIT License',43 'License :: OSI Approved :: ISC License (ISCL)',44 'Programming Language :: Python',45 # 'Programming Language :: Python :: 2.5',46 'Programming Language :: Python :: 2.6',47 'Programming Language :: Python :: 2.7',
4 unmodified lines
modified:test_requests.py+14 added
1#!/usr/bin/env python2# -*- coding: utf-8 -*-345import unittest6from cStringIO import StringIO78import requests910
32 unmodified lines
43 r = requests.get(url, auth=auth)4445 self.assertEqual(r.status_code, 200)4647 def test_POSTBIN_GET_POST_FILES(self):4849 bin = requests.post('http://www.postbin.org/')50 self.assertEqual(bin.status_code, 200)5152 post = requests.post(bin.url, data={'some': 'data'})53 self.assertEqual(post.status_code, 201)5455 post2 = requests.post(bin.url, files={'some': StringIO('data')})56 self.assertEqual(post2.status_code, 201)57585960if __name__ == '__main__':61 unittest.main()