Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Small changes to make the code more PEP8 compliant #887

Merged
merged 15 commits into from

7 participants

@rvoicilas

No description provided.

sweenzor and others added some commits
@sweenzor sweenzor Handle encoding of `None` when decoding unicode
If encoding is None, decoding will throw the following TypeError:
TypeError: unicode() argument 2 must be string, not None

If this is the case, attempt to run without any set encoding
2bb49ff
@sweenzor sweenzor Simplify error handling when decoding unicode eb6a6b1
@yegle yegle Python 3.3 compatible update
httplib.cookiejar.DefaultCookiePolicy changed its implementation of
set_ok_verifiability.
e656222
@legoktm legoktm Use __iter__ rather than the inefficient nested for loops 4f9e552
@yegle yegle Update: @property decorator instead of __getattr__ 22fdecb
@kennethreitz v0.14.1 ed8a3f3
@sigmavirus24 sigmavirus24 Only register callable items in lists
Prior to this, you could sneak a list of anything to register_hook and it
would accept it. This will check if the items in the list are callable before
registering them. Also added a regression test to make sure if this gets
changed it will be noticed.
4e6cf21
@kennethreitz new classifiers for 3.2+ 46fd297
@kennethreitz why not 582a53f
@kennethreitz order fix e60e82c
@kennethreitz padding 1444d90
@kennethreitz wording cc1b9da
@kennethreitz update 3e30196
@tokuda109 tokuda109 declare the encoding 5ec2c96
@rvoicilas rvoicilas Making the code more PEP8 compliant 820dfb0
@kennethreitz kennethreitz reopened this
@kennethreitz

Agreed on all fronts. Thanks so much!

:sparkles: :cake: :sparkles:

@kennethreitz kennethreitz merged commit c631627 into from
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Oct 8, 2012
  1. @sweenzor @rvoicilas

    Handle encoding of `None` when decoding unicode

    sweenzor authored rvoicilas committed
    If encoding is None, decoding will throw the following TypeError:
    TypeError: unicode() argument 2 must be string, not None
    
    If this is the case, attempt to run without any set encoding
  2. @sweenzor @rvoicilas

    Simplify error handling when decoding unicode

    sweenzor authored rvoicilas committed
  3. @yegle @rvoicilas

    Python 3.3 compatible update

    yegle authored rvoicilas committed
    httplib.cookiejar.DefaultCookiePolicy changed its implementation of
    set_ok_verifiability.
  4. @legoktm @rvoicilas
  5. @yegle @rvoicilas

    Update: @property decorator instead of __getattr__

    yegle authored rvoicilas committed
  6. @rvoicilas

    v0.14.1

    authored rvoicilas committed
  7. @sigmavirus24 @rvoicilas

    Only register callable items in lists

    sigmavirus24 authored rvoicilas committed
    Prior to this, you could sneak a list of anything to register_hook and it
    would accept it. This will check if the items in the list are callable before
    registering them. Also added a regression test to make sure if this gets
    changed it will be noticed.
  8. @rvoicilas

    new classifiers for 3.2+

    authored rvoicilas committed
  9. @rvoicilas

    why not

    authored rvoicilas committed
  10. @rvoicilas

    order fix

    authored rvoicilas committed
  11. @rvoicilas

    padding

    authored rvoicilas committed
  12. @rvoicilas

    wording

    authored rvoicilas committed
  13. @rvoicilas

    update

    authored rvoicilas committed
  14. @tokuda109 @rvoicilas

    declare the encoding

    tokuda109 authored rvoicilas committed
  15. @rvoicilas
