Skip to content

Commit 56caa8a

Browse files
authored
Merge pull request #270 from closeio/topic/use_flake8
Fix flake8 errors and add flake8 to TravisCI
2 parents f8c3bc8 + 60e454f commit 56caa8a

File tree

16 files changed

+104
-77
lines changed

16 files changed

+104
-77
lines changed

.travis.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,13 @@ install:
2828
- travis_retry pip install --upgrade pip
2929
- travis_retry pip install --upgrade nose
3030
- travis_retry pip install --upgrade setuptools
31+
- travis_retry pip install flake8
3132
- travis_retry pip install tox>=1.9
3233
- travis_retry tox -e $(echo py$TRAVIS_PYTHON_VERSION-me$MONGOENGINE | tr -d . | sed -e 's/pypypy/pypy/') -- -e test
3334

35+
before_script:
36+
- if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then tox -e flake8; fi
37+
3438
script:
3539
- tox -e $(echo py$TRAVIS_PYTHON_VERSION-me$MONGOENGINE | tr -d . | sed -e 's/pypypy/pypy/') -- --with-coverage
3640

flask_mongoengine/__init__.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
11
# -*- coding: utf-8 -*-
22
from __future__ import absolute_import
3-
import mongoengine, inspect
3+
import inspect
4+
import mongoengine
45

56
from flask import abort, current_app
67
from mongoengine.base.fields import BaseField
78
from mongoengine.queryset import (MultipleObjectsReturned,
8-
DoesNotExist, QuerySet)
9+
DoesNotExist, QuerySet)
910

1011
from mongoengine.base import ValidationError
11-
from pymongo import uri_parser
1212
from .sessions import *
1313
from .pagination import *
1414
from .metadata import *
1515
from .json import override_json_encoder
1616
from .wtf import WtfBaseField
1717
from .connection import *
18-
import flask_mongoengine
1918

