Skip to content

Commit 53c33f6

Browse files
authored
Configure pycodestyle and fix pep8 style errors (#179)
1 parent dc9fe5d commit 53c33f6

11 files changed

+65
-39
lines changed

flask_jwt_extended/config.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -179,14 +179,16 @@ def refresh_csrf_header_name(self):
179179
def access_expires(self):
180180
delta = current_app.config['JWT_ACCESS_TOKEN_EXPIRES']
181181
if not isinstance(delta, datetime.timedelta) and delta is not False:
182-
raise RuntimeError('JWT_ACCESS_TOKEN_EXPIRES must be a datetime.timedelta or False')
182+
err = 'JWT_ACCESS_TOKEN_EXPIRES must be a datetime.timedelta or False'
183+
raise RuntimeError(err)
183184
return delta
184185

185186
@property
186187
def refresh_expires(self):
187188
delta = current_app.config['JWT_REFRESH_TOKEN_EXPIRES']
188189
if not isinstance(delta, datetime.timedelta) and delta is not False:
189-
raise RuntimeError('JWT_REFRESH_TOKEN_EXPIRES must be a datetime.timedelta or False')
190+
err = 'JWT_REFRESH_TOKEN_EXPIRES must be a datetime.timedelta or False'
191+
raise RuntimeError(err)
190192
return delta
191193

192194
@property
@@ -204,7 +206,8 @@ def blacklist_checks(self):
204206
check_type = [check_type]
205207
for item in check_type:
206208
if item not in ('access', 'refresh'):
207-
raise RuntimeError('JWT_BLACKLIST_TOKEN_CHECKS must be "access" or "refresh"')
209+
err = 'JWT_BLACKLIST_TOKEN_CHECKS must be "access" or "refresh"'
210+
raise RuntimeError(err)
208211
return check_type
209212

210213
@property
@@ -275,4 +278,5 @@ def error_msg_key(self):
275278
def json_encoder(self):
276279
return current_app.json_encoder
277280

281+
278282
config = _Config()

flask_jwt_extended/default_callbacks.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,8 @@ def default_user_loader_error_callback(identity):
8484
function returns None, we return a general error message with a 401
8585
status code
8686
"""
87-
return jsonify({config.error_msg_key: "Error loading the user {}".format(identity)}), 401
87+
result = {config.error_msg_key: "Error loading the user {}".format(identity)}
88+
return jsonify(result), 401
8889

8990

9091
def default_claims_verification_callback(user_claims):
@@ -94,7 +95,7 @@ def default_claims_verification_callback(user_claims):
9495
return True
9596

9697

97-
def default_claims_verification_failed_callback():
98+
def default_verify_claims_failed_callback():
9899
"""
99100
By default, if the user claims verification failed, we return a generic
100101
error message with a 400 status code

flask_jwt_extended/jwt_manager.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@
1313
default_user_identity_callback, default_invalid_token_callback,
1414
default_unauthorized_callback, default_needs_fresh_token_callback,
1515
default_revoked_token_callback, default_user_loader_error_callback,
16-
default_claims_verification_callback,
17-
default_claims_verification_failed_callback
16+
default_claims_verification_callback, default_verify_claims_failed_callback
1817
)
1918
from flask_jwt_extended.tokens import (
2019
encode_refresh_token, encode_access_token
@@ -53,7 +52,7 @@ def __init__(self, app=None):
5352
self._user_loader_error_callback = default_user_loader_error_callback
5453
self._token_in_blacklist_callback = None
5554
self._claims_verification_callback = default_claims_verification_callback
56-
self._claims_verification_failed_callback = default_claims_verification_failed_callback
55+
self._verify_claims_failed_callback = default_verify_claims_failed_callback
5756

5857
# Register this extension with the flask app now (if it is provided)
5958
if app is not None:
@@ -83,7 +82,7 @@ def handle_auth_error(e):
8382
return self._unauthorized_callback(str(e))
8483

8584
@app.errorhandler(CSRFError)
86-
def handle_auth_error(e):
85+
def handle_csrf_error(e):
8786
return self._unauthorized_callback(str(e))
8887

8988
@app.errorhandler(ExpiredSignatureError)
@@ -124,7 +123,7 @@ def handler_user_load_error(e):
124123

125124
@app.errorhandler(UserClaimsVerificationError)
126125
def handle_failed_user_claims_verification(e):
127-
return self._claims_verification_failed_callback()
126+
return self._verify_claims_failed_callback()
128127

129128
@staticmethod
130129
def _set_default_configuration_options(app):
@@ -376,7 +375,7 @@ def claims_verification_failed_loader(self, callback):
376375
This callback must be a function that takes no arguments, and returns
377376
a Flask response.
378377
"""
379-
self._claims_verification_failed_callback = callback
378+
self._verify_claims_failed_callback = callback
380379
return callback
381380

382381
def _create_refresh_token(self, identity, expires_delta=None):
@@ -418,4 +417,3 @@ def _create_access_token(self, identity, fresh=False, expires_delta=None):
418417
json_encoder=config.json_encoder
419418
)
420419
return access_token
421-

flask_jwt_extended/utils.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,9 @@ def set_access_cookies(response, encoded_access_token, max_age=None):
205205
:param encoded_access_token: The encoded access token to set in the cookies.
206206
:param max_age: The max age of the cookie. If this is None, it will use the
207207
`JWT_SESSION_COOKIE` option (see :ref:`Configuration Options`).
208-
Otherwise, it will use this as the cookies `max-age` and the JWT_SESSION_COOKIE option will be ignored.
209-
Values should be the number of seconds (as an integer).
208+
Otherwise, it will use this as the cookies `max-age` and the
209+
JWT_SESSION_COOKIE option will be ignored. Values should be
210+
the number of seconds (as an integer).
210211
"""
211212
if not config.jwt_in_cookies:
212213
raise RuntimeWarning("set_access_cookies() called without "
@@ -245,8 +246,9 @@ def set_refresh_cookies(response, encoded_refresh_token, max_age=None):
245246
:param encoded_refresh_token: The encoded refresh token to set in the cookies.
246247
:param max_age: The max age of the cookie. If this is None, it will use the
247248
`JWT_SESSION_COOKIE` option (see :ref:`Configuration Options`).
248-
Otherwise, it will use this as the cookies `max-age` and the JWT_SESSION_COOKIE option will be ignored.
249-
Values should be the number of seconds (as an integer).
249+
Otherwise, it will use this as the cookies `max-age` and the
250+
JWT_SESSION_COOKIE option will be ignored. Values should be
251+
the number of seconds (as an integer).
250252
"""
251253
if not config.jwt_in_cookies:
252254
raise RuntimeWarning("set_refresh_cookies() called without "

flask_jwt_extended/view_decorators.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,10 @@ def _decode_jwt_from_headers():
184184
encoded_token = parts[0]
185185
else:
186186
if parts[0] != header_type or len(parts) != 2:
187-
msg = "Bad {} header. Expected value '{} <JWT>'".format(header_name, header_type)
187+
msg = "Bad {} header. Expected value '{} <JWT>'".format(
188+
header_name,
189+
header_type
190+
)
188191
raise InvalidHeaderError(msg)
189192
encoded_token = parts[1]
190193

@@ -274,7 +277,7 @@ def _decode_jwt_from_request(request_type):
274277
err_msg = "Missing JWT in {start_locs} or {end_locs} ({details})".format(
275278
start_locs=", ".join(token_locations[:-1]),
276279
end_locs=token_locations[-1],
277-
details= "; ".join(errors)
280+
details="; ".join(errors)
278281
)
279282
raise NoAuthorizationError(err_msg)
280283
else:

tests/test_cookies.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
unset_jwt_cookies, unset_access_cookies, unset_refresh_cookies, jwt_optional
88
)
99

10+
1011
def _get_cookie_from_response(response, cookie_name):
1112
cookie_headers = response.headers.getlist('Set-Cookie')
1213
for header in cookie_headers:
@@ -19,6 +20,7 @@ def _get_cookie_from_response(response, cookie_name):
1920
return cookie
2021
return None
2122

23+
2224
@pytest.fixture(scope='function')
2325
def app():
2426
app = Flask(__name__)
@@ -87,7 +89,7 @@ def optional_post_protected():
8789

8890

8991
@pytest.mark.parametrize("options", [
90-
('/refresh_token', 'refresh_token_cookie', '/refresh_protected', '/delete_refresh_tokens'),
92+
('/refresh_token', 'refresh_token_cookie', '/refresh_protected', '/delete_refresh_tokens'), # nopep8
9193
('/access_token', 'access_token_cookie', '/protected', '/delete_access_tokens')
9294
])
9395
def test_jwt_refresh_required_with_cookies(app, options):
@@ -200,7 +202,7 @@ def test_csrf_with_custom_header_names(app, options):
200202

201203

202204
@pytest.mark.parametrize("options", [
203-
('/refresh_token', 'csrf_refresh_token', '/refresh_protected', '/post_refresh_protected'),
205+
('/refresh_token', 'csrf_refresh_token', '/refresh_protected', '/post_refresh_protected'), # nopep8
204206
('/access_token', 'csrf_access_token', '/protected', '/post_protected')
205207
])
206208
def test_custom_csrf_methods(app, options):
@@ -412,6 +414,7 @@ def test_cookies_without_csrf(app):
412414
refresh_cookie = _get_cookie_from_response(response, 'refresh_token_cookie')
413415
assert refresh_cookie is not None
414416

417+
415418
def test_jwt_optional_with_csrf_enabled(app):
416419
test_client = app.test_client()
417420

@@ -423,7 +426,8 @@ def test_jwt_optional_with_csrf_enabled(app):
423426

424427
# User with a token should still get a CSRF error if csrf not present
425428
response = test_client.get('/access_token')
426-
csrf_token = _get_cookie_from_response(response, 'csrf_access_token')['csrf_access_token']
429+
csrf_cookie = _get_cookie_from_response(response, 'csrf_access_token')
430+
csrf_token = csrf_cookie['csrf_access_token']
427431
response = test_client.post('/optional_post_protected')
428432
assert response.status_code == 401
429433
assert response.get_json() == {'msg': 'Missing CSRF token in headers'}

tests/test_headers.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,9 @@ def test_custom_header_type(app):
4949
# Insure 'default' headers no longer work
5050
access_headers = {'Authorization': 'Bearer {}'.format(access_token)}
5151
response = test_client.get('/protected', headers=access_headers)
52+
expected_json = {'msg': "Bad Authorization header. Expected value 'JWT <JWT>'"}
5253
assert response.status_code == 422
53-
assert response.get_json() == {'msg': "Bad Authorization header. Expected value 'JWT <JWT>'"}
54+
assert response.get_json() == expected_json
5455

5556
# Insure new headers do work
5657
access_headers = {'Authorization': 'JWT {}'.format(access_token)}
@@ -69,7 +70,8 @@ def test_custom_header_type(app):
6970
app.config['JWT_HEADER_TYPE'] = ''
7071
access_headers = {'Authorization': 'Bearer {}'.format(access_token)}
7172
response = test_client.get('/protected', headers=access_headers)
72-
assert response.get_json() == {'msg': "Bad Authorization header. Expected value '<JWT>'"}
73+
expected_json = {'msg': "Bad Authorization header. Expected value '<JWT>'"}
74+
assert response.get_json() == expected_json
7375
assert response.status_code == 422
7476

7577

tests/test_json.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import pytest
22
from flask import Flask, jsonify
33

4-
from flask_jwt_extended import JWTManager, jwt_required, jwt_refresh_token_required, create_access_token, create_refresh_token
4+
from flask_jwt_extended import (
5+
JWTManager, jwt_required, jwt_refresh_token_required, create_access_token,
6+
create_refresh_token
7+
)
58
from tests.utils import get_jwt_manager
69

710

@@ -34,15 +37,15 @@ def test_content_type(app):
3437

3538
data = {'access_token': access_token}
3639
response = test_client.post('/protected', data=data)
37-
40+
expected_json = {'msg': 'Invalid content-type. Must be application/json.'}
3841
assert response.status_code == 401
39-
assert response.get_json() == {'msg': 'Invalid content-type. Must be application/json.'}
42+
assert response.get_json() == expected_json
4043

4144
data = {'refresh_token': refresh_token}
4245
response = test_client.post('/refresh', data=data)
43-
46+
expected_json = {'msg': 'Invalid content-type. Must be application/json.'}
4447
assert response.status_code == 401
45-
assert response.get_json() == {'msg': 'Invalid content-type. Must be application/json.'}
48+
assert response.get_json() == expected_json
4649

4750

4851
def test_custom_body_key(app):
@@ -60,7 +63,6 @@ def test_custom_body_key(app):
6063
assert response.status_code == 401
6164
assert response.get_json() == {'msg': 'Missing "Foo" key in json data.'}
6265

63-
6466
data = {'refresh_token': refresh_token}
6567
response = test_client.post('/refresh', json=data)
6668
assert response.status_code == 401
@@ -97,6 +99,7 @@ def custom_response(err_str):
9799
assert response.status_code == 201
98100
assert response.get_json() == {'foo': "bar"}
99101

102+
100103
def test_defaults(app):
101104
test_client = app.test_client()
102105

tests/test_multiple_token_locations.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,9 @@ def test_json_access(app):
7373
@pytest.mark.parametrize("options", [
7474
(['cookies', 'headers'], ('Missing JWT in cookies or headers (Missing cookie '
7575
'"access_token_cookie"; Missing Authorization Header)')),
76-
(['cookies', 'query_string'], ('Missing JWT in cookies or query_string (Missing cookie '
77-
'"access_token_cookie"; Missing "jwt" query paramater)')),
78-
(['headers', 'query_string'], ('Missing JWT in headers or query_string (Missing "jwt" '
79-
'query paramater; Missing Authorization Header)')),
80-
(['cookies', 'headers', 'query_string'], ('Missing JWT in cookies, headers or '
81-
'query_string (Missing cookie "access_token_cookie"; '
82-
'Missing "jwt" query paramater; Missing Authorization Header)'))
76+
(['json', 'query_string'], ('Missing JWT in json or query_string (Missing "jwt" '
77+
'query paramater; Invalid content-type. Must be '
78+
'application/json.)')),
8379
])
8480
def test_no_jwt_in_request(app, options):
8581
token_locations, expected_err = options

tests/test_options_method.py

+4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
)
55
import pytest
66

7+
78
@pytest.fixture(scope='function')
89
def app():
910
app = Flask(__name__)
@@ -27,16 +28,19 @@ def jwt_refresh_token_required_endpoint():
2728

2829
return app
2930

31+
3032
def test_access_jwt_required_enpoint(app):
3133
res = app.test_client().options('/jwt_required')
3234
assert res.status_code == 200
3335
assert res.data == b'ok'
3436

37+
3538
def test_access_jwt_refresh_token_required_enpoint(app):
3639
res = app.test_client().options('/jwt_refresh_token_required')
3740
assert res.status_code == 200
3841
assert res.data == b'ok'
3942

43+
4044
def test_access_fresh_jwt_required_enpoint(app):
4145
res = app.test_client().options('/fresh_jwt_required')
4246
assert res.status_code == 200

tests/test_view_decorators.py

+12-3
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,15 @@ def test_fresh_jwt_required(app):
7575
with app.test_request_context():
7676
access_token = create_access_token('username')
7777
fresh_access_token = create_access_token('username', fresh=True)
78-
fresh_timed_access_token = create_access_token('username', fresh=timedelta(minutes=5))
79-
stale_timed_access_token = create_access_token('username', fresh=timedelta(minutes=-1))
8078
refresh_token = create_refresh_token('username')
79+
fresh_timed_access_token = create_access_token(
80+
identity='username',
81+
fresh=timedelta(minutes=5)
82+
)
83+
stale_timed_access_token = create_access_token(
84+
identity='username',
85+
fresh=timedelta(minutes=-1)
86+
)
8187

8288
response = test_client.get(url, headers=make_headers(fresh_access_token))
8389
assert response.status_code == 200
@@ -146,8 +152,11 @@ def test_jwt_optional(app):
146152
with app.test_request_context():
147153
access_token = create_access_token('username')
148154
fresh_access_token = create_access_token('username', fresh=True)
149-
expired_token = create_access_token('username', expires_delta=timedelta(minutes=-1))
150155
refresh_token = create_refresh_token('username')
156+
expired_token = create_access_token(
157+
identity='username',
158+
expires_delta=timedelta(minutes=-1)
159+
)
151160

152161
response = test_client.get(url, headers=make_headers(fresh_access_token))
153162
assert response.status_code == 200

0 commit comments

Comments
 (0)