This page is out of date. Refresh to see the latest.
View
8 HISTORY.rst
@@ -3,6 +3,14 @@
History
-------
+0.14.1 (2012-10-01)
++++++++++++++++++++
+
+- Python 3.3 Compatibility
+- Simply default accept-encoding
+- Bugfixes
+
+
0.14.0 (2012-09-02)
++++++++++++++++++++
View
9 docs/_templates/sidebarintro.html
@@ -25,6 +25,15 @@
src="https://www.gittip.com/kennethreitz/widget.html"
width="48pt" height="20pt"></iframe>
</p>
+
+<p>
+ If your organization uses Requests, consider financial support:
+
+</p>
+<p>
+ <a href="http://gum.co/RRZc" class="gumroad-button">Requests Pro</a><script type="text/javascript" src="https://gumroad.com/js/gumroad-button.js"></script>
+</p>
+
<h3>Feedback</h3>
<p>
Feedback is greatly appreciated. If you have any questions, comments,
View
11 docs/_templates/sidebarlogo.html
@@ -22,4 +22,13 @@
<iframe style="border: 0; margin: 0; padding: 0;"
src="https://www.gittip.com/kennethreitz/widget.html"
width="48pt" height="20pt"></iframe>
-</p>
+</p>
+
+<p>
+ If your organization uses Requests, consider financial support:
+
+</p>
+
+<p>
+ <a href="http://gum.co/RRZc" class="gumroad-button">Requests Pro</a><script type="text/javascript" src="https://gumroad.com/js/gumroad-button.js"></script>
+</p>
View
4 requests/__init__.py
@@ -42,8 +42,8 @@
"""
__title__ = 'requests'
-__version__ = '0.14.0'
-__build__ = 0x001400
+__version__ = '0.14.1'
+__build__ = 0x001401
__author__ = 'Kenneth Reitz'
__license__ = 'ISC'
__copyright__ = 'Copyright 2012 Kenneth Reitz'
View
2  requests/auth.py
@@ -94,7 +94,7 @@ def __call__(self, r):
# to preserve body.
r.url, r.headers, _ = self.client.sign(
unicode(r.full_url), unicode(r.method), None, r.headers)
- elif decoded_body != None and contenttype in (CONTENT_TYPE_FORM_URLENCODED, ''):
+ elif decoded_body is not None and contenttype in (CONTENT_TYPE_FORM_URLENCODED, ''):
# Normal signing
if not contenttype:
r.headers['Content-Type'] = CONTENT_TYPE_FORM_URLENCODED
View
2  requests/compat.py
@@ -115,5 +115,5 @@
builtin_str = str
str = str
bytes = bytes
- basestring = (str,bytes)
+ basestring = (str, bytes)
numeric_types = (int, float)
View
16 requests/cookies.py
@@ -1,3 +1,5 @@
+# -*- coding: utf-8 -*-
+
"""
Compatibility code to be able to use `cookielib.CookieJar` with requests.
@@ -67,6 +69,10 @@ def add_unredirected_header(self, name, value):
def get_new_headers(self):
return self._new_headers
+ @property
+ def unverifiable(self):
+ return self.is_unverifiable()
+
class MockResponse(object):
"""Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
@@ -229,7 +235,7 @@ def get_dict(self, domain=None, path=None):
Python dict of name-value pairs of cookies that meet the requirements."""
dictionary = {}
for cookie in iter(self):
- if (domain == None or cookie.domain == domain) and (path == None
+ if (domain is None or cookie.domain == domain) and (path is None
or cookie.path == path):
dictionary[cookie.name] = cookie.value
return dictionary
@@ -273,7 +279,7 @@ def _find_no_duplicates(self, name, domain=None, path=None):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
- if toReturn != None: # if there are multiple cookies that meet passed in criteria
+ if toReturn is not None: # if there are multiple cookies that meet passed in criteria
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
toReturn = cookie.value # we will eventually return this as long as no cookie conflict
@@ -318,8 +324,7 @@ def create_cookie(name, value, **kwargs):
comment=None,
comment_url=None,
rest={'HttpOnly': None},
- rfc2109=False,
- )
+ rfc2109=False,)
badargs = set(kwargs) - set(result)
if badargs:
@@ -354,8 +359,7 @@ def morsel_to_cookie(morsel):
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
rest={'HttpOnly': morsel['httponly']},
- rfc2109=False,
- )
+ rfc2109=False,)
return c
View
1  requests/hooks.py
@@ -45,5 +45,4 @@ def dispatch_hook(key, hooks, hook_data):
if _hook_data is not None:
hook_data = _hook_data
-
return hook_data
View
12 requests/models.py
@@ -111,7 +111,7 @@ def __init__(self,
# Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})
self.proxies = dict(proxies or [])
- for proxy_type,uri_ref in list(self.proxies.items()):
+ for proxy_type, uri_ref in list(self.proxies.items()):
if not uri_ref:
del self.proxies[proxy_type]
@@ -462,10 +462,10 @@ def path_url(self):
def register_hook(self, event, hook):
"""Properly register a hook."""
- if isinstance(hook, (list, tuple, set)):
- self.hooks[event].extend(hook)
- else:
+ if callable(hook):
self.hooks[event].append(hook)
+ elif hasattr(hook, '__iter__'):
+ self.hooks[event].extend(h for h in hook if callable(h))
def deregister_hook(self, event, hook):
"""Deregister a previously registered hook.
@@ -828,10 +828,12 @@ def text(self):
# Decode unicode from given encoding.
try:
content = str(self.content, encoding, errors='replace')
- except LookupError:
+ except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
#
+ # A TypeError can be raised if encoding is None
+ #
# So we try blindly encoding.
content = str(self.content, errors='replace')
View
12 requests/utils.py
@@ -311,11 +311,8 @@ def dict_from_cookiejar(cj):
cookie_dict = {}
- for _, cookies in list(cj._cookies.items()):
- for _, cookies in list(cookies.items()):
- for cookie in list(cookies.values()):
- # print cookie
- cookie_dict[cookie.name] = cookie.value
+ for cookie in cj:
+ cookie_dict[cookie.name] = cookie.value
return cookie_dict
@@ -381,13 +378,15 @@ def stream_decode_response_unicode(iterator, r):
if rv:
yield rv
+
def iter_slices(string, slice_length):
"""Iterate over slices of a string."""
pos = 0
while pos < len(string):
- yield string[pos:pos+slice_length]
+ yield string[pos:pos + slice_length]
pos += slice_length
+
def get_unicode_from_response(r):
"""Returns the requested content back in unicode.
@@ -546,6 +545,7 @@ def default_user_agent():
'%s/%s' % (platform.system(), platform.release()),
])
+
def parse_header_links(value):
"""Return a dict of parsed link headers proxies.
View
2  setup.py
@@ -65,6 +65,8 @@
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
+ 'Programming Language :: Python :: 3.2',
+ 'Programming Language :: Python :: 3.3',
),
)
View
6 tests/informal/test_leaked_connections.py
@@ -4,7 +4,11 @@
the body of the request is not read.
"""
-import gc, os, subprocess, requests, sys
+import gc
+import os
+import requests
+import subprocess
+import sys
def main():
View
12 tests/test_proxies.py
@@ -1,7 +1,9 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-import sys, os, unittest
+import os
+import sys
+import unittest
# Path hack.
sys.path.insert(0, os.path.abspath('..'))
@@ -14,13 +16,13 @@ class HTTPSProxyTest(unittest.TestCase):
smoke_url = "https://github.com"
def test_empty_https_proxy(self):
- proxy = {"https" : "" }
- result = requests.get(self.smoke_url, verify=False, proxies = proxy)
+ proxy = {"https": ""}
+ result = requests.get(self.smoke_url, verify=False, proxies=proxy)
self.assertEqual(result.status_code, 200)
def test_empty_http_proxy(self):
- proxy = {"http" : "" }
- result = requests.get(self.smoke_url, proxies = proxy)
+ proxy = {"http": ""}
+ result = requests.get(self.smoke_url, proxies=proxy)
self.assertEqual(result.status_code, 200)
if __name__ == '__main__':
View
9 tests/test_requests.py
@@ -51,6 +51,7 @@ def setUp(self):
# time.sleep(1)
_httpbin = True
+
class TestBaseMixin(object):
def assertCookieHas(self, cookie, **kwargs):
@@ -60,6 +61,7 @@ def assertCookieHas(self, cookie, **kwargs):
message = 'Failed comparison for %s: %s != %s' % (attr, cookie_attr, expected_value)
self.assertEqual(cookie_attr, expected_value, message)
+
class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):
"""Requests test cases."""
@@ -778,6 +780,10 @@ def assert_hooks_are_callable(hooks):
r = requests.models.Request(hooks={'args': hooks})
assert_hooks_are_callable(r.hooks)
+ hooks.append('string that should not be registered')
+ r = requests.models.Request(hooks={'args': hooks})
+ assert_hooks_are_callable(r.hooks)
+
def test_session_persistent_cookies(self):
s = requests.session()
@@ -899,7 +905,7 @@ def test_connection_error(self):
def test_connection_error_with_safe_mode(self):
config = {'safe_mode': True}
r = get('http://localhost:1/nope', allow_redirects=False, config=config)
- assert r.content == None
+ assert r.content is None
# def test_invalid_content(self):
# # WARNING: if you're using a terrible DNS provider (comcast),
@@ -1034,7 +1040,6 @@ def test_danger_mode_redirects(self):
s.config['danger_mode'] = True
s.get(httpbin('redirect', '4'))
-
def test_empty_response(self):
r = requests.get(httpbin('status', '404'))
r.text
View
3  tests/test_requests_ext.py
@@ -2,7 +2,8 @@
# -*- coding: utf-8 -*-
# Path hack.
-import sys, os
+import os
+import sys
sys.path.insert(0, os.path.abspath('..'))
import unittest
View
4 tests/test_requests_https.py
@@ -1,8 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-import sys, os
-import json
+import os
+import sys
import unittest
# Path hack.
Something went wrong with that request. Please try again.