8000 Fix flake8 violations · python-telegram-bot/urllib3@cb79107 · GitHub
[go: up one dir, main page]

Skip to content
This repository was archived by the owner on May 21, 2023. It is now read-only.

Commit cb79107

Browse files
committed
Fix flake8 violations
Add tox rule to prevent regressions.
1 parent 3bd6340 commit cb79107

24 files changed

+137
-73
lines changed

.travis.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ env:
1414
- GAE_PYTHONPATH=${HOME}/.cache/google_appengine
1515
- PYTHONWARNINGS=always::DeprecationWarning
1616
matrix:
17+
- TOXENV=flake8-py3
1718
- TOXENV=py26
1819
- TOXENV=py27
1920
- TOXENV=py32

CONTRIBUTORS.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,5 +178,8 @@ In chronological order:
178178
* Evan Meagher <https://evanmeagher.net>
179179
* Bugfix related to `memoryview` usage in PyOpenSSL adapter
180180

181+
* John Vandenberg <jayvdb@gmail.com>
182+
* Python 2.6 fixes; pyflakes and pep8 compliance
183+
181184
* [Your name or handle] <[email or website]>
182185
* [Brief summary of your changes]

dummyserver/handlers.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ def __init__(self, body='', status='200 OK', headers=None): 9E88
2828
def __call__(self, request_handler):
2929
status, reason = self.status.split(' ', 1)
3030
request_handler.set_status(int(status), reason)
31-
for header,value in self.headers:
32-
request_handler.add_header(header,value)
31+
for header, value in self.headers:
32+
request_handler.add_header(header, value)
3333

3434
# chunked
3535
if isinstance(self.body, list):
@@ -48,6 +48,7 @@ def __call__(self, request_handler):
4848

4949
RETRY_TEST_NAMES = collections.defaultdict(int)
5050

51+
5152
class TestingApp(RequestHandler):
5253
"""
5354
Simple app that performs various operations, useful for testing an HTTP
@@ -136,8 +137,8 @@ def upload(self, request):
136137
files_ = request.files.get(param)
137138

138139
if len(files_) != 1:
139-
return Response("Expected 1 file for '%s', not %d" %(param, len(files_)),
140-
status='400 Bad Request')
140+
return Response("Expected 1 file for '%s', not %d" % (param, len(files_)),
141+
status='400 Bad Request')
141142
file_ = files_[0]
142143

143144
data = file_['body']
@@ -277,7 +278,7 @@ def _parse_header(line):
277278
value = p[i + 1:].strip()
278279
params.append((name, value))
279280
params = email.utils.decode_params(params)
280-
params.pop(0) # get rid of the dummy again
281+
params.pop(0) # get rid of the dummy again
281282
pdict = {}
282283
for name, value in params:
283284
value = email.utils.collapse_rfc2231_value(value)

dummyserver/proxy.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,22 +45,23 @@ def get(self):
4545

4646
def handle_response(response):
4747
if response.error and not isinstance(response.error,
48-
tornado.httpclient.HTTPError):
48+
tornado.httpclient.HTTPError):
4949
self.set_status(500)
5050
self.write('Internal server error:\n' + str(response.error))
5151
self.finish()
5252
else:
5353
self.set_status(response.code)
5454
for header in ('Date', 'Cache-Control', 'Server',
55-
'Content-Type', 'Location'):
55+
'Content-Type', 'Location'):
5656
v = response.headers.get(header)
5757
if v:
5858
self.set_header(header, v)
5959
if response.body:
6060
self.write(response.body)
6161
self.finish()
6262

63-
req = tornado.httpclient.HTTPRequest(url=self.request.uri,
63+
req = tornado.httpclient.HTTPRequest(
64+
url=self.request.uri,
6465
method=self.request.method, body=self.request.body,
6566
headers=self.request.headers, follow_redirects=False,
6667
allow_nonstandard_methods=True)
@@ -133,5 +134,5 @@ def run_proxy(port, start_ioloop=True):
133134
if len(sys.argv) > 1:
134135
port = int(sys.argv[1])
135136

136-
print ("Starting HTTP proxy on port %d" % port)
137+
print("Starting HTTP proxy on port %d" % port)
137138
run_proxy(port)

dummyserver/server.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
NO_SAN_CA = os.path.join(CERTS_PATH, 'cacert.no_san.pem')
4040
DEFAULT_CA_DIR = os.path.join(CERTS_PATH, 'ca_path_test')
4141

42+
4243
def _has_ipv6(host):
4344
""" Returns True if the system can bind an IPv6 address. """
4445
sock = None

dummyserver/testcase.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ def _start_server(cls, socket_handler):
4242
@classmethod
4343
def start_response_handler(cls, response, num=1, block_send=None):
4444
ready_event = threading.Event()
45+
4546
def socket_handler(listener):
4647
for _ in range(num):
4748
ready_event.set()
@@ -61,9 +62,9 @@ def socket_handler(listener):
6162
@classmethod
6263
def start_basic_handler(cls, **kw):
6364
return cls.start_response_handler(
64-
b'HTTP/1.1 200 OK\r\n'
65-
b'Content-Length: 0\r\n'
66-
b'\r\n', **kw)
65+
b'HTTP/1.1 200 OK\r\n'
66+
b'Content-Length: 0\r\n'
67+
b'\r\n', **kw)
6768

6869
@classmethod
6970
def tearDownClass(cls):

setup.cfg

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ cover-min-percentage=100
77
cover-erase=true
88

99
[flake8]
10+
exclude=./docs/conf.py,./test/*,./urllib3/packages/*
1011
max-line-length=99
1112

1213
[wheel]

setup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66
import re
77

88
try:
9-
import setuptools
9+
import setuptools # noqa: unused
1010
except ImportError:
11-
pass # No 'develop' command, oh well.
11+
pass # No 'develop' command, oh well.
1212

1313
base_path = os.path.dirname(__file__)
1414

tox.ini

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[tox]
2-
envlist = py26, py27, py32, py33, py34, pypy
2+
envlist = flake8-py3, py26, py27, py32, py33, py34, pypy
33

44
[testenv]
55
deps= -r{toxinidir}/dev-requirements.txt
@@ -27,3 +27,11 @@ commands=
2727
setenv =
2828
PYTHONPATH={env:GAE_PYTHONPATH:}
2929
{[testenv]setenv}
30+
31+
[testenv:flake8-py3]
32+
basepython = python3.4
33+
deps=
34+
flake8
35+
commands=
36+
flake8 --version
37+
flake8

urllib3/__init__.py

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
"""
22
urllib3 - Thread-safe connection pooling and re-using.
33
"""
4-
5-
__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'
6-
__license__ = 'MIT'
7-
__version__ = 'dev'
8-
4+
import warnings
95

106
from .connectionpool import (
117
HTTPConnectionPool,
@@ -32,8 +28,30 @@ class NullHandler(logging.Handler):
3228
def emit(self, record):
3329
pass
3430

31+
__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'
32+
__license__ = 'MIT'
33+
__version__ = 'dev'
34+
35+
__all__ = (
36+
'HTTPConnectionPool',
37+
'HTTPSConnectionPool',
38+
'PoolManager',
39+
'ProxyManager',
40+
'HTTPResponse',
41+
'Retry',
42+
'Timeout',
43+
'add_stderr_logger',
44+
'connection_from_url',
45+
'disable_warnings',
46+
'encode_multipart_formdata',
47+
'get_host',
48+
'make_headers',
49+
'proxy_from_url',
50+
)
51+
3552
logging.getLogger(__name__).addHandler(NullHandler())
3653

54+
3755
def add_stderr_logger(level=logging.DEBUG):
3856
"""
3957
Helper for quickly adding a StreamHandler to the logger. Useful for
@@ -55,7 +73,6 @@ def add_stderr_logger(level=logging.DEBUG):
5573
del NullHandler
5674

