Skip to content

Commit ec05109

Browse files
committed
ignore less flake8 errors + add flake8-import-order + minor style tweaks
1 parent 56caa8a commit ec05109

25 files changed

+127
-61
lines changed

flask_mongoengine/__init__.py

+17-11
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
# -*- coding: utf-8 -*-
22
from __future__ import absolute_import
33
import inspect
4-
import mongoengine
54

65
from flask import abort, current_app
6+
import mongoengine
7+
from mongoengine.base import ValidationError
78
from mongoengine.base.fields import BaseField
8-
from mongoengine.queryset import (MultipleObjectsReturned,
9-
DoesNotExist, QuerySet)
9+
from mongoengine.queryset import (DoesNotExist, MultipleObjectsReturned,
10+
QuerySet)
1011

11-
from mongoengine.base import ValidationError
12-
from .sessions import *
13-
from .pagination import *
14-
from .metadata import *
12+
from .connection import *
1513
from .json import override_json_encoder
14+
from .metadata import *
15+
from .pagination import *
16+
from .sessions import *
1617
from .wtf import WtfBaseField
17-
from .connection import *
18+
1819

1920
def redirect_connection_calls(cls):
2021
"""
@@ -25,9 +26,9 @@ def redirect_connection_calls(cls):
2526
# Proxy all 'mongoengine.connection'
2627
# specific attr via 'flask_mongoengine'
2728
connection_methods = {
28-
'get_db' : get_db,
29-
'DEFAULT_CONNECTION_NAME' : DEFAULT_CONNECTION_NAME,
30-
'get_connection' : get_connection
29+
'get_db': get_db,
30+
'DEFAULT_CONNECTION_NAME': DEFAULT_CONNECTION_NAME,
31+
'get_connection': get_connection
3132
}
3233

3334
cls_module = inspect.getmodule(cls)
@@ -37,6 +38,7 @@ def redirect_connection_calls(cls):
3738
if connection_methods.get(n, None):
3839
setattr(cls_module, n, connection_methods.get(n, None))
3940

41+
4042
def _patch_base_field(obj, name):
4143
"""
4244
If the object submitted has a class whose base class is
@@ -75,6 +77,7 @@ def _patch_base_field(obj, name):
7577
setattr(obj, name, cls)
7678
redirect_connection_calls(cls)
7779

80+
7881
def _include_mongoengine(obj):
7982
for module in mongoengine, mongoengine.fields:
8083
for key in module.__all__:
@@ -84,6 +87,7 @@ def _include_mongoengine(obj):
8487
# patch BaseField if available
8588
_patch_base_field(obj, key)
8689

90+
8791
def current_mongoengine_instance():
8892
"""
8993
Obtain instance of MongoEngine in the
@@ -98,6 +102,7 @@ def current_mongoengine_instance():
98102
return k
99103
return None
100104

105+
101106
class MongoEngine(object):
102107

103108
def __init__(self, app=None, config=None):
@@ -188,6 +193,7 @@ def paginate_field(self, field_name, doc_id, page, per_page,
188193
return ListFieldPagination(self, doc_id, field_name, page, per_page,
189194
total=total)
190195

196+
191197
class Document(mongoengine.Document):
192198
"""Abstract document with extra helpers in the queryset class"""
193199

flask_mongoengine/connection.py

+17-4
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
import atexit
22
import os.path
3-
import mongoengine
43
import shutil
54
import subprocess
65
import sys
76
import tempfile
87
import time
98

109
from flask import current_app
10+
import mongoengine
11+
from mongoengine import connection
1112
from pymongo import MongoClient, ReadPreference, errors
12-
from subprocess import Popen, PIPE
1313
from pymongo.errors import InvalidURI
14-
from mongoengine import connection
1514

1615
__all__ = (
1716
'create_connection', 'disconnect', 'get_connection',
@@ -28,12 +27,15 @@
2827
_process = None
2928
_app_instance = current_app
3029

30+
3131
class InvalidSettingsError(Exception):
3232
pass
3333

34+
3435
class ConnectionError(Exception):
3536
pass
3637

38+
3739
def disconnect(alias=DEFAULT_CONNECTION_NAME, preserved=False):
3840
global _connections, _process, _tmpdir
3941

@@ -58,6 +60,7 @@ def disconnect(alias=DEFAULT_CONNECTION_NAME, preserved=False):
5860
if os.path.exists(sock_file):
5961
os.remove("{0}/{1}".format(tempfile.gettempdir(), sock_file))
6062

63+
6164
def _validate_settings(is_test, temp_db, preserved, conn_host):
6265
"""
6366
Validate unitest settings to ensure
@@ -81,11 +84,13 @@ def _validate_settings(is_test, temp_db, preserved, conn_host):
8184
'only when `TESTING` is set to true.')
8285
raise InvalidSettingsError(msg)
8386

