Skip to content

Commit 189d300

Browse files
committed
Linting
1 parent 4a46873 commit 189d300

File tree

8 files changed

+50
-48
lines changed

8 files changed

+50
-48
lines changed

annotator/auth.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ def __init__(self, key):
1313

1414

1515
class User(object):
16-
def __init__(self, id, consumer, is_admin):
17-
self.id = id
16+
def __init__(self, userid, consumer, is_admin):
17+
self.id = userid
1818
self.consumer = consumer
1919
self.is_admin = is_admin
2020

@@ -108,7 +108,7 @@ def encode_token(token, secret):
108108

109109
def decode_token(token, secret='', ttl=DEFAULT_TTL, verify=True):
110110
try:
111-
if not type(token) is bytes:
111+
if not isinstance(token, bytes):
112112
if six.PY3:
113113
token = bytes(token, 'utf-8')
114114
else:

annotator/document.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def _get_all_by_uris(cls, uris):
5555
# index, so ignore this sort instruction if
5656
# 'updated' appears unmapped due to an empty
5757
# index.
58-
'ignore_unmapped': True,}}]}
58+
'ignore_unmapped': True}}]}
5959

6060
res = cls.es.conn.search(index=cls.es.index,
6161
doc_type=cls.__type__,

annotator/elasticsearch.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
from __future__ import absolute_import
22

3-
import csv
4-
import json
53
import logging
64
import datetime
75

@@ -10,26 +8,26 @@
108
import elasticsearch
119
from six import iteritems
1210
from six.moves.urllib.parse import urlparse
13-
from annotator.atoi import atoi
1411

1512
log = logging.getLogger(__name__)
1613

1714
RESULTS_MAX_SIZE = 200
1815
RESULTS_DEFAULT_SIZE = 20
1916

17+
2018
class ElasticSearch(object):
2119
"""
2220
Thin wrapper around an ElasticSearch connection to make connection handling
2321
more convenient.
2422
25-
Settings for the ES host and index name etcetera can still be changed in the
26-
corresponding attributes before the connection (self.conn) is used.
23+
Settings for the ES host and index name etcetera can still be changed in
24+
the corresponding attributes before the connection (self.conn) is used.
2725
"""
2826

2927
def __init__(self,
30-
host = 'http://127.0.0.1:9200',
31-
index = 'annotator',
32-
authorization_enabled = False):
28+
host='http://127.0.0.1:9200',
29+
index='annotator',
30+
authorization_enabled=False):
3331
self.host = host
3432
self.index = index
3533
self.authorization_enabled = authorization_enabled
@@ -41,7 +39,7 @@ def _connect(self):
4139
parsed = urlparse(host)
4240

4341
connargs = {
44-
'host': parsed.hostname,
42+
'host': parsed.hostname,
4543
}
4644

4745
username = parsed.username
@@ -89,7 +87,7 @@ class _Model(dict):
8987

9088
@classmethod
9189
def create_all(cls):
92-
log.info("Creating index '%s'." % cls.es.index)
90+
log.info("Creating index '%s'.", cls.es.index)
9391
conn = cls.es.conn
9492
try:
9593
conn.indices.create(cls.es.index)
@@ -100,7 +98,7 @@ def create_all(cls):
10098
or e.error.startswith('InvalidIndexNameException')):
10199
log.fatal("Failed to create an Elasticsearch index")
102100
raise
103-
log.warn("Index creation failed as index appears to already exist.")
101+
log.warn("Index creation failed: index appears to already exist.")
104102
mapping = cls.get_mapping()
105103
conn.indices.put_mapping(index=cls.es.index,
106104
doc_type=cls.__type__,
@@ -130,13 +128,13 @@ def drop_all(cls):
130128
# It would be lovely if this were called 'get', but the dict semantics
131129
# already define that method name.
132130
@classmethod
133-
def fetch(cls, id):
131+
def fetch(cls, docid):
134132
doc = cls.es.conn.get(index=cls.es.index,
135133
doc_type=cls.__type__,
136134
ignore=404,
137-
id=id)
135+
id=docid)
138136
if doc.get('found', True):
139-
return cls(doc['_source'], id=id)
137+
return cls(doc['_source'], id=docid)
140138