5775

58-
import warnings
5976
# SecurityWarning's always go off by default.
6077
warnings.simplefilter('always', exceptions.SecurityWarning, append=True)
6178
# SubjectAltNameWarning's should go off once per host
@@ -64,6 +81,7 @@ def add_stderr_logger(level=logging.DEBUG):
6481
warnings.simplefilter('default', exceptions.InsecurePlatformWarning,
6582
append=True)
6683

84+
6785
def disable_warnings(category=exceptions.HTTPWarning):
6886
"""
6987
Helper for quickly disabling all urllib3 warnings.

urllib3/_collections.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ def __eq__(self, other):
167167
def __ne__(self, other):
168168
return not self.__eq__(other)
169169

170-
if not PY3: # Python 2
170+
if not PY3: # Python 2
171171
iterkeys = MutableMapping.iterkeys
172172
itervalues = MutableMapping.itervalues
173173

@@ -304,7 +304,7 @@ def items(self):
304304
return list(self.iteritems())
305305

306306
@classmethod
307-
def from_httplib(cls, message): # Python 2
307+
def from_httplib(cls, message): # Python 2
308308
"""Read headers from a Python 2 httplib message object."""
309309
# python2.7 does not expose a proper API for exporting multiheaders
310310
# efficiently. This function re-reads raw lines from the message

urllib3/connection.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,13 @@
77
from .packages import six
88

99
try: # Python 3
10-
from http.client import HTTPConnection as _HTTPConnection, HTTPException
10+
from http.client import HTTPConnection as _HTTPConnection
11+
from http.client import HTTPException # noqa: unused in this module
1112
except ImportError:
12-
from httplib import HTTPConnection as _HTTPConnection, HTTPException
13-
14-
15-
class DummyConnection(object):
16-
"Used to detect a failed ConnectionCls import."
17-
pass
18-
13+
from httplib import HTTPConnection as _HTTPConnection
14+
from httplib import HTTPException # noqa: unused in this module
1915

2016
try: # Compiled with SSL?
21-
HTTPSConnection = DummyConnection
2217
import ssl
2318
BaseSSLError = ssl.SSLError
2419
except (ImportError, AttributeError): # Platform-specific: No SSL.
@@ -62,6 +57,11 @@ class ConnectionError(Exception):
6257
RECENT_DATE = datetime.date(2014, 1, 1)
6358

6459

60+
class DummyConnection(object):
61+
"""Used to detect a failed ConnectionCls import."""
62+
pass
63+
64+
6565
class HTTPConnection(_HTTPConnection, object):
6666
"""
6767
Based on httplib.HTTPConnection but provides an extra constructor
@@ -266,8 +266,8 @@ def connect(self):
266266
)
267267
match_hostname(cert, self.assert_hostname or hostname)
268268