87+
8488
def __get_app_config(key):
8589
return (_app_instance.get(key, False)
8690
if isinstance(_app_instance, dict)
8791
else _app_instance.config.get(key, False))
8892

93+
8994
def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
9095
global _connections
9196
set_global_attributes()
@@ -175,25 +180,30 @@ def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
175180

176181
return mongoengine.connection.get_db(alias)
177182

183+
178184
def _sys_exec(cmd, shell=True, env=None):
179185
if env is None:
180186
env = os.environ
181187

182-
a = Popen(cmd, shell=shell, stdout=PIPE, stderr=PIPE, env=env)
188+
a = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE,
189+
stderr=subprocess.PIPE, env=env)
183190
a.wait() # Wait for process to terminate
184191
if a.returncode: # Not 0 => Error has occured
185192
raise Exception(a.communicate()[1])
186193
return a.communicate()[0]
187194

195+
188196
def set_global_attributes():
189197
setattr(connection, '_connection_settings', _connection_settings)
190198
setattr(connection, '_connections', _connections)
191199
setattr(connection, 'disconnect', disconnect)
192200

201+
193202
def get_db(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
194203
set_global_attributes()
195204
return connection.get_db(alias, reconnect)
196205

206+
197207
def _register_test_connection(port, db_alias, preserved):
198208
global _process, _tmpdir
199209

@@ -248,6 +258,7 @@ def _register_test_connection(port, db_alias, preserved):
248258
_connections[db_alias] = _conn
249259
return _conn
250260

261+
251262
def _resolve_settings(conn_setting, removePass=True):
252263

253264
if conn_setting and isinstance(conn_setting, dict):
@@ -295,6 +306,7 @@ def _resolve_settings(conn_setting, removePass=True):
295306
return resolved
296307
return conn_setting
297308

309+
298310
def fetch_connection_settings(config, removePass=True):
299311
"""
300312
Fetch DB connection settings from FlaskMongoEngine
@@ -328,6 +340,7 @@ def fetch_connection_settings(config, removePass=True):
328340
# Connection settings provided in standard format.
329341
return _resolve_settings(config, removePass)
330342

343+
331344
def create_connection(config, app):
332345
"""
333346
Connection is created based on application configuration

flask_mongoengine/json.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
from flask.json import JSONEncoder
21
from bson import json_util
2+
from flask.json import JSONEncoder
33
from mongoengine.base import BaseDocument
44
from mongoengine.queryset import QuerySet
55

6+
67
def _make_encoder(superclass):
78
class MongoEngineJSONEncoder(superclass):
89
'''
@@ -18,6 +19,7 @@ def default(self, obj):
1819
return MongoEngineJSONEncoder
1920
MongoEngineJSONEncoder = _make_encoder(JSONEncoder)
2021

22+
2123
def override_json_encoder(app):
2224
'''
2325
A function to dynamically create a new MongoEngineJSONEncoder class

flask_mongoengine/metadata.py

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
unicode = unicode
99
basestring = basestring
1010

11+
1112
def get_version():
1213
if isinstance(VERSION[-1], basestring):
1314
return '.'.join(map(str, VERSION[:-1])) + VERSION[-1]

flask_mongoengine/operation_tracker.py

+15-5
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1+
import copy
12
import functools
2-
import time
33
import inspect
4-
import copy
5-
import sys
64
import os
5+
import sys
6+
import time
77
try:
88
import SocketServer
99
except ImportError:
1010
import socketserver as SocketServer
1111

12+
import bson
1213
import pymongo.collection
1314
import pymongo.cursor
1415
import pymongo.helpers
1516

16-
from bson import SON
1717

1818
__all__ = ['queries', 'inserts', 'updates', 'removes', 'install_tracker',
1919
'uninstall_tracker', 'reset', 'response_sizes']
@@ -35,6 +35,7 @@
3535
if sys.version_info >= (3, 0):
3636
unicode = str
3737

38+
3839
# Wrap helpers._unpack_response for getting response size
3940
@functools.wraps(_original_methods['_unpack_response'])
4041
def _unpack_response(response, *args, **kwargs):
@@ -47,6 +48,7 @@ def _unpack_response(response, *args, **kwargs):
4748
response_sizes.append(sys.getsizeof(response, len(response)) / 1024.0)
4849
return result
4950

51+
5052
# Wrap Cursor.insert for getting queries
5153
@functools.wraps(_original_methods['insert'])
5254
def _insert(collection_self, doc_or_docs, manipulate=True,
@@ -71,6 +73,7 @@ def _insert(collection_self, doc_or_docs, manipulate=True,
7173
})
7274
return result
7375

76+
7477
# Wrap Cursor.update for getting queries
7578
@functools.wraps(_original_methods['update'])
7679
def _update(collection_self, spec, document, upsert=False,
@@ -100,6 +103,7 @@ def _update(collection_self, spec, document, upsert=False,
100103
})
101104
return result
102105

106+
103107
# Wrap Cursor.remove for getting queries
104108
@functools.wraps(_original_methods['remove'])
105109
def _remove(collection_self, spec_or_id, safe=None, **kwargs):
@@ -122,6 +126,7 @@ def _remove(collection_self, spec_or_id, safe=None, **kwargs):
122126
})
123127
return result
124128