141139
@classmethod
142140
def _build_query(cls, query=None, offset=None, limit=None, sort=None, order=None):
@@ -189,7 +187,7 @@ def search_raw(cls, query=None, params=None, raw_result=False):
189187
def count(cls, **kwargs):
190188
"""Like search, but only count the number of matches."""
191189
kwargs.setdefault('params', {})
192-
kwargs['params'].update({'search_type':'count'})
190+
kwargs['params'].update({'search_type': 'count'})
193191
res = cls.search(raw_result=True, **kwargs)
194192
return res['hits']['total']
195193

annotator/store.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"""
1515
from __future__ import absolute_import
1616

17+
import csv
1718
import json
1819

1920
from elasticsearch.exceptions import TransportError
@@ -25,6 +26,7 @@
2526

2627
from annotator.atoi import atoi
2728
from annotator.annotation import Annotation
29+
from annotator.elasticsearch import RESULTS_MAX_SIZE
2830

2931
store = Blueprint('store', __name__)
3032

@@ -90,7 +92,7 @@ def root():
9092
'read': {
9193
'method': 'GET',
9294
'url': url_for('.read_annotation',
93-
id=':id',
95+
docid=':id',
9496
_external=True),
9597
'desc': "Get an existing annotation"
9698
},
@@ -99,7 +101,7 @@ def root():
99101
'url':
100102
url_for(
101103
'.update_annotation',
102-
id=':id',
104+
docid=':id',
103105
_external=True),
104106
'query': {
105107
'refresh': {
@@ -113,7 +115,7 @@ def root():
113115
'delete': {
114116
'method': 'DELETE',
115117
'url': url_for('.delete_annotation',
116-
id=':id',
118+
docid=':id',
117119
_external=True),
118120
'desc': "Delete an annotation"
119121
}
@@ -173,7 +175,7 @@ def create_annotation():
173175
refresh = request.args.get('refresh') != 'false'
174176
annotation.save(refresh=refresh)
175177

176-
location = url_for('.read_annotation', id=annotation['id'])
178+
location = url_for('.read_annotation', docid=annotation['id'])
177179

178180
return jsonify(annotation), 201, {'Location': location}
179181
else:
@@ -182,9 +184,9 @@ def create_annotation():
182184

183185

184186
# READ
185-
@store.route('/annotations/<id>')
186-
def read_annotation(id):
187-
annotation = g.annotation_class.fetch(id)
187+
@store.route('/annotations/<docid>')
188+
def read_annotation(docid):
189+
annotation = g.annotation_class.fetch(docid)
188190
if not annotation:
189191
return jsonify('Annotation not found!', status=404)
190192

@@ -196,9 +198,9 @@ def read_annotation(id):
196198

197199

198200
# UPDATE
199-
@store.route('/annotations/<id>', methods=['POST', 'PUT'])
200-
def update_annotation(id):
201-
annotation = g.annotation_class.fetch(id)
201+
@store.route('/annotations/<docid>', methods=['POST', 'PUT'])
202+
def update_annotation(docid):
203+
annotation = g.annotation_class.fetch(docid)
202204
if not annotation:
203205
return jsonify('Annotation not found! No update performed.',
204206
status=404)
@@ -209,7 +211,7 @@ def update_annotation(id):
209211

210212
if request.json is not None:
211213
updated = _filter_input(request.json, UPDATE_FILTER_FIELDS)
212-
updated['id'] = id # use id from URL, regardless of what arrives in
214+
updated['id'] = docid # use id from URL, regardless of what arrives in
213215
# JSON payload
214216

215217
changing_permissions = (
@@ -238,9 +240,9 @@ def update_annotation(id):
238240

239241

240242
# DELETE
241-
@store.route('/annotations/<id>', methods=['DELETE'])
242-
def delete_annotation(id):
243-
annotation = g.annotation_class.fetch(id)
243+
@store.route('/annotations/<docid>', methods=['DELETE'])
244+
def delete_annotation(docid):
245+
annotation = g.annotation_class.fetch(docid)
244246

245247
if not annotation:
246248
return jsonify('Annotation not found. No delete performed.',

reindex.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python
2-
import sys
32
import argparse
43

54
from elasticsearch import Elasticsearch
@@ -12,7 +11,8 @@
1211
WARNING: Documents that are created while reindexing may be lost!
1312
"""
1413