269-
self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED
270-
or self.assert_fingerprint is not None)
269+
self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or
270+
self.assert_fingerprint is not None)
271271

272272

273273
if ssl:

urllib3/connectionpool.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
from queue import LifoQueue, Empty, Full
1111
except ImportError:
1212
from Queue import LifoQueue, Empty, Full
13-
import Queue as _ # Platform-specific: Windows
13+
# Queue is imported for side effects on MS Windows
14+
import Queue as _unused_module_Queue # noqa: unused
1415

1516

1617
from .exceptions import (
@@ -22,7 +23,6 @@
2223
LocationValueError,
2324
MaxRetryError,
2425
ProxyError,
25-
ConnectTimeoutError,
2626
ReadTimeoutError,
2727
SSLError,
2828
TimeoutError,
@@ -35,7 +35,7 @@
3535
port_by_scheme,
3636
DummyConnection,
3737
HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,
38-
HTTPException, BaseSSLError, ConnectionError
38+
HTTPException, BaseSSLError,
3939
)
4040
from .request import RequestMethods
4141
from .response import HTTPResponse
@@ -54,7 +54,7 @@
5454
_Default = object()
5555

5656

57-
## Pool objects
57+
# Pool objects
5858
class ConnectionPool(object):
5959
"""
6060
Base class for all connection pools, such as
@@ -644,22 +644,24 @@ def urlopen(self, method, url, body=None, headers=None, retries=None,
644644
return response
645645

646646
log.info("Redirecting %s -> %s" % (url, redirect_location))
647-
return self.urlopen(method, redirect_location, body, headers,
648-
retries=retries, redirect=redirect,
649-
assert_same_host=assert_same_host,
650-
timeout=timeout, pool_timeout=pool_timeout,
651-
release_conn=release_conn, **response_kw)
647+
return self.urlopen(
648+
method, redirect_location, body, headers,
649+
retries=retries, redirect=redirect,
650+
assert_same_host=assert_same_host,
651+
timeout=timeout, pool_timeout=pool_timeout,
652+
release_conn=release_conn, **response_kw)
652653

653654
# Check if we should retry the HTTP response.
654655
if retries.is_forced_retry(method, status_code=response.status):
655656
retries = retries.increment(method, url, response=response, _pool=self)
656657
retries.sleep()
657658
log.info("Forced retry: %s" % url)
658-
return self.urlopen(method, url, body, headers,
659-
retries=retries, redirect=redirect,
660-
assert_same_host=assert_same_host,
661-
timeout=timeout, pool_timeout=pool_timeout,
662-
release_conn=release_conn, **response_kw)
659+
return self.urlopen(
660+
method, url, body, headers,
661+
retries=retries, redirect=redirect,
662+
assert_same_host=assert_same_host,
663+
timeout=timeout, pool_timeout=pool_timeout,
664+
release_conn=release_conn, **response_kw)
663665

664666
return response
665667

urllib3/contrib/appengine.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ def _get_absolute_timeout(self, timeout):
176176
if timeout is Timeout.DEFAULT_TIMEOUT:
177177
return 5 # 5s is the default timeout for URLFetch.
178178
< F438 span class=pl-k>if isinstance(timeout, Timeout):
179-
if not timeout.read is timeout.connect:
179+
if timeout.read is not timeout.connect:
180180
warnings.warn(
181181
"URLFetch does not support granular timeout settings, "
182182
"reverting to total timeout.", AppEnginePlatformWarning)

urllib3/contrib/pyopenssl.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@
7979
_openssl_verify = {
8080
ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
8181
ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
82-
ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER
83-
+ OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
82+
ssl.CERT_REQUIRED:
83+
OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
8484
}
8585

8686
DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS
@@ -106,7 +106,7 @@ def extract_from_urllib3():
106106
util.HAS_SNI = orig_util_HAS_SNI
107107

108108

109-
### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.
109+
# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.
110110
class SubjectAltName(BaseSubjectAltName):
111111
'''ASN.1 implementation for subjectAltNames support'''
112112

@@ -117,7 +117,7 @@ class SubjectAltName(BaseSubjectAltName):
117117
constraint.ValueSizeConstraint(1, 1024)
118118

119119

120-
### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.
120+
# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.
121121
def get_subj_alt_name(peer_cert):
122122
# Search through extensions
123123
dns_name = []
@@ -208,7 +208,7 @@ def _send_until_done(self, data):
208208
def sendall(self, data):
209209
total_sent = 0
210210
while total_sent < len(data):
211-
sent = self._send_until_done(data[total_sent:total_sent+SSL_WRITE_BLOCKSIZE])
211+
sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
212212
total_sent += sent
213213

214214
def shutdown(self):

0 commit comments

Comments
 (0)
0