Skip to content
Myr

Merge branch 'release/0.3.0'

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 8b3c4da, f8032e0 · Browse files · 8 files+428 added−271 removed
This commit

State

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

Diff stats

8 files+428 added−271 removed

  • other:+428 added−271 removed

8 files+428 added−271 removed

modified:requests/packages/poster/streaminghttp.py+7 added-5 removed
179 unmodified lines
180 "No Content-Length specified for iterable body")181 return urllib2.HTTPSHandler.do_request_(self, req)182183184def get_handlers():185 handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]186 if hasattr(httplib, "HTTPS"):187 handlers.append(StreamingHTTPSHandler)188 return handlers189 190def register_openers():191 """Register the streaming http handlers in the global urllib2 default192 opener object.193194 Returns the created OpenerDirector object."""189 handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]190 if hasattr(httplib, "HTTPS"):191 handlers.append(StreamingHTTPSHandler)195 opener = urllib2.build_opener(*get_handlers())196193 opener = urllib2.build_opener(*handlers)194197 urllib2.install_opener(opener)198199 return opener
added:requests/async.py+48 added
1# -*- coding: utf-8 -*-23"""4 requests.async5 ~~~~~~~~~~~~~~67 This module implements the main Requests system, after monkey-patching8 the urllib2 module with eventlet or gevent..910 :copyright: (c) 2011 by Kenneth Reitz.11 :license: ISC, see LICENSE for more details.12"""131415from __future__ import absolute_import1617import urllib18import urllib21920from urllib2 import HTTPError212223try:24 import eventlet25 eventlet.monkey_patch()26except ImportError:27 pass2829if not 'eventlet' in locals():30 try:31 from gevent import monkey32 monkey.patch_all()33 except ImportError:34 pass353637if not 'eventlet' in locals():38 raise ImportError('No Async adaptations of urllib2 found!')394041from .core import *424344__all__ = [45 'Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 46 'auth_manager', 'AuthObject','RequestException', 'AuthenticationError', 47 'URLRequired', 'InvalidMethod', 'HTTPError'48]
modified:requests/core.py+278 added-217 removed
9 unmodified lines
10 :license: ISC, see LICENSE for more details.11"""1213from __future__ import absolute_import1415import urllib16import urllib21718from urllib2 import HTTPError19from urlparse import urlparse2019try:20 import eventlet21 eventlet.monkey_patch()22except ImportError:23 pass2425if not 'eventlet' in locals():26 try:27 from gevent import monkey28 monkey.patch_all()29 except ImportError:30 pass3121from .packages.poster.encode import multipart_encode33from .packages.poster.streaminghttp import register_openers22from .packages.poster.streaminghttp import register_openers, get_handlers23242526__title__ = 'requests'37__version__ = '0.2.4'38__build__ = 0x00020427__version__ = '0.3.0'28__build__ = 0x00030029__author__ = 'Kenneth Reitz'30__license__ = 'ISC'31__copyright__ = 'Copyright 2011 Kenneth Reitz'3233__all__ = [34 'Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 35 'auth_manager', 'AuthObject','RequestException', 'AuthenticationError', 36 'URLRequired', 'InvalidMethod', 'HTTPError'37]3844AUTOAUTHS = []39404741class _Request(urllib2.Request):42 """Hidden wrapper around the urllib2.Request object. Allows for manual43 setting of HTTP methods.44 """52 53 def __init__(self, url, data=None, headers={}, origin_req_host=None,54 unverifiable=False, method=None):4546 def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None):47 urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)48 self.method = method4950 def get_method(self):
6 unmodified lines
57class Request(object):58 """The :class:`Request` object. It carries out all functionality of59 Requests. Recommended interface is with the Requests functions.60 """69 6162 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')71 6364 def __init__(self, url=None, headers=dict(), files=None, method=None,73 params=dict(), data=dict(), auth=None, cookiejar=None):65 data=dict(), auth=None, cookiejar=None):66 67 self.url = url68 self.headers = headers69 self.files = files70 self.method = method78 self.params = params71 self.data = data7273 # url encode data if it's a dict74 if hasattr(data, 'items'):75 self._enc_data = urllib.urlencode(data)76 else:77 self._enc_data = data7879 self.response = Response()81 8081 if isinstance(auth, (list, tuple)):82 auth = AuthObject(*auth)83 if not auth:84 auth = auth_manager.get_auth(self.url)85 self.auth = auth86 self.cookiejar = cookiejar87 self.sent = False85 86 888990 def __repr__(self):91 return '<Request [%s]>' % (self.method)89 90 929394 def __setattr__(self, name, value):95 if (name == 'method') and (value):96 if not value in self._METHODS:97 raise InvalidMethod()95 9899 object.__setattr__(self, name, value)97 98 100101102 def _checks(self):103 """Deterministic checks for consistency."""104105 if not self.url:106 raise URLRequired107105 108109 def _get_opener(self):110 """Creates appropriate opener object for urllib2."""111112 _handlers = []113111 if self.auth or self.cookiejar:114 if self.auth:115 if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):116 auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)117 self.auth.handler = self.auth.handler(auth_manager)118 auth_manager.add_auth(self.url, self.auth)119113 if self.auth:120 _handlers.append(self.auth.handler)121115 authr = urllib2.HTTPPasswordMgrWithDefaultRealm()116117 authr.add_password(None, self.url, self.auth.username, self.auth.password)118 auth_handler = urllib2.HTTPBasicAuthHandler(authr)119120 _handlers.append(auth_handler)121122 if self.cookiejar:123124 cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)125 _handlers.append(cookie_handler)126122 _handlers.extend(get_handlers())123 opener = urllib2.build_opener(*_handlers)124 return opener.open129125 else:126 return urllib2.urlopen127128129 def _build_response(self, resp):130 """Build internal Response object from given response."""131 137 self.response.status_code = resp.code138 self.response.headers = resp.info().dict132 self.response.status_code = getattr(resp, 'code', None)133 self.response.headers = getattr(resp.info(), 'dict', None)134 self.response.url = getattr(resp, 'url', None)135 self.response.content = resp.read()140 self.response.url = resp.url136142 137138 @staticmethod139 def _build_url(url, data):140 """Build URLs."""141 142 if urlparse(url).query:143 return '%s&%s' % (url, data)144 else:145 if data:146 return '%s?%s' % (url, data)147 else:148 return url149150151 def send(self, anyway=False):152 """Sends the request. Returns True of successful, false if not.153 If there was an HTTPError during transmission,154 self.response.status_code will contain the HTTPError code.
2 unmodified lines
157158 :param anyway: If True, request will be sent, even if it has159 already been sent.160 """153161 self._checks()155162 success = False163158164 if self.method in ('GET', 'HEAD', 'DELETE'):160 if (not self.sent) or anyway:165 req = _Request(self._build_url(self.url, self._enc_data), method=self.method)166 else:167162 # url encode GET params if it's a dict163 if isinstance(self.params, dict):164 params = urllib.urlencode(self.params)165 else:166 params = self.params168 if self.files:169 register_openers()170171 if self.data:172 self.files.update(self.data)173 174 datagen, headers = multipart_encode(self.files)175 req = _Request(self.url, data=datagen, headers=headers, method=self.method)176 177 else:168 req = _Request(("%s?%s" % (self.url, params)), method=self.method)178 req = _Request(self.url, data=self._enc_data, method=self.method)179170 if self.headers:171 req.headers = self.headers180 if self.headers:181 req.headers = self.headers182183 if not self.sent or anyway:184 try:185 opener = self._get_opener()186 resp = opener(req)187 except urllib2.HTTPError, why:188 self._build_response(why)189 self.response.error = why190 else:191 self._build_response(resp)192 self.response.ok = True193175 try:176 resp = opener(req)177 self._build_response(resp)178 self.response.ok = True194 self.response.cached = False195 else:196 self.response.cached = True197180 except urllib2.HTTPError, why:181 self._build_response(why)182 self.response.error = why198184185 elif self.method == 'PUT':186 if (not self.sent) or anyway:187188 if self.files:189 register_openers()190 datagen, headers = multipart_encode(self.files)191 req = _Request(self.url, data=datagen, headers=headers, method='PUT')192193 if self.headers:194 req.headers.update(self.headers)195196 else:197198 req = _Request(self.url, method='PUT')199200 if self.headers:201 req.headers = self.headers202203 req.data = self.data204205 try:206 opener = self._get_opener()207 resp = opener(req)208209 self._build_response(resp)210 self.response.ok = True211212 except urllib2.HTTPError, why:213 self._build_response(why)214 self.response.error = why215216217 elif self.method == 'POST':218 if (not self.sent) or anyway:219220 if self.files:221 register_openers()222 datagen, headers = multipart_encode(self.files)223 req = _Request(self.url, data=datagen, headers=headers, method='POST')224225 if self.headers:226 req.headers.update(self.headers)227 228 else:229 req = _Request(self.url, method='POST')230 req.headers = self.headers231232 # url encode form data if it's a dict233 if isinstance(self.data, dict):234 req.data = urllib.urlencode(self.data)235 else:236 req.data = self.data237238 try:239 opener = self._get_opener()240 resp = opener(req)241242 self._build_response(resp)243 self.response.ok = True244245 except urllib2.HTTPError, why:246 self._build_response(why)247 self.response.error = why248 199 self.sent = self.response.ok250 200201 return self.sent252 202203204 205class Response(object):206 """The :class:`Request` object. All :class:`Request` objects contain a207 :class:`Request.response <response>` attribute, which is an instance of208 this class.
5 unmodified lines
214 self.headers = dict()215 self.url = None216 self.ok = False217 self.error = None218 self.cached = False267 219220221 def __repr__(self):222 return '<Response [%s]>' % (self.status_code)270 223224225 def __nonzero__(self):226 """Returns true if status_code is 'OK'."""227 return not self.error274 228229230 def raise_for_status(self):231 """Raises stored HTTPError if one exists."""232 if self.error:233 raise self.error234235236237class AuthManager(object):238 """Authentication Manager."""239 240 def __new__(cls):241 singleton = cls.__dict__.get('__singleton__')242 if singleton is not None:243 return singleton244245 cls.__singleton__ = singleton = object.__new__(cls)246247 return singleton248249250 def __init__(self):251 self.passwd = {}252 self._auth = {}253254255 def __repr__(self):256 return '<AuthManager [%s]>' % (self.method)257258259 def add_auth(self, uri, auth):260 """Registers AuthObject to AuthManager."""261 262 uri = self.reduce_uri(uri, False)263 self._auth[uri] = auth264265 def add_password(self, realm, uri, user, passwd):266 """Adds password to AuthManager."""267 # uri could be a single URI or a sequence268 if isinstance(uri, basestring):269 uri = [uri]270 271 reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])272 273 if reduced_uri not in self.passwd:274 self.passwd[reduced_uri] = {}275 self.passwd[reduced_uri] = (user, passwd)276277278 def find_user_password(self, realm, authuri):279 for uris, authinfo in self.passwd.iteritems():280 reduced_authuri = self.reduce_uri(authuri, False)281 for uri in uris:282 if self.is_suburi(uri, reduced_authuri):283 return authinfo284285 return (None, None)286287288 def get_auth(self, uri):289 uri = self.reduce_uri(uri, False)290 return self._auth.get(uri, None)291292293 def reduce_uri(self, uri, default_port=True):294 """Accept authority or URI and extract only the authority and path."""295 # note HTTP URLs do not have a userinfo component296 parts = urllib2.urlparse.urlsplit(uri)297 if parts[1]:298 # URI299 scheme = parts[0]300 authority = parts[1]301 path = parts[2] or '/'302 else:303 # host or host:port304 scheme = None305 authority = uri306 path = '/'307 host, port = urllib2.splitport(authority)308 if default_port and port is None and scheme is not None:309 dport = {"http": 80,310 "https": 443,311 }.get(scheme)312 if dport is not None:313 authority = "%s:%d" % (host, dport)314 return authority, path315316 317 def is_suburi(self, base, test):318 """Check if test is below base in a URI tree319320 Both args must be URIs in reduced form.321 """322 if base == test:323 return True324 if base[0] != test[0]:325 return False326 common = urllib2.posixpath.commonprefix((base[1], test[1]))327 if len(common) == len(base[1]):328 return True329 return False330331332 def empty(self):333 self.passwd = {}334335336 def remove(self, uri, realm=None):337 # uri could be a single URI or a sequence338 if isinstance(uri, basestring):339 uri = [uri]340341 for default_port in True, False:342 reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])343 del self.passwd[reduced_uri][realm]344345346 def __contains__(self, uri):347 # uri could be a single URI or a sequence348 if isinstance(uri, basestring):349 uri = [uri]350351 uri = tuple([self.reduce_uri(u, False) for u in uri])352353 if uri in self.passwd:354 return True355356 return False357358auth_manager = AuthManager()359360361362class AuthObject(object):363 """The :class:`AuthObject` is a simple HTTP Authentication token. When364 given to a Requests function, it enables Basic HTTP Authentication for that365 Request. You can also enable Authorization for domain realms with AutoAuth.366 See AutoAuth for more details.287 367368 :param username: Username to authenticate with.369 :param password: Password for given username.370 :param realm: (optional) the realm this auth applies to371 :param handler: (optional) basic || digest || proxy_basic || proxy_digest372 """291 292 def __init__(self, username, password):373374 _handlers = {375 'basic': urllib2.HTTPBasicAuthHandler,376 'digest': urllib2.HTTPDigestAuthHandler,377 'proxy_basic': urllib2.ProxyBasicAuthHandler,378 'proxy_digest': urllib2.ProxyDigestAuthHandler379 }380381 def __init__(self, username, password, handler='basic', realm=None):382 self.username = username383 self.password = password384 self.realm = realm385386 if isinstance(handler, basestring):387 self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)388 else:389 self.handler = handler390391392393394def request(method, url, **kwargs):395 """Sends a `method` request. Returns :class:`Response` object.396397 :param method: method for the new :class:`Request` object.398 :param url: URL for the new :class:`Request` object.399 :param params: (optional) Dictionary of GET/HEAD/DELETE Parameters to send with the :class:`Request`.400 :param data: (optional) Bytes/Dictionary of PUT/POST Data to send with the :class:`Request`.401 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.402 :param cookies: (optional) CookieJar object to send with the :class:`Request`.403 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.404 :param auth: (optional) AuthObject to enable Basic HTTP Auth.405 """406 data = kwargs.pop('data', dict()) or kwargs.pop('params', dict())407408 r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', {}),409 cookiejar=kwargs.pop('cookies', None), files=kwargs.pop('files', None),410 auth=kwargs.pop('auth', auth_manager.get_auth(url)))411 r.send()412413 return r.response414415416def get(url, params={}, headers={}, cookies=None, auth=None):417 """Sends a GET request. Returns :class:`Response` object.418419 :param url: URL for the new :class:`Request` object.
2 unmodified lines
422 :param cookies: (optional) CookieJar object to send with the :class:`Request`.423 :param auth: (optional) AuthObject to enable Basic HTTP Auth.424 """425 308 r = Request(method='GET', url=url, params=params, headers=headers,309 cookiejar=cookies, auth=_detect_auth(url, auth))310 r.send()311 312 return r.response426 return request('GET', url, params=params, headers=headers, cookiejar=cookies, auth=auth)427428429def head(url, params={}, headers={}, cookies=None, auth=None):430 """Sends a HEAD request. Returns :class:`Response` object.
3 unmodified lines
434 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.435 :param cookies: (optional) CookieJar object to send with the :class:`Request`.436 :param auth: (optional) AuthObject to enable Basic HTTP Auth.437 """324 r = Request(method='HEAD', url=url, params=params, headers=headers,325 cookiejar=cookies, auth=_detect_auth(url, auth))326 r.send()327 328 return r.response438439 return request('HEAD', url, params=params, headers=headers, cookiejar=cookies, auth=auth)440441442def post(url, data={}, headers={}, files=None, cookies=None, auth=None):443 """Sends a POST request. Returns :class:`Response` object.444445 :param url: URL for the new :class:`Request` object.335 :param data: (optional) Dictionary of POST Data to send with the :class:`Request`.446 :param data: (optional) Dictionary of POST data to send with the :class:`Request`.447 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.448 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.449 :param cookies: (optional) CookieJar object to send with the :class:`Request`.450 :param auth: (optional) AuthObject to enable Basic HTTP Auth.451 """341 342 r = Request(method='POST', url=url, data=data, headers=headers,343 files=files, cookiejar=cookies, auth=_detect_auth(url, auth))344 r.send()345 346 return r.response347 348 452453 return request('POST', url, data=data, headers=headers, files=files, cookiejar=cookies, auth=auth)454455456def put(url, data='', headers={}, files={}, cookies=None, auth=None):457 """Sends a PUT request. Returns :class:`Response` object.458459 :param url: URL for the new :class:`Request` object.353 :param data: (optional) Bytes of PUT Data to send with the :class:`Request`.460 :param params: (optional) Bytes of PUT Data to send with the :class:`Request`.461 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.462 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.463 :param cookies: (optional) CookieJar object to send with the :class:`Request`.464 :param auth: (optional) AuthObject to enable Basic HTTP Auth.465 """466360 r = Request(method='PUT', url=url, data=data, headers=headers, files=files,361 cookiejar=cookies, auth=_detect_auth(url, auth))362 r.send()363 364 return r.response467 return request('PUT', url, data=data, headers=headers, files=files, cookiejar=cookies, auth=auth)468366 469470def delete(url, params={}, headers={}, cookies=None, auth=None):471 """Sends a DELETE request. Returns :class:`Response` object.472473 :param url: URL for the new :class:`Request` object.371 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.474 :param params: (optional) Dictionary of DELETE Parameters to send with the :class:`Request`.475 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.476 :param cookies: (optional) CookieJar object to send with the :class:`Request`.477 :param auth: (optional) AuthObject to enable Basic HTTP Auth.478 """376 377 r = Request(method='DELETE', url=url, params=params, headers=headers,378 cookiejar=cookies, auth=_detect_auth(url, auth))379 r.send()380 381 return r.response479480 return request('DELETE', url, params=params, headers=headers, cookiejar=cookies, auth=auth)481384def add_autoauth(url, authobject):385 """Registers given AuthObject to given URL domain. for auto-activation.386 Once a URL is registered with an AuthObject, the configured HTTP387 Authentication will be used for all requests with URLS containing the given388 URL string.482390 Example: ::391 >>> c_auth = requests.AuthObject('kennethreitz', 'xxxxxxx')392 >>> requests.add_autoauth('https://convore.com/api/', c_auth)393 >>> r = requests.get('https://convore.com/api/account/verify.json')394 # Automatically HTTP Authenticated! Wh00t!483396 :param url: Base URL for given AuthObject to auto-activate for.397 :param authobject: AuthObject to auto-activate.398 """399400 global AUTOAUTHS401 402 AUTOAUTHS.append((url, authobject))403404405def _detect_auth(url, auth):406 """Returns registered AuthObject for given url if available, defaulting to407 given AuthObject.408 """409410 return _get_autoauth(url) if not auth else auth411412 413def _get_autoauth(url):414 """Returns registered AuthObject for given url if available."""415 416 for (autoauth_url, auth) in AUTOAUTHS:417 if autoauth_url in url: 418 return auth419 420 return None421422484class RequestException(Exception):485 """There was an ambiguous exception that occured while handling your486 request."""487488class AuthenticationError(RequestException):489 """The authentication credentials provided were invalid."""429 490491class URLRequired(RequestException):492 """A valid URL is required to make a request."""432 493494class InvalidMethod(RequestException):495 """An inappropriate method was attempted."""
modified:AUTHORS+2 added
10 unmodified lines
11```````````````````````1213- Various Pocoo Members14- Chris Adams15- Flavio Percoco Premoli16- Dj Gilcrease
added:HACKING+15 added
1Where possible, please follow PEP8 with regard to coding style. Sometimes the2line length restriction is too hard to follow, so don't bend over backwards3there.45Triple-quotes should always be """, single quotes are ' unless using " would6result in less escaping within the string.78All modules, functions, and methods should be well documented reStructuredText9for Sphinx AutoDoc.1011All functionality should be available in pure Python. Optional C (via Cython)12implementations may be written for performance reasons, but should never13replace the Python implementation.1415Lastly, don't take yourself too seriously :)
modified:HISTORY.rst+12 added
1History2-------340.3.0 (2011-02-25)5++++++++++++++++++67* Automatic Authentication API Change8* Smarter Query URL Parameterization9* Allow file uploads and POST data together10* New Authentication Manager System11 - Simpler Basic HTTP System12 - Supports all build-in urllib2 Auths13 - Allows for custom Auth Handlers1415160.2.4 (2011-02-19)17++++++++++++++++++1819* Python 2.5 Support
41 unmodified lines
modified:README.rst+33 added-30 removed
1Requests: The Simple (e.g. usable) HTTP Module2==============================================34Most existing Python modules for dealing HTTP requests are insane. I have to look up *everything* that I want to do. Most of my worst Python experiences are a result of the various built-in HTTP libraries (yes, even worse than Logging). 4Most existing Python modules for dealing HTTP requests are insane. I have to look up *everything* that I want to do. Most of my worst Python experiences are a result of the various built-in HTTP libraries (yes, even worse than Logging).56But this one's different. This one's going to be awesome. And simple.78Really simple. 8Really simple.910Features11--------12
1 unmodified line
14 + Simple HTTP Header Request Attachment15 + Simple Data/Params Request Attachment16 + Simple Multipart File Uploads17 + CookieJar Support18 19- Simple Basic HTTP Authentication1819- Simple Authentication20 + Simple URL + HTTP Auth Registry212223Usage
5 unmodified lines
29 >>> r = requests.get('http://google.com')303132HTTPS? Basic Authentication? ::33 3334 >>> r = requests.get('https://convore.com/api/account/verify.json')35 >>> r.status_code36 4013738 3839Uh oh, we're not authorized! Let's add authentication. ::40 41 >>> conv_auth = requests.AuthObject('requeststest', 'requeststest')4041 >>> conv_auth = ('requeststest', 'requeststest')42 >>> r = requests.get('https://convore.com/api/account/verify.json', auth=conv_auth)43 4344 >>> r.status_code45 200 46 45 2004647 >>> r.headers['content-type']48 'application/json'49 4950 >>> r.content51 '{"username": "requeststest", "url": "/users/requeststest/", "id": "9408", "img": "censored-long-url"}'52535455API56---57 5758**Requests:**5960All request functions return a Response object (see below).6162If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.63If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.64 6465 GET Requests66 >>> request.get(url, params={}, headers={}, cookies=None, auth=None)67 <request object>68 6869 HEAD Requests70 >>> request.head(url, params={}, headers={}, cookies=None, auth=None)71 <request object>72 7273 PUT Requests74 >>> request.put(url, data='', headers={}, files={}, cookies=None, auth=None)75 <request object>76 7677 POST Requests78 >>> request.post(url, data={}, headers={}, files={}, cookies=None, auth=None)79 <request object>80 8081 DELETE Requests82 >>> request.delete(url, params={}, headers={}, cookies=None, auth=None)83 <request object>84 848586**Responses:**87 88 Response.status_code:8788 Response.status_code89 (Integer) Received HTTP Status Code Response9091 Response.headers:91 Response.headers92 (Dictionary) Received HTTP Response Headers9394 Response.content:94 Response.content95 (Bytes) Received Content9697 Response.url98 (String) URL of response. Useful for detecting redirects. 99 98 (String) URL of response. Useful for detecting redirects.99100 Response.ok101 (Bool) True if no errors occurred during the request, and the status_code is kosher.102 102103 Response.cached104 (Bool) True if Response.content is stored within the object.105106 Response.error107 (HTTPError) If an HTTPError occurred (e.g. status of 404), Otherwise this is None.105 108109 Response.raise_for_status()110 Raises HTTPError if a request is not kosher.111112113**HTTP Authentication Registry:**114115 You can register AuthObjects to automatically enable HTTP Authentication on requests that contain a registered base URL string.116114 >>> requests.add_autoauth(url, authobject)117 >>> requests.auth_manager.add_auth(url, authobject)118119120121Installation
1 unmodified line
123124To install requests, simply: ::125126 $ pip install requests124 127128Or, if you absolutely must: ::129130 $ easy_install requests131132But, you really shouldn't do that.130 133134135136Contribute137----------138139If you'd like to contribute, simply fork `the repository`_, commit your changes to the **develop** branch (or branch off of it), and send a pull request. Make sure you add yourself to AUTHORS_.
13 unmodified lines
modified:test_requests.py+33 added-19 removed
6 unmodified lines
789class RequestsTestSuite(unittest.TestCase):10 """Requests test cases."""11 1112 def setUp(self):13 pass1415 def tearDown(self):16 """Teardown."""17 pass18 1819 def test_invalid_url(self):20 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')212222 def test_HTTP_200_OK_GET(self):23 r = requests.get('http://google.com')24 self.assertEqual(r.status_code, 200)252726 def test_HTTPS_200_OK_GET(self):27 r = requests.get('https://google.com')28 self.assertEqual(r.status_code, 200)2930 def test_HTTP_200_OK_GET_WITH_PARAMS(self):3132 heads = {'User-agent': 'Mozilla/5.0'}33 34 r = requests.get('http://www.google.com/search', params={'q': 'test'}, headers=heads)35 self.assertEqual(r.status_code, 200)363738 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):3940 heads = {'User-agent': 'Mozilla/5.0'}4142 r = requests.get('http://google.com/search?test=true', params={'q': 'test'}, headers=heads)43 self.assertEqual(r.status_code, 200)44 45 def test_HTTP_200_OK_HEAD(self):46 r = requests.head('http://google.com')47 self.assertEqual(r.status_code, 200)483749 def test_HTTPS_200_OK_HEAD(self):50 r = requests.head('https://google.com')51 self.assertEqual(r.status_code, 200)524253 def test_AUTH_HTTPS_200_OK_GET(self):44 auth = requests.AuthObject('requeststest', 'requeststest')54 auth = ('requeststest', 'requeststest')55 url = 'https://convore.com/api/account/verify.json'56 r = requests.get(url, auth=auth)5758 self.assertEqual(r.status_code, 200)595051 requests.add_autoauth(url, auth)5260 r = requests.get(url)61 self.assertEqual(r.status_code, 200)6263 # reset auto authentication57 requests.AUTOAUTHS = []64 requests.auth_manager.empty()65596066 def test_POSTBIN_GET_POST_FILES(self):6768 bin = requests.post('http://www.postbin.org/')69 print bin.url70 self.assertEqual(bin.status_code, 200)6571 72 post = requests.post(bin.url, data={'some': 'data'})73 self.assertEqual(post.status_code, 201)7475 post2 = requests.post(bin.url, files={'some': open('test_requests.py')})76 self.assertEqual(post2.status_code, 201)7778 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):7980 bin = requests.post('http://www.postbin.org/')81 82 self.assertEqual(bin.status_code, 200)8384 post2 = requests.post(bin.url, files={'some': open('test_requests.py')}, data={'some': 'data'})85 self.assertEqual(post2.status_code, 201)8687 def test_nonzero_evaluation(self):88 r = requests.get('http://google.com/some-404-url')89 self.assertEqual(bool(r), False)90 91 r = requests.get('http://google.com/')92 self.assertEqual(bool(r), True)798093 94 def test_request_ok_set(self):95 r = requests.get('http://google.com/some-404-url')96 self.assertEqual(r.ok, False)848597 98 def test_status_raising(self):99 r = requests.get('http://google.com/some-404-url')100 self.assertRaises(requests.HTTPError, r.raise_for_status)89101 102 r = requests.get('http://google.com/')103 self.assertFalse(r.error)104 r.raise_for_status()105 106107108109if __name__ == '__main__':110 unittest.main()