-
Notifications
You must be signed in to change notification settings - Fork 2
/
routes.py
1430 lines (1070 loc) · 45.8 KB
/
routes.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
import glob
import sys
import os
import base64
import urllib
from operator import itemgetter
print "importing flask"
from flask import Flask, request, session, send_file, escape, g, redirect, url_for, abort, render_template, flash, make_response, jsonify, Markup, Response, send_from_directory, Blueprint, json
print "importing jinja2"
from jinja2 import TemplateNotFound, Markup
print "importing user database"
sys.path.insert(0, os.path.dirname(os.path.abspath( __file__ )))
from user_database import *
DATABASES_DB_NAME = 0
DATABASES_DB_F_NAME = 1
DATABASES_DB_CONF = 2
DATABASES_MTIME = 3
DATABASES_INTERFACE = 4
@app.before_request
def before_request():
"""
before each request, add global variables to the global G variable.
If using WSGI (eg. apache), this won't work
"""
#print "before request", request.url, request.base_url, request.url_root, request.endpoint
if app.config['HAS_LOGIN']:
#if get_users() > 0:
#print "before request: has config"
if 'username' in session:
#print "before request: has config - has username set"
print 'Logged in as %s' % (escape(session['username']))
else:
is_libre = False
for librepath in app.config['LIBRE_PATHS' ]:
if request.path.startswith( librepath ):
#print "before request: has config - no username set - redirecting to login", url_for('login')
print "before request: has config - no username set - libre path: request",request.path, "libre", librepath
is_libre = True
break
#abort(401)
if not is_libre:
for librepoint in app.config['LIBRE_POINTS']:
if request.endpoint == librepoint:
#print "before request: has config - no username set - redirecting to login", url_for('login')
print "before request: has config - no username set - libre endpoint: request",request.endpoint, "libre", librepoint
is_libre = True
break
if not is_libre:
print "not libre", request.endpoint, request.path, 'redirecting'
#for r in dir(request):
# try:
# print "r", r, '=',getattr(request, r)
# except:
# pass
return redirect(url_for('login', _external=True))
@app.route('/login', methods=['GET', 'POST'])
def login():
"""
Perform login
"""
print "login"
message = ""
if app.config['HAS_LOGIN']:
print "login: has config"
if request.method == 'POST':
#print "login: has config - POST"
username = request.form.get('username', None)
password = request.form.get('password', None)
noonce = request.form.get('noonce' , None)
if app.config['USE_ENCRYPTION']:
if password is not None:
password = app.config["ENCRYPTION_INST"].decrypter( password )
print "login: has config - POST - username %s password %s noonce %s" % ( username, password, noonce )
if username is not None and password is not None and noonce is not None and "noonce" in session and noonce == session["noonce"]:
print "login: has config - POST - not none. noonce match"
if check_user_exists(username):
print "login: has config - POST - not none - user in credentials - username %s password %s noonce %s" % ( username, password, noonce )
if verify_user_credentials(username, password, noonce):
#print "login: has config - POST - not none - user in credentials - right password"
session['username'] = username
del session['noonce']
return redirect(url_for('get_main', _external=True))
else:
print "login: has config - POST - not none. noonce match", noonce, ( session["noonce"] if "noonce" in session else None )
message = "WRONG PASSWORD"
else:
message = "NO SUCH USER"
else:
print "login: has config - POST - not none. noonce does not match", noonce, ( session["noonce"] if "noonce" in session else None )
message = "TRY AGAIN"
session["noonce"] = gen_noonce()
print "new noonce", session["noonce"]
return render_template('login.html', noonce=session["noonce"], message=message, app=app)
#return app.send_static_file('login.html')
else:
print "login: no config"
return redirect(url_for('get_main', _external=True))
@app.route('/admin', methods=['GET', 'POST'])
def admin():
"""
Administration page
"""
message = None
print "admin"
if app.config['HAS_LOGIN']:
if request.method == 'POST':
print "admin: has config - POST"
action = request.form.get('action' , None)
username = request.form.get('username', None)
password = request.form.get('password', None)
noonce = request.form.get('noonce' , None)
security = request.form.get('security', None)
if app.config['USE_ENCRYPTION']:
if password is not None:
password = app.config["ENCRYPTION_INST"].decrypter( password )
print "admin: has config - POST - action %s username %s password %s noonce %s security %s" % tuple([ str(x) for x in ( action, username, password, noonce, security ) ])
#if username is not None and action is not None and noonce is not None and username != "admin" and "noonce" in session and noonce == session["noonce"]:
if username is not None and action is not None and noonce is not None and "noonce" in session and noonce == session["noonce"]:
if action == "add":
print "admin: has config - POST. ADDING USER"
if password is None or generate_password_hash(username+noonce) == password:
print "admin: has config - POST - not none. noonce match. NO PASSWORD"
message = "FAILED TO ADD USER %s. NO PASSWORD" % username
elif not str(username).isalnum():
print "admin: has config - POST - not none. noonce match. INVALID USERNAME"
message = "FAILED TO ADD USER %s. INVALID USERNAME" % username
else:
print "admin: has config - POST - not none. noonce match"
if check_user_exists(username):
print "admin: has config - POST - not none - user in credentials. ALREADY EXISTS"
message = "FAILED TO ADD USER %s. ALREADY EXISTS" % username
else:
if security is None or security != generate_password_hash(password+noonce):
print "admin: has config - POST - not none. SECURITY FAILED %s vs %s" % (str(security), generate_password_hash(password+noonce))
message = "FAILED TO ADD USER %s. SECURITY FAILED" % ( username )
else:
print "admin: has config - POST - not none - user not in credentials. ADDING user %s pass %s salt %s" % ( username, password, noonce )
add_user(username, password, noonce)
message = "SUCCESS IN ADDING USER %s" % ( username )
elif action == "del":
print "admin: has config - POST - not none. noonce match. DELETING USER:", username
if check_user_exists(username):
del_user(username)
message = "SUCCESS IN DELETING USER %s" % username
else:
message = "FAILED TO DELETE USER '%s'. DOES NOT EXISTS" % username
else:
message = "TRY AGAIN"
session["noonce"] = gen_noonce()
print "new noonce", session["noonce"]
#return render_template('admin.html', users=[x for x in sorted(get_users()) if x != "admin"], message=message, noonce=session["noonce"], app=app)
return render_template('admin.html', users=[x for x in sorted(get_users())], message=message, noonce=session["noonce"], app=app)
#return app.send_static_file('login.html')
else:
print "admin: no config"
return redirect(url_for('get_main', _external=True))
@app.route('/salt/<username>', methods=['GET'])
def getsalt(username):
"""
Get user's salt
"""
print "get user %s salt" % username
salt = None
if app.config['HAS_LOGIN']:
if check_user_exists(username):
salt = get_salt(username)
return jsonify({'salt' : salt})
else:
return jsonify({'salt' : 'peper'})
@app.route('/logout', methods=['GET'])
def logout():
"""
Perform logout
"""
print "logoff"
if app.config['HAS_LOGIN'] and 'username' in session:
print "logoff from user %s: has config" % str(session['username'])
session.pop('username', None)
#return redirect(url_for('get_main'))
return redirect(url_for('login', _external=True))
else:
return redirect(url_for('get_main', _external=True))
@app.route("/username", methods=['GET'])
def get_username():
if app.config['HAS_LOGIN']:
return jsonify({'username': session['username']})
else:
return jsonify({'username': 'libre'})
@app.route("/", methods=['GET'])
def get_main():
#return redirect ( url_for('static', filename='index.html' ) )
if app.config['HAS_LOGIN'] and session['username'] == 'admin':
return redirect(url_for('admin', _external=True))
return app.send_static_file('index.html')
@app.route("/alive", methods=['GET'])
def get_alive():
res = jsonify( { 'res': True } )
res.headers['Access-Control-Allow-Origin'] = '*'
return res
@app.route("/api", methods=['GET'])
def get_api():
api = {
"/api/dbs" : { 'databases': ['str:db_name'] },
"/api/maxnumcol" : { 'maxnumcol': 'int:num_cols' },
"/api/mtime/<db_name>" : { 'mtime' : 'date:creation_date' },
"/api/spps/<db_name>" : { 'spps' : ['str:ref' ] },
"/api/chroms/<db_name>" : { 'chroms': ['str:chrom'] },
"/api/clusterlist/<db_name>" : {
"str:name_space": [
"str:cluster_name"
]
},
"/api/genes/<db_name>/<chrom>" : { 'genes' : ['str:gene' ] },
"/api/tree/<db_name>/<chrom>/<gene>" : { 'chrom' : 'str:chrom', 'gene': 'str:gene', 'tree' : { "newick": "str[newick]:tree_string", "png": "str[base64]:png_image" } },
"/api/alignment/<db_name>/<chrom>/<gene>": { 'chrom' : 'str:chrom', 'gene': 'str:gene', "alignment": { "coords": [ 'int:snp_pos' ], "fasta": { "str:ref": "str:alignment" } } },
"/api/matrix/<db_name>/<chrom>/<gene>" : { 'chrom' : 'str:chrom', 'gene': 'str:gene', 'matrix' : [ [ 'int:distance' ] ] },
"/api/report/<db_name>/<chrom>/<gene>" : {
"END" : 'int:end_pos',
"FASTA": {
"coords": [ 'int:pos' ],
"fasta" : { "int:ref": "str:alignment" }
},
"LEN_OBJ": 'int:',
"LEN_SNP": 'int:num_snps',
"LINE": [ [ 'float:distance' ] ],
"NAME" : "str:gene",
"START": "int:start_pos",
"TREE" : {
"newick": "str[newick]:tree_string",
"png" : "str[base64]:png_image"
},
"chrom" : "str:chrom",
"db_name": "str:db_name",
"gene" : "str:gene",
"spps" : [ "str:ref" ]
},
"/api/cluster/<db_name>/<ref>/<chrom>[?(png|svg)&(rows|columns|lst)]" : {
"str:cluster_name": {
"cols": {
"colsNewick": None,
"colsOrder" : None,
"colsPng" : None,
"colsSvg" : None
},
"rows": {
"rowsNewick": "null|str[newick]:tree_string",
"rowsOrder" : [ 'int:row_number' ],
"rowsPng" : "null|str[base64]: png_image",
"rowsSvg" : "null|str[base64]: svg_image"
}
}
},
"/api/data/<db_name>/<ref>/<chrom>" : {
"clusters": {
"str:cluster_name": {
"cols": {
"colsNewick": None,
"colsOrder" : None,
"colsPng" : None,
"colsSvg" : None
},
"rows": {
"rowsNewick": "null|str[newick]:tree_string",
"rowsOrder" : [ 'int:row_number' ],
"rowsPng" : "null|str[base64]: png_image",
"rowsSvg" : "null|str[base64]: svg_image"
}
}
},
"data": {
"line": [
[
[
"float:distance",
"int:row_num",
"int:col_num"
],
]
],
"name": [ "str:ref" ]
},
"data_info": {
"length" : "int:chromosome_length",
"length_abs" : "int:absolute_chromosome_length",
"maxPos" : "int:max_pos",
"maxPosAbs" : "int:absolute_max_pos",
"maxVal" : "float:max_matrix_val",
"minPos" : "int:min_pos",
"minPosAbs" : "int:absolute_min_pos",
"minVal" : "float:min_matrix_val",
"num_cols" : "int:num_columns",
"num_cols_total": "int:total_num_columns",
"num_rows" : "int:num_rows"
},
"header": {
"end" : [ "int:segment_end_pos" ],
"name" : [ "str:segment_name" ],
"num_snps" : [ "int:num_snps_in_segment" ],
"num_unities": [ "int:num_entities_in_segment" ],
"start" : [ "int:segment_start_pos" ]
},
"request": {
"chrom" : "str:chomosome",
"classes" : "null|int:num_classes",
"endPos" : "null|int:end_pos",
"evenly" : "bool:evenly_split",
"group" : "null|int:num_groups",
"maxNum" : "null|int:max_num_of_segments",
"page" : "null|int:current_page",
"ref" : "str:ref",
"startPos": "null|int:start_pos"
}
},
"/api/help" : "str:help_string",
"/api/example" : "str:example_data"
}
res = jsonify( { 'api': api } )
res.headers['Access-Control-Allow-Origin'] = '*'
return res
@app.route("/api/help", methods=['GET'])
def get_api_help():
hlp = """\
curl "http://assembly.ab.wurnet.nl:10000/api
LIST OF API METHODS
curl "http://assembly.ab.wurnet.nl:10000/api/example"
EXAMPLE DATA
curl "http://assembly.ab.wurnet.nl:10000/api/dbs"
{
"databases": [
"Arabidopsis 50k",
"Arabidopsis 10k - Chr 4 - Xianwen",
"Tomato 84 - 10Kb - Introgression",
"Tomato 84 - 10Kb",
"Tomato 60 RIL - 50k - RIL mode - Delete",
"Arabidopsis 10k - Chr 4 - Xianwen - Single",
"Tomato 84 - 50Kb",
"Tomato 60 RIL - 50k",
"Tomato 84 - Genes",
"Tomato 60 RIL - 10k",
"Tomato 60 RIL - 50k - RIL mode - Greedy",
"Tomato 60 RIL - 50k - RIL mode",
"Arabidopsis 50k - Chr 4 - Xianwen",
"Tomato 84 - 50Kb - Introgression",
"Arabidopsis 50k - Chr 4 - Xianwen - Single"
]
}
curl "http://assembly.ab.wurnet.nl:10000/api/spps/Arabidopsis%2050k"
{
"spps": [
"11C1",
"7015",
"8411",
"Zupan-1",
"ref"
]
}
curl "http://assembly.ab.wurnet.nl:10000/api/chroms/Arabidopsis%2050k"
{
"chroms": [
"Chr1",
"Chr2",
"Chr3",
"Chr4",
"Chr5"
]
}
curl "http://assembly.ab.wurnet.nl:10000/api/data/Arabidopsis%2050k/ref/Chr5"
FULL DATA
"""
resp = Response(
response=hlp,
status=200,
mimetype='text/html'
)
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
@app.route("/api/example", methods=['GET'])
def get_api_example():
dbs = json.loads( get_dbs().data )
db_name = dbs['databases'][0]
maxnumcol = json.loads( get_max_num_col().data )
mtime = json.loads( get_mtime(db_name).data )
spps = json.loads( get_spps(db_name).data )
chroms = json.loads( get_chroms(db_name).data )
chrom = chroms["chroms"][0]
clusterlist = json.loads( get_cluster_list(db_name).data )
genes = json.loads( get_genes(db_name, chrom).data )
gene = genes["genes"][0]
tree = json.loads( get_tree(db_name, chrom, gene).data )
alignment = json.loads( get_aln(db_name, chrom, gene).data )
matrix = json.loads( get_matrix(db_name, chrom, gene).data )
report = json.loads( get_report(db_name, chrom, gene).data )
ref = spps["spps"][0]
cluster = json.loads( get_cluster(db_name, ref, chrom).data )
data = json.loads( get_data(db_name, ref, chrom).data )
api = {
"/api/dbs" : dbs,
"/api/maxnumcol" : maxnumcol,
"/api/mtime/<db_name>" : mtime,
"/api/spps/<db_name>" : spps,
"/api/chroms/<db_name>" : chroms,
"/api/clusterlist/<db_name>" : clusterlist,
"/api/genes/<db_name>/<chrom>" : genes,
"/api/tree/<db_name>/<chrom>/<gene>" : tree,
"/api/alignment/<db_name>/<chrom>/<gene>": alignment,
"/api/matrix/<db_name>/<chrom>/<gene>" : matrix,
"/api/report/<db_name>/<chrom>/<gene>" : report,
"/api/cluster/<db_name>/<chrom>/<gene>" : cluster,
"/api/data/<db_name>/<chrom>/<gene>" : data
}
#print "DBS", dbs, dir(dbs)
#for r in dir(dbs):
# try:
# print " R", r, " = ", getattr(dbs, r)
# except:
# pass
res = jsonify( { 'api': api } )
res.headers['Access-Control-Allow-Origin'] = '*'
return res
@app.route("/api/spps/<db_name>", methods=['GET'])
def get_spps(db_name):
"""
Get list of species available to the database
"""
man = getManager(db_name)
if man is None:
print "no such manager"
abort(404)
spps = get_spps_raw( man )
if spps is None:
print "no species information"
abort(404)
if len(spps) == 0:
print "no species"
abort(404)
return jsonify({'spps' : spps})
@app.route("/api/chroms/<db_name>", methods=['GET'])
def get_chroms(db_name):
"""
Get list of chromosomes available to the database
"""
man = getManager(db_name)
if man is None:
print "no such manager"
abort(404)
chroms = get_chroms_raw( man )
if chroms is None:
print "no chromosome information"
abort(404)
if len(chroms) == 0:
print "no chromosomes"
abort(404)
return jsonify({'chroms': chroms})
@app.route("/api/genes/<db_name>/<chrom>", methods=['GET'])
def get_genes(db_name, chrom):
"""
Get list of genes available for database/chromosome combination
"""
man = getManager(db_name)
if man is None:
print "no such manager"
abort(404)
genes = get_genes_raw(man, chrom)
if genes is None:
print "no genes information"
abort(404)
if len(genes) == 0:
print "no genes"
abort(404)
return jsonify({'genes': genes})
@app.route("/api/tree/<db_name>/<chrom>/<gene>", methods=['GET'])
def get_tree(db_name, chrom, gene):
"""
Get phylogenetic tree from gene
"""
man = getManager(db_name)
if man is None:
print "no such manager"
abort(404)
if chrom not in man.getChroms():
abort( 404 )
genes = get_genes_raw(man, chrom)
if genes is None:
abort(404)
if gene not in genes:
print 'gene',gene, 'not in genes'#,genes
abort(404)
tree = get_tree_raw(man, chrom, gene)
if tree is None:
abort(404)
try:
tree['png'] = base64.standard_b64encode( tree['png'] )
except:
print "error getting tree png"
abort(404)
return jsonify( {'chrom': chrom, 'gene': gene, 'tree': tree } )
@app.route("/api/alignment/<db_name>/<chrom>/<gene>", methods=['GET'])
def get_aln(db_name, chrom, gene):
"""
Get fasta alignment from gene
"""
man = getManager(db_name)
if man is None:
print "no such manager"
abort(404)
if chrom not in man.getChroms():
abort(404)
genes = get_genes_raw(man, chrom)
if genes is None:
print "genes is none"
abort(404)
if len(genes) == 0:
print "no genes"
abort(404)
if gene not in genes:
print "gene",gene,"not in genes"#,genes
abort(404)
aln = get_aln_raw(man, chrom, gene)
return jsonify( {'chrom': chrom, 'gene': gene, 'alignment': aln } )
@app.route("/api/matrix/<db_name>/<chrom>/<gene>", methods=['GET'])
def get_matrix(db_name, chrom, gene):
"""
Ger distance matrix from gene
"""
man = getManager(db_name)
if man is None:
print "no such manager"
abort(404)
if chrom not in man.getChroms():
print "chrom",chrom,"not in chroms"
abort(404)
genes = get_genes_raw(man, chrom)
if genes is None:
print "genes is none"
abort(404)
if gene not in genes:
print "gene",gene,"not in genes"#,genes
abort(404)
matrix = get_matrix_raw(man, chrom, gene)
if matrix is None:
print "no matrix"
abort(404)
return jsonify( {'chrom': chrom, 'gene': gene, 'matrix': matrix } )
@app.route("/api/report/<db_name>/<chrom>/<gene>", methods=['GET'])
def get_report(db_name, chrom, gene):
"""
Get full report for gene
"""
man = getManager(db_name)
if man is None:
print "no such manager"
abort(404)
if chrom not in man.getChroms():
print "chromosome",chrom,"not in chroms"
abort(404)
genes = get_genes_raw(man, chrom)
if genes is None:
print "no genes"
abort(404)
if gene not in genes:
print "gene",gene,"not in genes"#,genes
abort(404)
#print "getting report", db_name, chrom, gene
res = get_report_raw(db_name, man, chrom, gene)
#print "got report", res
if res is None:
print "no report"
abort(404)
return jsonify( res )
@app.route("/api/clusterlist/<db_name>", methods=['GET'])
def get_cluster_list(db_name):
man = getManager(db_name)
if man is None:
print "no such manager"
abort(404)
clusterlist = get_cluster_list_raw(man)
appendClusterList( man, clusterlist )
return jsonify(clusterlist)
@app.route("/api/cluster/<db_name>/<ref>/<chrom>", methods=['GET'])
def get_cluster(db_name, ref, chrom):
"""
Get clustering information
"""
man = getManager(db_name)
if man is None:
print "no such manager"
abort(404)
ref = urllib.unquote(ref)
cluster = get_cluster_raw(man, ref, chrom)
#print cluster
#if cluster is None:
# clusters = get_clusters_raw(man)
# if clusters is not None:
# if chrom in clusters:
# cluster = clusters[ chrom ]
if cluster is None:
print "no cluster information"
abort(404)
if len(cluster) is None:
print "no clusters"
abort(404)
png = 'png' in request.args
svg = 'svg' in request.args
rows = 'rows' in request.args
cols = 'cols' in request.args
lst = 'lst' in request.args
if png or svg:
print 'png or svg'
data = cluster['clusters']
#print 'png or svg', data
if data is None:
print "no data"
abort(404)
fmt = 'svg'
cna = 'Svg'
mtype = 'image/svg+xml'
if png:
fmt = 'png'
cna = 'Png'
mtype = 'image/png'
print 'png or svg: fmt:',fmt,"cna",cna,"mtype",mtype
rc = None
fname = None
if rows:
rc = 'rows'
fname = db_name+'_'+ref+'_'+chrom+'_'+rc+'.'+fmt
elif cols:
rc = 'cols'
fname = db_name+'_'+ref+'_'+chrom+'_'+rc+'.'+fmt
print 'png or svg: fmt:',fmt,"cna",cna,"mtype",mtype,"rc",rc,"fname",fname
if rc is not None:
print "png or svg: rc",rc
cna = rc + cna
if rc not in data:
print rc,"not in data"
abort(404)
if cna not in data[rc]:
print cna,"not in data",rc
abort(404)
rdata = data[rc][cna]
if rdata is None:
print "no such data"
abort(404)
return send_file(io.BytesIO( rdata ), mimetype=mtype, as_attachment=False, attachment_filename=fname)
else:
print 'png or svg: PNG ALL'
res = {}
for rc in ['rows', 'cols']:
if rc not in data:
print rc,"not in data"
abort(404)
rcName = rc + cna
print 'png or svg:', rc, rcName
if rcName not in data[ rc ]:
print "no rcname", rcName
abort(404)
rdata = data[ rc ][ rcName ]
if rdata is None:
print "no such data"
abort(404)
res[rc] = base64.standard_b64encode( rdata )
return jsonify(res)
elif lst:
data = cluster['clusters']
filterClusters(data, "DEL")
return jsonify(data)
else:
data = cluster['clusters']
filterClusters(data, "B64")
return jsonify(data)
@app.route("/api/data/<db_name>/<ref>/<chrom>", methods=['GET'])
def get_data(db_name, ref, chrom):
print "get data", db_name, ref, chrom
man = getManager( db_name )
if man is None:
print "no such manager"
abort(404)
ref = urllib.unquote(urllib.unquote(urllib.unquote(ref)))
print "get data", db_name, ref, chrom
data = check_get_data(man, ref, chrom, request)
if data is None:
print "no data"
abort(404)
(ref, chrom, startPos, endPos, group_every, num_classes, evenly, maxNum, page) = data
table = get_data_raw(man, ref, chrom, startPos, endPos, group_every, num_classes, evenly, maxNum=maxNum, page=page)
if table is None:
print "no table"
abort(404)
print "sending table"
return jsonify(table)
@app.route("/api/mtime/<db_name>", methods=['GET'])
def get_mtime(db_name):
if db_name not in app.config["DATABASEINV"]:
abort(404)
return jsonify( { 'mtime': app.config["DATABASES"][ app.config["DATABASEINV"][db_name] ][ DATABASES_MTIME ] } )
@app.route("/api/maxnumcol", methods=['GET'])
def get_max_num_col():
return jsonify({'maxnumcol': MAX_NUMBER_OF_COLUMNS})
@app.route("/api/dbs", methods=['GET'])
def get_dbs():
return jsonify( { 'databases': app.config["DATABASEINV"].keys() } )
def get_spps_raw( man ):
"""
Retrieve list of species from interface
"""
sppsinv = man.getSppIndexInvert()
return sppsinv
def get_chroms_raw( man ):
"""
Retrieve list of chromosomes from interface
"""
return sorted( man.getChroms() )
def get_genes_raw(man, chrom):
"""
Retrieve list of genes from interface
"""
genes = man.getGenes( chrom )
return genes
def get_tree_raw(man, chrom, gene):
"""
Retriece phylogenetic tree from interface
"""
tree = man.getTree( gene, chrom )
return tree
def get_aln_raw(man, chrom, gene):
"""
Retrieve fasta alignment for gene from interface
"""
aln = man.getAlignment( gene, chrom )
return aln
def get_matrix_raw(man, chrom, gene):
"""
Retrieve distance matrix for gene from interface
"""
matrix = man.getMatrix( gene, chrom )
return matrix
def get_report_raw(db_name, man, chrom, gene):
"""
Retrieve all information for gene from interface
"""
dic = man.getRegisterDict( gene, chrom )
#print "got report dic", dic
dic['db_name'] = db_name
dic['chrom' ] = chrom
dic['gene' ] = gene
try:
dic['spps' ] = get_spps_raw( man )
except:
print "no spps"
abort(404)
try:
dic['TREE' ]['png'] = base64.standard_b64encode( dic['TREE' ]['png'] )