2019
def redirect_connection_calls(cls):
2120
"""
@@ -120,7 +119,7 @@ def init_app(self, app, config=None):
120119
# Make documents JSON serializable
121120
override_json_encoder(app)
122121

123-
if not 'mongoengine' in app.extensions:
122+
if 'mongoengine' not in app.extensions:
124123
app.extensions['mongoengine'] = {}
125124

126125
if self in app.extensions['mongoengine']:

flask_mongoengine/connection.py

Lines changed: 37 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
1-
import atexit, os.path, time, mongoengine, sys
2-
import shutil, subprocess, tempfile
1+
import atexit
2+
import os.path
3+
import mongoengine
4+
import shutil
5+
import subprocess
6+
import sys
7+
import tempfile
8+
import time
9+
310
from flask import current_app
4-
from pymongo import MongoClient, ReadPreference, errors, uri_parser
11+
from pymongo import MongoClient, ReadPreference, errors
512
from subprocess import Popen, PIPE
613
from pymongo.errors import InvalidURI
714
from mongoengine import connection
@@ -24,11 +31,14 @@
2431
class InvalidSettingsError(Exception):
2532
pass
2633

34+
class ConnectionError(Exception):
35+
pass
36+
2737
def disconnect(alias=DEFAULT_CONNECTION_NAME, preserved=False):
2838
global _connections, _process, _tmpdir
2939

3040
if alias in _connections:
31-
conn = get_connection(alias=alias);
41+
conn = get_connection(alias=alias)
3242
client = conn.client
3343
if client:
3444
client.close()
@@ -46,8 +56,7 @@ def disconnect(alias=DEFAULT_CONNECTION_NAME, preserved=False):
4656
if os.path.exists(_tmpdir):
4757
shutil.rmtree(_tmpdir, ignore_errors=True)
4858
if os.path.exists(sock_file):
49-
os.remove("{0}/{1}".\
50-
format(tempfile.gettempdir(), sock_file))
59+
os.remove("{0}/{1}".format(tempfile.gettempdir(), sock_file))
5160

5261
def _validate_settings(is_test, temp_db, preserved, conn_host):
5362
"""
@@ -56,21 +65,20 @@ def _validate_settings(is_test, temp_db, preserved, conn_host):
5665
connection.
5766
5867
"""
59-
if (not isinstance(is_test, bool)
60-
or not isinstance(temp_db, bool)
61-
or not isinstance(preserved, bool)):
62-
msg = '`TESTING`, `TEMP_DB`, and `PRESERVE_TEMP_DB`'\
63-
' must be boolean values'
68+
if (not isinstance(is_test, bool) or not isinstance(temp_db, bool) or
69+
not isinstance(preserved, bool)):
70+
msg = ('`TESTING`, `TEMP_DB`, and `PRESERVE_TEMP_DB`'
71+
' must be boolean values')
6472
raise InvalidSettingsError(msg)
6573

6674
elif not is_test and conn_host.startswith('mongomock://'):
67-
msg = "`MongoMock` connection is only required for `unittest`."\
68-
"To enable this set `TESTING` to true`."
75+
msg = ("`MongoMock` connection is only required for `unittest`."
76+
"To enable this set `TESTING` to true`.")
6977
raise InvalidURI(msg)
7078

7179
elif not is_test and temp_db or preserved:
72-
msg = '`TESTING` and/or `TEMP_DB` can be used '\
73-
'only when `TESTING` is set to true.'
80+
msg = ('`TESTING` and/or `TEMP_DB` can be used '
81+
'only when `TESTING` is set to true.')
7482
raise InvalidSettingsError(msg)
7583

7684
def __get_app_config(key):
@@ -117,7 +125,7 @@ def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
117125
return _register_test_connection(port, db_alias, preserved)
118126

119127
elif (conn_host.startswith('mongomock://') and
120-
mongoengine.VERSION < (0, 10, 6)):
128+
mongoengine.VERSION < (0, 10, 6)):
121129
# Use MongoClient from mongomock
122130
try:
123131
import mongomock
@@ -212,16 +220,16 @@ def _register_test_connection(port, db_alias, preserved):
212220

213221
if _conn is None:
214222
_process = subprocess.Popen([
215-
'mongod', '--bind_ip', 'localhost',
216-
'--port', str(port),
217-
'--dbpath', _tmpdir,
218-
'--nojournal', '--nohttpinterface',
219-
'--noauth', '--smallfiles',
220-
'--syncdelay', '0',
221-
'--maxConns', '10',
222-
'--nssize', '1', ],
223-
stdout=open(os.devnull, 'wb'),
224-
stderr=subprocess.STDOUT)
223+
'mongod', '--bind_ip', 'localhost',
224+
'--port', str(port),
225+
'--dbpath', _tmpdir,
226+
'--nojournal', '--nohttpinterface',
227+
'--noauth', '--smallfiles',
228+
'--syncdelay', '0',
229+
'--maxConns', '10',
230+
'--nssize', '1', ],
231+
stdout=open(os.devnull, 'wb'),
232+
stderr=subprocess.STDOUT)
225233
atexit.register(disconnect, preserved=preserved)
226234

227235
# wait for the instance db to be ready
@@ -232,7 +240,8 @@ def _register_test_connection(port, db_alias, preserved):
232240
_conn = MongoClient('localhost', port)
233241
except errors.ConnectionFailure:
234242
continue
235-
else: break
243+
else:
244+
break
236245
else:
237246
msg = 'Cannot connect to the mongodb test instance'
238247
raise mongoengine.ConnectionError(msg)
@@ -358,7 +367,7 @@ def create_connection(config, app):
358367
_app_instance = app if app else config
359368

360369
if config is None or not isinstance(config, dict):
361-
raise Exception("Invalid application configuration");
370+
raise InvalidSettingsError("Invalid application configuration")
362371

363372
conn_settings = fetch_connection_settings(config, False)
364373

flask_mongoengine/operation_tracker.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def _insert(collection_self, doc_or_docs, manipulate=True,
6060
)
6161
total_time = (time.time() - start_time) * 1000
6262

63-
__traceback_hide__ = True
63+
__traceback_hide__ = True # noqa
6464
stack_trace, internal = _tidy_stacktrace()
6565
inserts.append({
6666
'document': doc_or_docs,
@@ -86,7 +86,7 @@ def _update(collection_self, spec, document, upsert=False,
8686
)
8787
total_time = (time.time() - start_time) * 1000
8888

89-
__traceback_hide__ = True
89+
__traceback_hide__ = True # noqa
9090
stack_trace, internal = _tidy_stacktrace()
9191
updates.append({
9292
'document': document,
@@ -111,7 +111,7 @@ def _remove(collection_self, spec_or_id, safe=None, **kwargs):
111111
)
112112
total_time = (time.time() - start_time) * 1000
113113

114-
__traceback_hide__ = True
114+
__traceback_hide__ = True # noqa
115115
stack_trace, internal = _tidy_stacktrace()
116116
removes.append({
117117
'spec_or_id': spec_or_id,
@@ -167,7 +167,7 @@ def privar(name):
167167
if maxScan:
168168
query_son["$maxScan"] = maxScan
169169

170-
__traceback_hide__ = True
170+
__traceback_hide__ = True # noqa
171171
stack_trace, internal = _tidy_stacktrace()
172172
query_data = {
173173
'time': total_time,

flask_mongoengine/panels.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@ def nav_title(self):
3939
def nav_subtitle(self):
4040
attrs = ['queries', 'inserts', 'updates', 'removes']
4141
ops = sum(sum((1 for o in getattr(operation_tracker, a)
42-
if not o['internal']))
43-
for a in attrs)
42+
if not o['internal']))
43+
for a in attrs)
4444
total_time = sum(sum(o['time'] for o in getattr(operation_tracker, a))
4545
for a in attrs)
4646
return '{0} operations in {1:.2f}ms'.format(ops, total_time)

flask_mongoengine/wtf/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
from flask_mongoengine.wtf.orm import model_fields, model_form
2-
from flask_mongoengine.wtf.base import WtfBaseField
1+
from flask_mongoengine.wtf.orm import model_fields, model_form # noqa
2+
from flask_mongoengine.wtf.base import WtfBaseField # noqa

flask_mongoengine/wtf/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,4 @@ def save(self, commit=True, **kwargs):
1818

1919
if commit:
2020
self.instance.save(**kwargs)
21-
return self.instance
21+
return self.instance

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ Flask>=0.8
22
Flask-DebugToolbar>=0.8
33
Flask-WTF>=0.8.3
44
mongoengine>=0.8.0
5+
flake8

setup.cfg

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,8 @@ cover-erase = 1
66
cover-branches = 1
77
cover-package = flask_mongoengine
88
tests = tests
9+
10+
[flake8]
11+
ignore=E2,E129,E302,E5,W391,F403,F405,E501,E731,F999
12+
exclude=build,dist,docs,examples,venv,.tox,.eggs
13+
max-complexity=35

setup.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
import os, imp
1+
import imp
2+
import os
3+
24
from setuptools import setup
35

46
def load_module(module_name, script_file):
@@ -22,22 +24,19 @@ def load_module(module_name, script_file):
2224

2325
# Load documentation
2426
doc_path = os.path.join(os.path.dirname(__file__), "docs", "index.rst")
25-
26-
# Load guide
27-
doc_path = os.path.join(os.path.dirname(__file__), "docs", "index.rst")
28-
DESCRIPTION = 'Flask-MongoEngine is a Flask extension ' + \
29-
'that provides integration with MongoEngine and WTF model forms.'
27+
DESCRIPTION = ('Flask-MongoEngine is a Flask extension '
28+
'that provides integration with MongoEngine and WTF model forms.')
3029

3130
LONG_DESCRIPTION = None
3231
try:
3332
LONG_DESCRIPTION = open(doc_path).read()
3433

3534
# Stops exit traceback on tests
36-
import multiprocessing
35+
import multiprocessing # noqa
3736
except:
3837
pass
3938

40-
test_requirements = ['nose', 'rednose', 'coverage', 'mongomock']
39+
test_requirements = ['coverage', 'flake8', 'mongomock', 'nose', 'rednose']
4140

4241
setup(
4342
name='flask-mongoengine',

0 commit comments

Comments
 (0)