forked from kristallizer/metpetdb_interface
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
720 lines (606 loc) · 30.7 KB
/
app.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
import ast
import StringIO
import base64
from urllib import urlencode
from requests import get, post
import json
from itsdangerous import URLSafeTimedSerializer
from flask import Flask, request, render_template, url_for, redirect, flash, \
session
from flask_mail import Mail, Message
import dotenv
from getenv import env
import drest
from api import MetpetAPI
from forms import LoginForm, RequestPasswordResetForm, PasswordResetForm
from utilities import paginate_model
app = Flask(__name__)
app.config.from_object('config')
mail = Mail(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search/')
def search():
print "REQ ARGS"
print request.args
email = session.get('email', None)
api_key = session.get('api_key', None)
api = MetpetAPI(email, api_key).api
filters = dict(request.args)
filter_dictionary = {}
for key in filters:
if filters[key][0]:
if key != "resource":
filter_dictionary[key] = ",".join(filters[key])
#If View Samples selected
if request.args.get('resource') == 'sample':
#If minerals are selected, check for AND/OR
#If AND, get samples with filters
#If OR, union samples with mineral and samples with other filters
if request.args.getlist('minerals__in'):
#MINERAL AND
if (request.args.get('mineralandor') == 'or'):
url = url_for('samples') + '?' + urlencode(filter_dictionary)
return redirect(url)
#MINERAL OR
elif request.args.get('mineralandor') == 'and':
sample_results = []
for key in filter_dictionary:
if key != "minerals__in" and key != "search_filters" and key != "fields" and key != "mineralandor":
minerals = request.args.getlist('minerals__in')
for m in minerals:
samples = api.sample.get(params={key : filter_dictionary[key], 'minerals__in': m, 'fields': 'sample_id,user__name,collector,number,public_data,rock_type__rock_type,subsample_count,chem_analyses_count,image_count,minerals__name,collection_date', 'limit':0}).data['objects']
temp_list = [];
if not sample_results:
sample_results = samples
else:
#intersect sample_results and samples
for s in sample_results:
if s in samples:
temp_list.append(s)
sample_results = temp_list
#Build mineral list string for rendering results
for sample in sample_results:
mineral_names = [str(m) for m in sample['minerals__name']]
sample['mineral_list'] = (', ').join(mineral_names)
#Return data to samples template
return render_template('samples_mineral_and_samples.html', samples=sample_results)
#If no mineral, get samples with filters
else:
url = url_for('samples') + '?' + urlencode(filter_dictionary)
return redirect(url)
#If View Chemical Analyses selected
elif request.args.get('resource') == 'chemicalanalysis':
#If minerals are selected
if request.args.getlist('minerals__in'):
#MINERAL OR
if (request.args.get('mineralandor') == 'or'):
request_obj = drest.api.API(baseurl=env('API_HOST'))
if email and api_key:
headers = {'email': email, 'api_key': api_key}
else:
headers = None
response = request_obj.\
make_request('GET',
'/get-chem-analyses-given-sample-filters/',
params=filter_dictionary,
headers=headers)
ids = response.data['chemical_analysis_ids']
url = url_for('chemical_analyses') + '?' + \
urlencode({'chemical_analysis_id__in': ids})
return redirect(url)
#MINERAL AND
else:
#Get sample IDs
sample_results = []
for key in filter_dictionary:
if key != "minerals__in" and key != "search_filters" and key != "fields" and key != "mineralandor":
minerals = request.args.getlist('minerals__in')
for m in minerals:
samples = api.sample.get(params={key : filter_dictionary[key], 'minerals__in': m, 'fields': 'sample_id', 'limit':0}).data['objects']
temp_list = [];
if not sample_results:
sample_results = samples
else:
#intersect sample_results and samples
for s in sample_results:
if s in samples:
temp_list.append(s)
sample_results = temp_list
sample_resources = ((',').join(str(s['sample_id']) for s in sample_results))
#print sample_resources
#Get subsample IDs using sample IDs
subsamples = api.subsample.get(params={'sample__in': sample_resources, 'fields': 'subsample_id', 'limit':0}).data['objects']
#print subsamples
#subsample_resources = subsamples = api.subsample.get().data['objects'];
#print "SUBSAMPLE RESOURCES"
subsample_resources = ((',').join(str(s['subsample_id']) for s in subsamples))
#print subsample_resources
#print len(subsample_resources)
##chemical_analyses_results = api.chemical_analysis.get(params={'subsample_subsample__in': subsample_resources}).data['objects']
#Get chemical analyses using subsample IDs
chemical_analyses_results = api.chemical_analysis.get(params={'subsample__in': subsample_resources, 'fields': 'chemical_analysis_id,spot_id,public_data,analysis_method,where_done,analyst,analysis_date,reference_x,reference_y,total,mineral', 'limit': 0}).data['objects']
#,mineral__name,reference_x,reference_y,total
#,public_data,analysis_method,mineral__name,where_done,reference_x,reference_y,total
print chemical_analyses_results
return render_template('samples_mineral_and_chemical_analyses.html', chemical_analyses=chemical_analyses_results)
return "CHEM ANALYSIS RESULTS"
#If no minerals, get chemical analyses with get-chem-analyses-given-sample-filters
else:
request_obj = drest.api.API(baseurl=env('API_HOST'))
if email and api_key:
headers = {'email': email, 'api_key': api_key}
else:
headers = None
response = request_obj.\
make_request('GET',
'/get-chem-analyses-given-sample-filters/',
params=filter_dictionary,
headers=headers)
ids = response.data['chemical_analysis_ids']
url = url_for('chemical_analyses') + '?' + \
urlencode({'chemical_analysis_id__in': ids})
return redirect(url)
owner_list = []
region_list = []
rock_type_list = []
collector_list = []
country_list = []
reference_list = []
number_list = []
igsn_list = []
metamorphic_region_list = []
metamorphic_grade_list = []
element_list = []
oxide_list = []
oxides = api.oxide.get(params={'limit': 0}).data['objects']
elements = api.element.get(params={'limit': 0}).data['objects']
rock_types = api.rock_type.get(params={'order_by': 'rock_type', 'limit': 0}).data['objects']
regions = api.region.get(params={'order_by': 'name', 'limit': 0}).data['objects']
references = api.reference.get(params={'order_by': 'name', 'limit': 0}).data['objects']
metamorphic_regions = api.metamorphic_region.get(params={'order_by': 'name', 'limit': 0}).data['objects']
metamorphic_grades = api.metamorphic_grade.get(params={'limit': 0}).data['objects']
samples = api.sample.get(params={'fields': 'user__user_id,user__name,collector,number,sesar_number,country,public_data',
'limit': 0}).data['objects']
mineral_relationships = api.mineral_relationship.get(\
params={'limit': 0,
'fields':'parent_mineral__mineral_id,parent_mineral__name,child_mineral__mineral_id,child_mineral__name'}).\
data['objects']
mineralroots = []
parents = set()
children = set()
for m in mineral_relationships:
parents.add((m['parent_mineral__name'], m['parent_mineral__mineral_id']))
children.add((m['child_mineral__name'], m['child_mineral__mineral_id']))
mineralroots = set(parents) - set(children)
m_list= []
mineral_list = []
m_list = parents.union(children)
for (name, mid) in m_list:
mineral_list.append({"name": name, "id": mid})
mineralnodes = []
for (name, mid) in mineralroots:
mineralnodes.append({"id": name, "parent": "#", "text": name, "mineral_id": mid})
for m in mineral_relationships:
node = {"id": m['child_mineral__name'], "parent": m['parent_mineral__name'], "text": m['child_mineral__name'], "mineral_id": m['child_mineral__mineral_id']}
mineralnodes.append(node)
for element in elements:
element_list.append(element)
for oxide in oxides:
oxide_list.append(oxide)
for region in regions:
region_list.append(region['name'])
for rock_type in rock_type_list:
rock_type_list.append(rock_type['name'])
for ref in references:
reference_list.append(ref['name'])
for mmr in metamorphic_regions:
metamorphic_region_list.append(mmr['name'])
for mmg in metamorphic_grades:
metamorphic_grade_list.append(mmg['name'])
owner_dict = {}
if email:
logged_in_user = api.user.get(params={'email': email,
'fields': 'user_id,name'}).data['objects']
owner_dict[logged_in_user[0]['user_id']] = logged_in_user[0]['name']
for sample in samples:
collector_list.append(unicode(sample['collector']))
number_list.append(sample['number'])
igsn_list.append(sample['sesar_number'])
country_list.append(sample['country'])
"""The 'owners' list in the Provenance tab should contain only users
with public samples"""
if sample['public_data'] == 'Y':
if not sample['user__user_id'] in owner_dict:
owner_dict[sample['user__user_id']] = sample['user__name']
collector_list = list (set ( collector_list ))
country_list = list(set (country_list))
return render_template('search_form.html',
query='',
elements=element_list,
oxides=oxide_list,
regions=region_list,
mineralrelationships=json.dumps(mineral_relationships),
mineral_nodes=json.dumps(mineralnodes),
minerals=mineral_list,
rock_types=rock_types,
provenances=collector_list,
references=reference_list,
numbers=number_list,
igsns=igsn_list,
countries=country_list,
owners = owner_dict,
metamorphic_regions=metamorphic_region_list,
metamorphic_grades=metamorphic_grade_list)
@app.route('/search-chemistry/')
def search_chemistry():
print "REQ ARGS"
print request.args
email = session.get('email', None)
api_key = session.get('api_key', None)
api = MetpetAPI(email, api_key).api
filters = dict(request.args)
filter_dictionary = {}
for key in filters:
if filters[key][0]:
if key != "resource":
filter_dictionary[key] = ",".join(filters[key])
#Check resource
print "RESOURCE IS "
print request.args.get('resource')
#If chem analysis data is passed, return results
if request.args :
if 'squirrel' not in request.args and request.args.get('resource') == 'chemicalanalysis':
return render_template('chem_search_chemical_analyses.html', can=request.args.get("results"))
elif 'squirrel' not in request.args and request.args.get('resource') == 'sample':
return render_template('chem_search_samples.html', samples=request.args.get("results"))
#url = url_for('chem_search_chemical_analyses') + '?' + \
# urlencode({'chemical_analyses': request.args.get("chemical_analyses")})
#return redirect(url)
#If chemistry row data is passed, get (M, E1) / (M, O1)
if request.args.get('squirrel') == 'squirrel':
if 'elements__element_id__in' in request.args:
element = request.args.get('elements__element_id__in')
elif 'oxides__oxide_id__in' in request.args:
oxide = request.args.get('oxides__oxide_id__in')
mineral_ids = (',').join(request.args.getlist('minerals__in'))
cid_list = []
#Get chemical analyses for (E, M)
if 'elements__element_id__in' in request.args and request.args.get('resource') == 'chemicalanalysis':
e_chem_analysis_ids = api.chemical_analysis.get(params={'elements__element_id__in': element, 'minerals__in': mineral_ids, 'fields': 'chemical_analysis_id,spot_id,public_data,analysis_method,mineral__name,where_done,analyst,analysis_date,reference_x,reference_y,total,chemical_analysis_id', 'limit': 0}).data['objects']
for cid in e_chem_analysis_ids:
cid_list.append(cid)
return json.dumps(cid_list)
#Get chemical analyses for (O, M)
elif 'oxides__oxide_id__in' in request.args and request.args.get('resource') == 'chemicalanalysis':
o_chem_analysis_ids = api.chemical_analysis.get(params={'oxides__oxide_id__in': oxide, 'minerals__in': mineral_ids, 'fields': 'chemical_analysis_id,spot_id,public_data,analysis_method,mineral__name,where_done,analyst,analysis_date,reference_x,reference_y,total,chemical_analysis_id', 'limit': 0}).data['objects']
for cid in o_chem_analysis_ids:
cid_list.append(cid)
return json.dumps(cid_list)
#Get samples for (E, M)
elif 'elements__element_id__in' in request.args and request.args.get('resource') == 'sample':
subsample_resources = api.chemical_analysis.get(params={'elements__element_id__in': element, 'minerals__in': mineral_ids, 'fields': 'subsample', 'limit': 0}).data['objects']
subsample_ids = set()
for s in subsample_resources:
#Remove first 18 characters and trailing /
subsample_id = s['subsample'].replace("Subsample #", "")
subsample_ids.add(subsample_id)
print subsample_ids
sample_resources = api.subsample.get(params={'subsample_id__in': (',').join(str(s) for s in subsample_ids), 'fields': 'sample', 'limit':0}).data['objects']
sample_ids = set()
for s in sample_resources:
#Remove first 18 characters and trailing /
sample_id = s['sample'].replace("Sample #", "")
sample_ids.add(sample_id)
print sample_ids
sample_results = api.sample.get(params={'sample_id__in': (',').join(str(s) for s in sample_ids), 'fields': 'sample_id,user__name,collector,number,public_data,rock_type__rock_type,subsample_count,chem_analyses_count,image_count,minerals__name,collection_date', 'limit':0}).data['objects']
print "S RESULTS"
print sample_results
return json.dumps(sample_results)
#Get samples for (O, M)
elif 'oxides__oxide_id__in' in request.args and request.args.get('resource') == 'sample':
subsample_resources = api.chemical_analysis.get(params={'oxides__oxide_id__in': oxide, 'minerals__in': mineral_ids, 'fields': 'subsample', 'limit': 0}).data['objects']
subsample_ids = set()
for s in subsample_resources:
#Remove first 18 characters and trailing /
subsample_id = s['subsample'].replace("Subsample #", "")
subsample_ids.add(subsample_id)
print subsample_ids
sample_resources = api.subsample.get(params={'subsample_id__in': (',').join(str(s) for s in subsample_ids), 'fields': 'sample', 'limit':0}).data['objects']
sample_ids = set()
for s in sample_resources:
#Remove first 18 characters and trailing /
sample_id = s['sample'].replace("Sample #", "")
sample_ids.add(sample_id)
print sample_ids
sample_results = api.sample.get(params={'sample_id__in': (',').join(str(s) for s in sample_ids), 'fields': 'sample_id,user__name,collector,number,public_data,rock_type__rock_type,subsample_count,chem_analyses_count,image_count,minerals__name,collection_date', 'limit':0}).data['objects']
print "S RESULTS"
print sample_results
return json.dumps(sample_results)
owner_list = []
region_list = []
rock_type_list = []
collector_list = []
country_list = []
reference_list = []
number_list = []
igsn_list = []
metamorphic_region_list = []
metamorphic_grade_list = []
element_list = []
oxide_list = []
oxides = api.oxide.get(params={'limit': 0}).data['objects']
elements = api.element.get(params={'limit': 0}).data['objects']
rock_types = api.rock_type.get(params={'order_by': 'rock_type', 'limit': 0}).data['objects']
regions = api.region.get(params={'order_by': 'name', 'limit': 0}).data['objects']
references = api.reference.get(params={'order_by': 'name', 'limit': 0}).data['objects']
metamorphic_regions = api.metamorphic_region.get(params={'order_by': 'name', 'limit': 0}).data['objects']
metamorphic_grades = api.metamorphic_grade.get(params={'limit': 0}).data['objects']
samples = api.sample.get(params={'fields': 'user__user_id,user__name,collector,number,sesar_number,country,public_data',
'limit': 0}).data['objects']
mineral_relationships = api.mineral_relationship.get(\
params={'limit': 0,
'fields':'parent_mineral__mineral_id,parent_mineral__name,child_mineral__mineral_id,child_mineral__name'}).\
data['objects']
mineralroots = []
parents = set()
children = set()
for m in mineral_relationships:
parents.add((m['parent_mineral__name'], m['parent_mineral__mineral_id']))
children.add((m['child_mineral__name'], m['child_mineral__mineral_id']))
mineralroots = set(parents) - set(children)
m_list= []
mineral_list = []
m_list = parents.union(children)
for (name, mid) in m_list:
mineral_list.append({"name": name, "id": mid})
mineralnodes = []
mineralnodes.append({"id": "Minerals", "parent" : "#", "text": "Minerals"})
for (name, mid) in mineralroots:
mineralnodes.append({"id": name, "parent": "Minerals", "text": name, "mineral_id": mid})
for m in mineral_relationships:
node = {"id": m['child_mineral__name'], "parent": m['parent_mineral__name'], "text": m['child_mineral__name'], "mineral_id": m['child_mineral__mineral_id']}
mineralnodes.append(node)
for element in elements:
element_list.append(element)
for oxide in oxides:
oxide_list.append(oxide)
for region in regions:
region_list.append(region['name'])
for rock_type in rock_type_list:
rock_type_list.append(rock_type['name'])
for ref in references:
reference_list.append(ref['name'])
for mmr in metamorphic_regions:
metamorphic_region_list.append(mmr['name'])
for mmg in metamorphic_grades:
metamorphic_grade_list.append(mmg['name'])
owner_dict = {}
if email:
logged_in_user = api.user.get(params={'email': email,
'fields': 'user_id,name'}).data['objects']
owner_dict[logged_in_user[0]['user_id']] = logged_in_user[0]['name']
for sample in samples:
collector_list.append(unicode(sample['collector']))
number_list.append(sample['number'])
igsn_list.append(sample['sesar_number'])
country_list.append(sample['country'])
"""The 'owners' list in the Provenance tab should contain only users
with public samples"""
if sample['public_data'] == 'Y':
if not sample['user__user_id'] in owner_dict:
owner_dict[sample['user__user_id']] = sample['user__name']
collector_list = list (set ( collector_list ))
country_list = list(set (country_list))
return render_template('chemical_search_form.html',
query='',
elements=element_list,
oxides=oxide_list,
regions=region_list,
mineralrelationships=json.dumps(mineral_relationships),
minerals=mineral_list,
mineral_nodes=json.dumps(mineralnodes),
rock_types=rock_types,
provenances=collector_list,
references=reference_list,
numbers=number_list,
igsns=igsn_list,
countries=country_list,
owners = owner_dict,
metamorphic_regions=metamorphic_region_list,
metamorphic_grades=metamorphic_grade_list)
@app.route('/login', methods=['GET', 'POST'])
def login():
if session.get('api_key'):
return redirect(url_for('search'))
form = LoginForm()
if form.validate_on_submit():
payload = {'email': form.email.data,
'password': form.password.data}
response = post(env('API_HOST') + '/authenticate/', data=payload)
if response.status_code == 200:
data = json.loads(response.text)
session['email'] = data['email']
session['api_key'] = data['api_key']
flash('Login successful!')
return redirect(url_for('search'))
else:
flash('Authentication failed. Please try again.')
return render_template('login.html',
form=form)
@app.route('/logout')
def logout():
session.pop('email', None)
session.pop('api_key', None)
flash('Logout successful.')
return redirect(url_for('search'))
@app.route('/request-password-reset', methods=['GET', 'POST'])
def request_reset_password():
form = RequestPasswordResetForm()
if form.validate_on_submit():
payload = {'email': form.email.data}
response = post(env('API_HOST') + '/reset-password/', data=payload)
if response.status_code == 200:
data = json.loads(response.text)
message = Message("Metpetdb: Reset Password",
sender=env('DEFAULT_MAIL_SENDER'),
recipients=[form.email.data])
reset_url = url_for('reset_password', token=data['reset_token'],
_external=True)
message.body = render_template('reset_password_email.html',
reset_url=reset_url)
mail.send(message)
flash('Please check your email for a link to reset your password')
return redirect(url_for('login'))
else:
flash("Invalid email. Please try again.")
return render_template('request_password_reset.html', form=form)
@app.route('/reset-password/<string:token>', methods=['GET', 'POST'])
def reset_password(token):
form = PasswordResetForm()
if form.validate_on_submit():
payload = {'token': form.token.data,
'password': form.password.data}
response = post(env('API_HOST') + '/reset-password/', data=payload)
if response.status_code == 200:
data = json.loads(response.text)
session['email'] = data['email']
session['api_key'] = data['api_key']
flash('Password reset successful!')
return redirect(url_for('search'))
else:
flash('Password reset failed. Please try again.')
return redirect(url_for('request_reset_password'))
if token:
response = get(env('API_HOST') + '/reset-password/' + token)
if response.status_code == 200:
form = PasswordResetForm(token=token)
return render_template('reset_password.html', form=form)
flash('Password reset failed. Please try again.')
return redirect(url_for('request_reset_password'))
@app.route('/samples/')
def samples():
email = session.get('email', None)
api_key = session.get('api_key', None)
api = MetpetAPI(email, api_key).api
filters = ast.literal_eval(json.dumps(request.args))
offset = request.args.get('offset', 0)
filters['offset'] = offset
data = api.sample.get(params=filters)
next, previous, last, total_count = paginate_model('samples', data, filters)
samples = data.data['objects']
for sample in samples:
mineral_names = [str(m) for m in sample['minerals__name']]
sample['mineral_list'] = (', ').join(mineral_names)
if 'minerals' in samples:
mineral_names = [mineral['name'] for mineral in sample['minerals']]
sample['mineral_list'] = (', ').join(mineral_names)
first_page_filters = filters
del first_page_filters['offset']
if filters:
first_page_url = url_for('samples') + '?' + urlencode(first_page_filters)
else:
first_page_url = url_for('samples') + urlencode(first_page_filters)
return render_template('samples.html',
samples=samples,
next_url=next,
prev_url=previous,
total=total_count,
first_page=first_page_url,
last_page=last)
@app.route('/sample/<int:id>')
def sample(id):
email = session.get('email', None)
api_key = session.get('api_key', None)
api = MetpetAPI(email, api_key).api
sample = api.sample.get(id).data
location = sample['location'].split(" ")
longtitude = location[1].replace("(","")
latitude = location[2].replace(")","")
loc = [longtitude, latitude]
filter = {"sample__sample_id": sample['sample_id'], "limit": "0"}
subsamples = api.subsample.get(params=filter).data['objects']
aliases = api.sample_alias.get(params=filter).data['objects']
aliases_str = [alias['alias'] for alias in aliases]
regions = [region['name'] for region in sample['regions']]
metamorphic_regions = [metamorphic_region['name'] for metamorphic_region in sample['metamorphic_regions']]
metamorphic_grades = [metamorphic_grade['name'] for metamorphic_grade in sample['metamorphic_grades']]
references = [reference['name'] for reference in sample['references']]
minerals = [mineral['name'] for mineral in sample['minerals']]
if sample:
return render_template('sample.html',
sample=sample,
location=loc,
minerals=(', ').join(minerals),
regions=(', ').join(regions),
references=(', ').join(references),
metamorphic_grades=(', ').join(metamorphic_grades),
metamorphic_regions=(', ').join(metamorphic_regions),
aliases=(', ').join(aliases_str),
subsamples=subsamples)
else:
return HttpResponse("Sample does not Exist")
@app.route('/subsample/<int:id>')
def subsample(id):
email = session.get('email', None)
api_key = session.get('api_key', None)
api = MetpetAPI(email, api_key).api
subsample = api.subsample.get(id).data
user = api.user.get(subsample['user']['user_id']).data
filter = {"subsample__subsample_id": subsample['subsample_id'],
"limit": "0"}
chemical_analyses = api.chemical_analysis.get(params=filter).data['objects']
if subsample:
return render_template('subsample.html',
subsample=subsample,
user=user,
chemical_analyses=chemical_analyses,
sample_id=subsample['sample'].split('/')[-2])
else:
return HttpResponse("Subsample does not Exist")
@app.route('/chemical_analyses/')
def chemical_analyses():
email = session.get('email', None)
api_key = session.get('api_key', None)
api = MetpetAPI(email, api_key).api
filters = ast.literal_eval(json.dumps(request.args))
offset = request.args.get('offset', 0)
filters['offset'] = offset
data = api.chemical_analysis.get(params=filters)
next, previous, last, total_count = paginate_model('chemical_analyses',
data, filters)
chemical_analyses = data.data['objects']
first_page_filters = filters
del first_page_filters['offset']
if filters:
first_page_url = url_for('chemical_analyses') + '?' + urlencode(first_page_filters)
else:
first_page_url = url_for('chemical_analyses') + urlencode(first_page_filters)
return render_template('chemical_analyses.html',
chemical_analyses=chemical_analyses,
next_url=next,
prev_url=previous,
total=total_count,
first_page=first_page_url,
last_page=last)
@app.route('/chemical_analysis/<int:id>')
def chemical_analysis(id):
email = session.get('email', None)
api_key = session.get('api_key', None)
payload = {'email': email, 'api_key': api_key}
url = env('API_HOST') + '/chemical_analysis/{0}'.format(id)
response = get(url, params=payload)
return render_template('chemical_analysis.html',
data=response.json())
@app.route('/user/<int:id>')
def user(id):
api = MetpetAPI(None, None).api
user = api.user.get(id).data
if sample:
return render_template('user.html', user=user)
else:
return HttpResponse("User does not Exist")
if __name__ == '__main__':
dotenv.read_dotenv('../app_variables.env')
app.run(debug=True)