129+
125130
# Wrap Cursor._refresh for getting queries
126131
@functools.wraps(_original_methods['refresh'])
127132
def _cursor_refresh(cursor_self):
@@ -142,7 +147,7 @@ def privar(name):
142147
total_time = (time.time() - start_time) * 1000
143148

144149
query_son = privar('query_spec')()
145-
if not isinstance(query_son, SON):
150+
if not isinstance(query_son, bson.SON):
146151

147152
if "$query" not in query_son:
148153
query_son = {"$query": query_son}
@@ -203,6 +208,7 @@ def privar(name):
203208

204209
return result
205210

211+
206212
def install_tracker():
207213
if pymongo.collection.Collection.insert != _insert:
208214
pymongo.collection.Collection.insert = _insert
@@ -215,6 +221,7 @@ def install_tracker():
215221
if pymongo.helpers._unpack_response != _unpack_response:
216222
pymongo.helpers._unpack_response = _unpack_response
217223

224+
218225
def uninstall_tracker():
219226
if pymongo.collection.Collection.insert == _insert:
220227
pymongo.collection.Collection.insert = _original_methods['insert']
@@ -227,6 +234,7 @@ def uninstall_tracker():
227234
if pymongo.helpers._unpack_response == _unpack_response:
228235
pymongo.helpers._unpack_response = _original_methods['_unpack_response']
229236

237+
230238
def reset():
231239
global queries, inserts, updates, removes, response_sizes
232240
queries = []
@@ -235,6 +243,7 @@ def reset():
235243
removes = []
236244
response_sizes = []
237245

246+
238247
def _get_ordering(son):
239248
"""Helper function to extract formatted ordering from dict.
240249
"""
@@ -244,6 +253,7 @@ def fmt(field, direction):
244253
if '$orderby' in son:
245254
return ', '.join(fmt(f, d) for f, d in son['$orderby'].items())
246255

256+
247257
def _tidy_stacktrace():
248258
"""
249259
Tidy the stack_trace

flask_mongoengine/pagination.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
__all__ = ("Pagination", "ListFieldPagination")
88

9+
910
class Pagination(object):
1011

1112
def __init__(self, iterable, page, per_page):
@@ -102,18 +103,22 @@ def iter_pages(self, left_edge=2, left_current=2,
102103
{% endmacro %}
103104
"""
104105
last = 0
105-
for num in range(1, self.pages + 1) if sys.version_info >= (3, 0) else xrange(1, self.pages + 1):
106-
if (num <= left_edge or
106+
range_func = range if sys.version_info >= (3, 0) else xrange
107+
for num in range_func(1, self.pages + 1):
108+
if (
109+
num <= left_edge or
110+
num > self.pages - right_edge or
107111
(num >= self.page - left_current and
108-
num <= self.page + right_current) or
109-
num > self.pages - right_edge):
112+
num <= self.page + right_current)
113+
):
110114
if last + 1 != num:
111115
yield None
112116
yield num
113117
last = num
114118
if last != self.pages:
115119
yield None
116120

121+
117122
class ListFieldPagination(Pagination):
118123

119124
def __init__(self, queryset, doc_id, field_name, page, per_page,

flask_mongoengine/panels.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
from flask import current_app
2-
32
from flask_debugtoolbar.panels import DebugPanel
4-
from jinja2 import PackageLoader, ChoiceLoader
3+
from jinja2 import ChoiceLoader, PackageLoader
4+
55
from flask_mongoengine import operation_tracker
66

7-
_ = lambda x: x
87

98
package_loader = PackageLoader('flask_mongoengine', 'templates')
109

10+
1111
def _maybe_patch_jinja_loader(jinja_env):
1212
"""Patch the jinja_env loader to include flaskext.mongoengine
1313
templates folder if necessary.
@@ -17,6 +17,7 @@ def _maybe_patch_jinja_loader(jinja_env):
1717
elif package_loader not in jinja_env.loader.loaders:
1818
jinja_env.loader.loaders.append(package_loader)
1919

20+
2021
class MongoDebugPanel(DebugPanel):
2122
"""Panel that shows information about MongoDB operations (including stack)
2223

0 commit comments

Comments
 (0)