-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmad_responder.py
executable file
·2048 lines (1884 loc) · 67.5 KB
/
mad_responder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from datetime import datetime, timedelta
import json
import os
import platform
import re
import sys
from time import time
from urllib.parse import parse_qs
import elasticsearch
from flask import Flask, g, render_template, request, jsonify
from flask.json import JSONEncoder
from flask_cors import CORS
from flask_swagger import swagger
from jwt import decode
from kafka import KafkaProducer
from kafka.errors import KafkaError
import pymysql.cursors
import requests
# SQL statements
SQL = {
'CVREL': "SELECT subject,relationship,object FROM cv_relationship_vw "
+ "WHERE subject_id=%s OR object_id=%s",
'CVTERMREL': "SELECT subject,relationship,object FROM "
+ "cv_term_relationship_vw WHERE subject_id=%s OR "
+ "object_id=%s",
}
class CustomJSONEncoder(JSONEncoder):
def default(self, obj): # pylint: disable=E0202, W0221
try:
if isinstance(obj, datetime):
return obj.strftime('%a, %-d %b %Y %H:%M:%S')
iterable = iter(obj)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, obj)
__version__ = '0.2.0'
app = Flask(__name__)
app.json_encoder = CustomJSONEncoder
app.config.from_pyfile("config.cfg")
CONFIG = {'config': {'url': app.config['CONFIG_ROOT']}}
CVTERMS = dict()
SERVER = dict()
CORS(app)
conn = pymysql.connect(host=app.config['MYSQL_DATABASE_HOST'],
user=app.config['MYSQL_DATABASE_USER'],
password=app.config['MYSQL_DATABASE_PASSWORD'],
db=app.config['MYSQL_DATABASE_DB'],
cursorclass=pymysql.cursors.DictCursor)
cursor = conn.cursor()
app.config['STARTTIME'] = time()
app.config['STARTDT'] = datetime.now()
IDCOLUMN = 0
START_TIME = ESEARCH = PRODUCER = ''
# *****************************************************************************
# * Classes *
# *****************************************************************************
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
retval = dict(self.payload or ())
retval['rest'] = {'error': self.message}
return retval
# *****************************************************************************
# * Flask *
# *****************************************************************************
@app.before_request
def before_request():
global START_TIME, CVTERMS, CONFIG, ESEARCH, SERVER, PRODUCER
START_TIME = time()
g.db = conn
g.c = cursor
app.config['COUNTER'] += 1
endpoint = request.endpoint if request.endpoint else '(Unknown)'
app.config['ENDPOINTS'][endpoint] = app.config['ENDPOINTS'].get(endpoint, 0) + 1
if request.method == 'OPTIONS':
result = initialize_result()
return generate_response(result)
if not SERVER:
data = call_responder('config', 'config/rest_services')
CONFIG = data['config']
data = call_responder('config', 'config/servers')
SERVER = data['config']
try:
ESEARCH = elasticsearch.Elasticsearch(SERVER['elk-elastic']['address'])
except Exception as ex: # pragma: no cover
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print(message)
sys.exit(-1)
PRODUCER = KafkaProducer(bootstrap_servers=SERVER['Kafka']['broker_list'])
try:
g.c.execute('SELECT cv,cv_term,id FROM cv_term_vw ORDER BY 1,2')
rows = g.c.fetchall()
for row in rows:
if row['cv'] not in CVTERMS:
CVTERMS[row['cv']] = dict()
CVTERMS[row['cv']][row['cv_term']] = row['id']
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
# ******************************************************************************
# * Utility functions *
# ******************************************************************************
def call_profile (token):
server = 'neuprint'
url = CONFIG[server]['url'] + 'profile'
url = url.replace('/api', '')
headers = {"Content-Type": "application/json",
"Authorization": "Bearer " + token}
try:
req = requests.get(url, headers=headers)
except requests.exceptions.RequestException as err: # pragma no cover
print(err)
sys.exit(-1)
if req.status_code == 200:
return req.json()
elif req.status_code == 401:
raise InvalidUsage("Please provide a valid Auth Token", 401)
else:
print("Could not get response from %s" % (url))
print(req)
sys.exit(-1)
def call_responder(server, endpoint, payload=''):
url = CONFIG[server]['url'] + endpoint
try:
if payload:
headers = {"Content-Type": "application/json",
"Authorization": "Bearer " + app.config['BEARER']}
req = requests.post(url, headers=headers, json=payload)
else:
req = requests.get(url)
except requests.exceptions.RequestException as err: # pragma no cover
print(err)
sys.exit(-1)
if req.status_code == 200:
return req.json()
else:
print("Could not get response from %s: %s" % (url, req.text))
raise InvalidUsage(req.text, req.status_code)
def sql_error(err):
error_msg = ''
try:
error_msg = "MySQL error [%d]: %s" % (err.args[0], err.args[1])
except IndexError:
error_msg = "Error: %s" % err
if error_msg:
print(error_msg)
return error_msg
def initialize_result():
result = {"rest": {'requester': request.remote_addr,
'url': request.url,
'endpoint': request.endpoint,
'error': False,
'elapsed_time': '',
'row_count': 0}}
if 'Authorization' in request.headers:
token = re.sub(r'Bearer\s+', '', request.headers['Authorization'])
dtok = dict()
app.config['BEARER'] = token
dtok = call_profile(token)
result['rest']['user'] = dtok['ImageURL']
app.config['USERS'][dtok['ImageURL']] = app.config['USERS'].get(dtok['ImageURL'], 0) + 1
elif request.method in ['DELETE', 'POST'] or request.endpoint in app.config['REQUIRE_AUTH']:
raise InvalidUsage('You must authorize to use this endpoint', 401)
if app.config['LAST_TRANSACTION'] and time() - app.config['LAST_TRANSACTION'] >= app.config['RECONNECT_SECONDS']:
g.db.ping()
app.config['LAST_TRANSACTION'] = time()
return result
def add_key_value_pair(key, val, separator, sql, bind):
eprefix = ''
if not isinstance(key, str):
key = key.decode('utf-8')
if re.search(r'[!><]$', key):
match = re.search(r'[!><]$', key)
eprefix = match.group(0)
key = re.sub(r'[!><]$', '', key)
if not isinstance(val[0], str):
val[0] = val[0].decode('utf-8')
if '*' in val[0]:
val[0] = val[0].replace('*', '%')
if eprefix == '!':
eprefix = ' NOT'
else:
eprefix = ''
sql += separator + ' ' + key + eprefix + ' LIKE %s'
else:
sql += separator + ' ' + key + eprefix + '=%s'
bind = bind + (val,)
return sql, bind
def generate_sql(result, sql, query=False):
bind = ()
global IDCOLUMN
IDCOLUMN = 0
query_string = 'id='+str(query) if query else request.query_string
order = ''
if query_string:
if not isinstance(query_string, str):
query_string = query_string.decode('utf-8')
ipd = parse_qs(query_string)
separator = ' AND' if ' WHERE ' in sql else ' WHERE'
for key, val in ipd.items():
if key == '_sort':
order = ' ORDER BY ' + val[0]
elif key == '_columns':
sql = sql.replace('*', val[0])
varr = val[0].split(',')
if 'id' in varr:
IDCOLUMN = 1
elif key == '_distinct':
if 'DISTINCT' not in sql:
sql = sql.replace('SELECT', 'SELECT DISTINCT')
else:
sql, bind = add_key_value_pair(key, val, separator, sql, bind)
separator = ' AND'
sql += order
if bind:
result['rest']['sql_statement'] = sql % bind
else:
result['rest']['sql_statement'] = sql
return sql, bind
def execute_sql(result, sql, container, query=False):
sql, bind = generate_sql(result, sql, query)
if app.config['DEBUG']: # pragma: no cover
if bind:
print(sql % bind)
else:
print(sql)
try:
if bind:
g.c.execute(sql, bind)
else:
g.c.execute(sql)
rows = g.c.fetchall()
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
result[container] = []
if rows:
result[container] = rows
result['rest']['row_count'] = len(rows)
return 1
raise InvalidUsage("No rows returned for query %s" % (sql,), 404)
def show_columns(result, table):
result['columns'] = []
try:
g.c.execute("SHOW COLUMNS FROM " + table)
rows = g.c.fetchall()
if rows:
result['columns'] = rows
result['rest']['row_count'] = len(rows)
return 1
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
def get_additional_cv_data(sid):
sid = str(sid)
g.c.execute(SQL['CVREL'], (sid, sid))
cvrel = g.c.fetchall()
return cvrel
def get_cv_data(result, cvs):
result['data'] = []
try:
for col in cvs:
tcv = col
if ('id' in col) and (not IDCOLUMN):
cvrel = get_additional_cv_data(col['id'])
tcv['relationships'] = list(cvrel)
result['data'].append(tcv)
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
def get_additional_cv_term_data(sid):
sid = str(sid)
g.c.execute(SQL['CVTERMREL'], (sid, sid))
cvrel = g.c.fetchall()
return cvrel
def get_cv_term_data(result, cvterms):
result['data'] = []
try:
for col in cvterms:
cvterm = col
if ('id' in col) and (not IDCOLUMN):
cvtermrel = get_additional_cv_term_data(col['id'])
cvterm['relationships'] = list(cvtermrel)
result['data'].append(cvterm)
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
def update_property(result, proptype):
ipd = dict()
if request.form:
result['rest']['form'] = request.form
for i in request.form:
ipd[i] = request.form[i]
elif request.json:
result['rest']['json'] = request.json
ipd = request.json
missing = ''
for ptmp in ['id', 'cv', 'term', 'value']:
if ptmp not in ipd:
missing = missing + ptmp + ' '
if missing:
raise InvalidUsage('Missing arguments: ' + missing)
sql = 'SELECT id FROM %s WHERE ' % (proptype)
sql += 'id=%s'
bind = (ipd['id'],)
try:
g.c.execute(sql, bind)
rows = g.c.fetchall()
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
if len(rows) != 1:
raise InvalidUsage(('Could not find %s ID %s' % (proptype, ipd['id'])), 404)
if ipd['cv'] in CVTERMS and ipd['term'] in CVTERMS[ipd['cv']]:
sql = 'INSERT INTO %s_property (%s_id,type_id,value) ' % (proptype, proptype)
sql += 'VALUES(%s,%s,%s)'
bind = (ipd['id'], CVTERMS[ipd['cv']][ipd['term']], ipd['value'],)
result['rest']['sql_statement'] = sql % bind
try:
g.c.execute(sql, bind)
result['rest']['row_count'] = g.c.rowcount
result['rest']['inserted_id'] = g.c.lastrowid
g.db.commit()
return
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
raise InvalidUsage(('Could not find CV/term %s/%s' % (ipd['cv'], ipd['term'])), 404)
def generate_response(result):
global START_TIME
result['rest']['elapsed_time'] = str(timedelta(seconds=(time() - START_TIME)))
return jsonify(**result)
def publish(result, message):
message['uri'] = request.url
message['client'] = 'mad_responder'
message['user'] = result['rest']['user']
message['host'] = os.uname()[1]
message['status'] = 200
message['time'] = int(time())
future = PRODUCER.send(app.config['KAFKA_TOPIC'], json.dumps(message).encode('utf-8'))
try:
future.get(timeout=10)
except KafkaError:
print("Failed sending to Kafka!")
# *****************************************************************************
# * Endpoints *
# *****************************************************************************
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/')
def show_swagger():
return render_template('swagger_ui.html')
@app.route("/spec")
def spec():
return get_doc_json()
@app.route('/doc')
def get_doc_json():
swag = swagger(app)
swag['info']['version'] = __version__
swag['info']['title'] = "MAD Responder"
return jsonify(swag)
@app.route("/stats")
def stats():
'''
Show stats
Show uptime/requests statistics
---
tags:
- Diagnostics
responses:
200:
description: Stats
400:
description: Stats could not be calculated
'''
tbt = time() - app.config['LAST_TRANSACTION']
result = initialize_result()
db_connection = True
try:
g.db.ping(reconnect=False)
except Exception as err:
template = "An exception of type {0} occurred. Arguments:{1!r}"
message = template.format(type(err).__name__, err.args)
result['rest']['error'] = 'Error: %s' % (message,)
db_connection = False
try:
start = datetime.fromtimestamp(app.config['STARTTIME']).strftime('%Y-%m-%d %H:%M:%S')
up_time = datetime.now() - app.config['STARTDT']
result['stats'] = {"version": __version__,
"requests": app.config['COUNTER'],
"start_time": start,
"uptime": str(up_time),
"python": sys.version,
"pid": os.getpid(),
"endpoint_counts": app.config['ENDPOINTS'],
"user_counts": app.config['USERS'],
"time_since_last_transaction": tbt,
"database_connection": db_connection}
if None in result['stats']['endpoint_counts']:
del result['stats']['endpoint_counts']
except Exception as err:
template = "An exception of type {0} occurred. Arguments:{1!r}"
message = template.format(type(err).__name__, err.args)
raise InvalidUsage('Error: %s' % (message,))
return generate_response(result)
@app.route('/processlist/columns', methods=['GET'])
def get_processlist_columns():
'''
Get columns from the system processlist table
Show the columns in the system processlist table, which may be used to
filter results for the /processlist endpoints.
---
tags:
- Diagnostics
responses:
200:
description: Columns in system processlist table
'''
result = initialize_result()
show_columns(result, "information_schema.processlist")
return generate_response(result)
@app.route('/processlist', methods=['GET'])
def get_processlist_info():
'''
Get processlist information (with filtering)
Return a list of processlist entries (rows from the system processlist
table). The caller can filter on any of the columns in the system
processlist table. Inequalities (!=) and some relational operations
(<= and >=) are supported. Wildcards are supported (use "*").
Specific columns from the system processlist table can be returned with
the _columns key. The returned list may be ordered by specifying a column
with the _sort key. In both cases, multiple columns would be separated
by a comma.
---
tags:
- Diagnostics
responses:
200:
description: List of information for one or database processes
404:
description: Processlist information not found
'''
result = initialize_result()
execute_sql(result, 'SELECT * FROM information_schema.processlist', 'data')
for row in result['data']:
row['HOST'] = 'None' if row['HOST'] is None else row['HOST'].decode("utf-8")
return generate_response(result)
@app.route('/processlist/host', methods=['GET'])
def get_processlist_host_info(): # pragma: no cover
'''
Get processlist information for this host
Return a list of processlist entries (rows from the system processlist
table) for this host.
---
tags:
- Diagnostics
responses:
200:
description: Database process list information for the current host
404:
description: Processlist information not found
'''
result = initialize_result()
hostname = platform.node() + '%'
try:
sql = "SELECT * FROM information_schema.processlist WHERE host LIKE %s"
result['rest']['sql_statement'] = sql % hostname
g.c.execute(sql, (hostname,))
rows = g.c.fetchall()
result['rest']['row_count'] = len(rows)
for row in rows:
row['HOST'] = 'None' if row['HOST'] is None else row['HOST'].decode("utf-8")
result['data'] = rows
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
return generate_response(result)
@app.route("/ping")
def pingdb():
'''
Ping the database connection
Ping the database connection and reconnect if needed
---
tags:
- Diagnostics
responses:
200:
description: Ping successful
400:
description: Ping unsuccessful
'''
result = initialize_result()
try:
g.db.ping()
except Exception as err:
raise InvalidUsage(sql_error(err), 400)
return generate_response(result)
# *****************************************************************************
# * Test endpoints *
# *****************************************************************************
@app.route('/test_sqlerror', methods=['GET'])
def testsqlerror():
result = initialize_result()
try:
sql = "SELECT some_column FROM non_existent_table"
result['rest']['sql_statement'] = sql
g.c.execute(sql)
rows = g.c.fetchall()
return rows
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
@app.route('/test_other_error', methods=['GET'])
def testothererror():
result = initialize_result()
try:
testval = 4 / 0
result['testval'] = testval
return result
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
# *****************************************************************************
# * CV/CV term endpoints *
# *****************************************************************************
@app.route('/cvs/columns', methods=['GET'])
def get_cv_columns():
'''
Get columns from cv table
Show the columns in the cv table, which may be used to filter results for
the /cvs and /cv_ids endpoints.
---
tags:
- CV
responses:
200:
description: Columns in cv table
'''
result = initialize_result()
show_columns(result, "cv")
return generate_response(result)
@app.route('/cv_ids', methods=['GET'])
def get_cv_ids():
'''
Get CV IDs (with filtering)
Return a list of CV IDs. The caller can filter on any of the columns in the
cv table. Inequalities (!=) and some relational operations (<= and >=)
are supported. Wildcards are supported (use "*"). The returned list may be
ordered by specifying a column with the _sort key. Multiple columns should
be separated by a comma.
---
tags:
- CV
responses:
200:
description: List of one or more CV IDs
404:
description: CVs not found
'''
result = initialize_result()
if execute_sql(result, 'SELECT id FROM cv', 'temp'):
result['data'] = []
for col in result['temp']:
result['data'].append(col['id'])
del result['temp']
return generate_response(result)
@app.route('/cvs/<string:sid>', methods=['GET'])
def get_cv_by_id(sid):
'''
Get CV information for a given ID
Given an ID, return a row from the cv table. Specific columns from the cv
table can be returned with the _columns key. Multiple columns should be
separated by a comma.
---
tags:
- CV
parameters:
- in: path
name: sid
type: string
required: true
description: CV ID
responses:
200:
description: Information for one CV
404:
description: CV ID not found
'''
result = initialize_result()
if execute_sql(result, 'SELECT * FROM cv', 'temp', sid):
get_cv_data(result, result['temp'])
del result['temp']
return generate_response(result)
@app.route('/cvs', methods=['GET'])
def get_cv_info():
'''
Get CV information (with filtering)
Return a list of CVs (rows from the cv table). The caller can filter on
any of the columns in the cv table. Inequalities (!=) and some relational
operations (<= and >=) are supported. Wildcards are supported
(use "*"). Specific columns from the cv table can be returned with the
_columns key. The returned list may be ordered by specifying a column with
the _sort key. In both cases, multiple columns would be separated by a
comma.
---
tags:
- CV
responses:
200:
description: List of information for one or more CVs
404:
description: CVs not found
'''
result = initialize_result()
if execute_sql(result, 'SELECT * FROM cv', 'temp'):
get_cv_data(result, result['temp'])
del result['temp']
return generate_response(result)
@app.route('/cv', methods=['OPTIONS', 'POST'])
def add_cv(): # pragma: no cover
'''
Add CV
---
tags:
- CV
parameters:
- in: query
name: name
type: string
required: true
description: CV name
- in: query
name: definition
type: string
required: true
description: CV description
- in: query
name: display_name
type: string
required: false
description: CV display name (defaults to CV name)
- in: query
name: version
type: string
required: false
description: CV version (defaults to 1)
- in: query
name: is_current
type: string
required: false
description: is CV current? (defaults to 1)
responses:
200:
description: CV added
400:
description: Missing arguments
'''
result = initialize_result()
ipd = dict()
if request.form:
result['rest']['form'] = request.form
for i in request.form:
ipd[i] = request.form[i]
missing = ''
for ptmp in ['name', 'definition']:
if ptmp not in ipd:
missing = missing + ptmp + ' '
if missing:
raise InvalidUsage('Missing arguments: ' + missing)
if 'display_name' not in ipd:
ipd['display_name'] = ipd['name']
if 'version' not in ipd:
ipd['version'] = 1
if 'is_current' not in ipd:
ipd['is_current'] = 1
if not result['rest']['error']:
try:
bind = (ipd['name'], ipd['definition'], ipd['display_name'],
ipd['version'], ipd['is_current'],)
result['rest']['sql_statement'] = SQL['INSERT_CV'] % bind
g.c.execute(SQL['INSERT_CV'], bind)
result['rest']['row_count'] = g.c.rowcount
result['rest']['inserted_id'] = g.c.lastrowid
g.db.commit()
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
return generate_response(result)
@app.route('/cvterms/columns', methods=['GET'])
def get_cv_term_columns():
'''
Get columns from cv_term_vw table
Show the columns in the cv_term_vw table, which may be used to filter
results for the /cvterms and /cvterm_ids endpoints.
---
tags:
- CV
responses:
200:
description: Columns in cv_term_vw table
'''
result = initialize_result()
show_columns(result, "cv_term_vw")
return generate_response(result)
@app.route('/cvterm_ids', methods=['GET'])
def get_cv_term_ids():
'''
Get CV term IDs (with filtering)
Return a list of CV term IDs. The caller can filter on any of the columns
in the cv_term_vw table. Inequalities (!=) and some relational operations
(<= and >=) are supported. Wildcards are supported (use "*"). The
returned list may be ordered by specifying a column with the _sort key.
Multiple columns should be separated by a comma.
---
tags:
- CV
responses:
200:
description: List of one or more CV term IDs
404:
description: CV terms not found
'''
result = initialize_result()
if execute_sql(result, 'SELECT id FROM cv_term_vw', 'temp'):
result['data'] = []
for col in result['temp']:
result['data'].append(col['id'])
del result['temp']
return generate_response(result)
@app.route('/cvterms/<string:sid>', methods=['GET'])
def get_cv_term_by_id(sid):
'''
Get CV term information for a given ID
Given an ID, return a row from the cv_term_vw table. Specific columns from
the cv_term_vw table can be returned with the _columns key. Multiple columns
should be separated by a comma.
---
tags:
- CV
parameters:
- in: path
name: sid
type: string
required: true
description: CV term ID
responses:
200:
description: Information for one CV term
404:
description: CV term ID not found
'''
result = initialize_result()
if execute_sql(result, 'SELECT * FROM cv_term_vw', 'temp', sid):
get_cv_term_data(result, result['temp'])
del result['temp']
return generate_response(result)
@app.route('/cvterms', methods=['GET'])
def get_cv_term_info():
'''
Get CV term information (with filtering)
Return a list of CV terms (rows from the cv_term_vw table). The caller can
filter on any of the columns in the cv_term_vw table. Inequalities (!=)
and some relational operations (<= and >=) are supported. Wildcards
are supported (use "*"). Specific columns from the cv_term_vw table can be
returned with the _columns key. The returned list may be ordered by
specifying a column with the _sort key. In both cases, multiple columns
would be separated by a comma.
---
tags:
- CV
responses:
200:
description: List of information for one or more CV terms
404:
description: CV terms not found
'''
result = initialize_result()
if execute_sql(result, 'SELECT * FROM cv_term_vw', 'temp'):
get_cv_term_data(result, result['temp'])
del result['temp']
return generate_response(result)
@app.route('/cvterm', methods=['OPTIONS', 'POST'])
def add_cv_term(): # pragma: no cover
'''
Add CV term
---
tags:
- CV
parameters:
- in: query
name: cv
type: string
required: true
description: CV name
- in: query
name: name
type: string
required: true
description: CV term name
- in: query
name: definition
type: string
required: true
description: CV term description
- in: query
name: display_name
type: string
required: false
description: CV term display name (defaults to CV term name)
- in: query
name: is_current
type: string
required: false
description: is CV term current? (defaults to 1)
- in: query
name: data_type
type: string
required: false
description: data type (defaults to text)
responses:
200:
description: CV term added
400:
description: Missing arguments
'''
result = initialize_result()
ipd = dict()
if request.form:
result['rest']['form'] = request.form
for i in request.form:
ipd[i] = request.form[i]
missing = ''
for ptmp in ['cv', 'name', 'definition']:
if ptmp not in ipd:
missing = missing + ptmp + ' '
if missing:
raise InvalidUsage('Missing arguments: ' + missing)
if 'display_name' not in ipd:
ipd['display_name'] = ipd['name']
if 'is_current' not in ipd:
ipd['is_current'] = 1
if 'data_type' not in ipd:
ipd['data_type'] = 'text'
if not result['rest']['error']:
try:
bind = (ipd['cv'], ipd['name'], ipd['definition'],
ipd['display_name'], ipd['is_current'],
ipd['data_type'],)
result['rest']['sql_statement'] = SQL['INSERT_CVTERM'] % bind
g.c.execute(SQL['INSERT_CVTERM'], bind)
result['rest']['row_count'] = g.c.rowcount
result['rest']['inserted_id'] = g.c.lastrowid
g.db.commit()
except Exception as err:
raise InvalidUsage(sql_error(err), 500)
return generate_response(result)
# *****************************************************************************
# * Annotation endpoints *
# *****************************************************************************
@app.route('/annotations/columns', methods=['GET'])
def get_annotations_columns():
'''
Get columns from annotation_vw table
Show the columns in the annotation_vw table, which may be used to filter
results for the /annotations and /annotation_ids endpoints.
---
tags:
- Annotation
responses:
200:
description: Columns in annotation_vw table
'''
result = initialize_result()
show_columns(result, "annotation_vw")
return generate_response(result)
@app.route('/annotation_ids', methods=['GET'])
def get_annotation_ids():
'''
Get annotation IDs (with filtering)
Return a list of annotation IDs. The caller can filter on any of the
columns in the annotation_vw table. Inequalities (!=) and some relational
operations (<= and >=) are supported. Wildcards are supported
(use "*"). The returned list may be ordered by specifying a column with
the _sort key. Multiple columns should be separated by a comma.
---
tags:
- Annotation
responses:
200:
description: List of one or more annotation IDs
404:
description: Annotations not found
'''
result = initialize_result()
if execute_sql(result, 'SELECT id FROM annotation_vw', 'temp'):
result['data'] = []
for col in result['temp']:
result['data'].append(col['id'])
del result['temp']
return generate_response(result)
@app.route('/annotations/<string:sid>', methods=['GET'])
def get_annotations_by_id(sid):
'''
Get annotation information for a given ID
Given an ID, return a row from the annotation_vw table. Specific columns