15-
def main(argv):
14+
15+
def main():
1616
argparser = argparse.ArgumentParser(description=description)
1717
argparser.add_argument('old_index', help="Index to read from")
1818
argparser.add_argument('new_index', help="Index to write to")
@@ -39,4 +39,4 @@ def main(argv):
3939
reindexer.alias(new_index, alias)
4040

4141
if __name__ == '__main__':
42-
main(sys.argv)
42+
main()

run.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,20 +34,22 @@
3434

3535
here = os.path.dirname(__file__)
3636

37-
def main():
37+
38+
def main(argv):
3839
app = Flask(__name__)
3940

4041
cfg_file = 'annotator.cfg'
41-
if len(sys.argv) == 2:
42-
cfg_file = sys.argv[1]
42+
if len(argv) == 2:
43+
cfg_file = argv[1]
4344

4445
cfg_path = os.path.join(here, cfg_file)
4546

4647
try:
4748
app.config.from_pyfile(cfg_path)
4849
except IOError:
4950
print("Could not find config file %s" % cfg_path, file=sys.stderr)
50-
print("Perhaps you need to copy annotator.cfg.example to annotator.cfg", file=sys.stderr)
51+
print("Perhaps copy annotator.cfg.example to annotator.cfg",
52+
file=sys.stderr)
5153
sys.exit(1)
5254

5355
if app.config.get('ELASTICSEARCH_HOST') is not None:
@@ -69,10 +71,11 @@ def main():
6971
date = time.strftime('%Y-%m-%d')
7072
log.fatal("Elasticsearch index mapping is incorrect! Please "
7173
"reindex it. You can use reindex.py for this, e.g. "
72-
"python reindex.py --host {0} {1} {1}-{2}".format(
73-
es.host,
74-
es.index,
75-
date))
74+
"python reindex.py --host %s %s %s-%s",
75+
es.host,
76+
es.index,
77+
es.index,
78+
date)
7679
raise
7780

7881
@app.before_request
@@ -108,4 +111,4 @@ def before_request():
108111
app.run(host=host, port=port)
109112

110113
if __name__ == '__main__':
111-
main()
114+
main(sys.argv)

tests/helpers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ def __init__(self, key='mockconsumer'):
55
self.ttl = 86400
66

77
class MockUser(object):
8-
def __init__(self, id='alice', consumer=None):
9-
self.id = id
8+
def __init__(self, userid='alice', consumer=None):
9+
self.id = userid
1010
self.consumer = MockConsumer(consumer if consumer is not None else 'mockconsumer')
1111
self.is_admin = False
1212

tests/test_store.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,6 @@ def test_update_ignore_auth_in_payload(self):
264264
assert_equal(upd['user'], self.user.id, "annotation 'user' field should not be futzable by API")
265265
assert_equal(upd['consumer'], self.user.consumer.key, "annotation 'consumer' field should not be futzable by API")
266266

267-
268267
def test_delete(self):
269268
kwargs = dict(text=u"Bar", id='456')
270269
ann = self._create_annotation(**kwargs)

0 commit comments

Comments
 (0)