forked from opencitations/ramose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ramose.py
1627 lines (1375 loc) · 66.8 KB
/
ramose.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2020
# Silvio Peroni <essepuntato@gmail.com>
# Marilena Daquino <marilena.daquino2@unibo.it>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
# OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
# DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE.
__author__ = 'essepuntato'
from abc import abstractmethod
from re import search, DOTALL, findall, sub, match, split
from requests import get, post, put, delete
from csv import DictReader, reader, writer
from json import dumps
from io import StringIO
from sys import exc_info, maxsize, path
from collections import OrderedDict
from markdown import markdown
from importlib import import_module
from urllib.parse import parse_qs, urlsplit, quote , unquote
from operator import add, itemgetter, gt, eq, lt
from dateutil.parser import parse
from datetime import datetime
from isodate import parse_duration
from argparse import ArgumentParser
from os.path import abspath, dirname, basename
from os import path as pt
import logging
from os import sep, getcwd
import logging
from flask import Flask, request , make_response, send_from_directory
from werkzeug.exceptions import HTTPException
FIELD_TYPE_RE = "([^\(\s]+)\(([^\)]+)\)"
PARAM_NAME = "{([^{}\(\)]+)}"
class HashFormatHandler(object):
"""This class creates an object capable to read files stored in Hash Format (see
https://github.com/opencitations/ramose#Hashformat-configuration-file). A Hash Format
file (.hf) is a specification file that includes information structured using the following
syntax:
```
#<field_name_1> <field_value_1>
#<field_name_1> <field_value_2>
#<field_name_3> <field_value_3>
[...]
#<field_name_n> <field_value_n>
```"""
def read(self, file_path):
"""This method takes in input a path of a file containing a document specified in
Hash Format, and returns its representation as list of dictionaries."""
result = []
with open(file_path, "r", newline=None, encoding = 'utf8') as f:
first_field_name = None
cur_object = None
cur_field_name = None
cur_field_content = None
for line in f.readlines():
cur_matching = search("^#([^\s]+)\s(.+)$", line, DOTALL)
if cur_matching is not None:
cur_field_name = cur_matching.group(1)
cur_field_content = cur_matching.group(2)
# If both the name and the content are defined, continue to process
if cur_field_name and cur_field_content:
# Identify the separator key
if first_field_name is None:
first_field_name = cur_field_name
# If the current field is equal to the separator key,
# then create a new object
if cur_field_name == first_field_name:
# If there is an already defined object, add it to the
# final result
if cur_object is not None:
result.append(cur_object)
cur_object = {}
# Add the new key to the object
cur_object[cur_field_name] = cur_field_content
elif cur_object is not None and len(cur_object) > 0:
cur_object[cur_field_name] += line
# Insert the last object in the result
if cur_object is not None and len(cur_object) > 0:
result.append(cur_object)
# Clean the final \n
for item in result:
for key in item:
item[key] = item[key].rstrip()
return result
class DocumentationHandler(object):
def __init__(self, api_manager):
"""This class provides the main structure for returning a human-readable documentation of all
the operations described in the configuration files handled by the APIManager specified as input."""
self.conf_doc = api_manager.all_conf
@abstractmethod
def get_documentation(self, *args, **dargs):
"""An abstract method that returns a string defining the human-readable documentation of the operations
available in the input APIManager."""
pass
@abstractmethod
def store_documentation(self, file_path, *args, **dargs):
"""An abstract method that store in the input file path (parameter 'file_path') the human-readable
documentation of the operations available in the input APIManager."""
pass
@abstractmethod
def get_index(self, *args, **dargs):
"""An abstract method that returns a string defining the index of all the various configuration files
handled by the input APIManager."""
pass
class HTMLDocumentationHandler(DocumentationHandler):
# HTML documentation: START
def __title(self, conf):
"""This method returns the title string defined in the API specification."""
return conf["conf_json"][0]["title"]
def __sidebar(self, conf):
"""This method builds the sidebar of the API documentation"""
result = ""
i = conf["conf_json"][0]
result += """
<h4>%s</h4>
<ul id="sidebar_menu" class="sidebar_menu">
<li><a class="btn active" href="#description">DESCRIPTION</a></li>
<li><a class="btn" href="#parameters">PARAMETERS</a></li>
<li><a class="btn" href="#operations">OPERATIONS</a>
<ul class="sidebar_submenu">%s</ul>
</li>
<li><a class="btn active" href="/">HOME</a></li>
</ul>
""" % \
(i["title"], "".join(["<li><a class='btn' href='#%s'>%s</a></li>" % (op["url"], op["url"])
for op in conf["conf_json"][1:]]))
return result
def __header(self, conf):
"""This method builds the header of the API documentation"""
result = ""
i = conf["conf_json"][0]
result += """
<a id='toc'></a>
# %s
**Version:** %s <br/>
**API URL:** <a href="%s">%s</a><br/>
**Contact:** %s<br/>
**License:** %s<br/>
## <a id="description"></a>Description [back to top](#toc)
%s
%s""" % \
(i["title"], i["version"], i["base"] + i["url"], i["base"] + i["url"], i["contacts"], i["license"],
i["description"], self.__parameters())
# (i["title"], i["version"], i["base"] + i["url"], i["base"] + i["url"], i["contacts"], i["contacts"], i["license"],
# "".join(["<li>[%s](#%s): %s</li>" % (op["url"], op["url"], op["description"].split("\n")[0])
# for op in self.conf_json[1:]]),
# i["description"], self.__parameters())
return markdown(result)
def __parameters(self):
result = """## <a id="parameters"></a>Parameters [back to top](#toc)
Parameters can be used to filter and control the results returned by the API. They are passed as normal HTTP parameters in the URL of the call. They are:
1. `require=<field_name>`: all the rows that have an empty value in the `<field_name>` specified are removed from the result set - e.g. `require=given_name` removes all the rows that do not have any string specified in the `given_name` field.
2. `filter=<field_name>:<operator><value>`: only the rows compliant with `<value>` are kept in the result set. The parameter `<operation>` is not mandatory. If `<operation>` is not specified, `<value>` is interpreted as a regular expression, otherwise it is compared by means of the specified operation. Possible operators are "=", "<", and ">". For instance, `filter=title:semantics?` returns all the rows that contain the string "semantic" or "semantics" in the field `title`, while `filter=date:>2016-05` returns all the rows that have a `date` greater than May 2016.
3. `sort=<order>(<field_name>)`: sort in ascending (`<order>` set to "asc") or descending (`<order>` set to "desc") order the rows in the result set according to the values in `<field_name>`. For instance, `sort=desc(date)` sorts all the rows according to the value specified in the field `date` in descending order.
4. `format=<format_type>`: the final table is returned in the format specified in `<format_type>` that can be either "csv" or "json" - e.g. `format=csv` returns the final table in CSV format. This parameter has higher priority of the type specified through the "Accept" header of the request. Thus, if the header of a request to the API specifies `Accept: text/csv` and the URL of such request includes `format=json`, the final table is returned in JSON.
5. `json=<operation_type>("<separator>",<field>,<new_field_1>,<new_field_2>,...)`: in case a JSON format is requested in return, tranform each row of the final JSON table according to the rule specified. If `<operation_type>` is set to "array", the string value associated to the field name `<field>` is converted into an array by splitting the various textual parts by means of `<separator>`. For instance, considering the JSON table `[ { "names": "Doe, John; Doe, Jane" }, ... ]`, the execution of `array("; ",names)` returns `[ { "names": [ "Doe, John", "Doe, Jane" ], ... ]`. Instead, if `<operation_type>` is set to "dict", the string value associated to the field name `<field>` is converted into a dictionary by splitting the various textual parts by means of `<separator>` and by associating the new fields `<new_field_1>`, `<new_field_2>`, etc., to these new parts. For instance, considering the JSON table `[ { "name": "Doe, John" }, ... ]`, the execution of `dict(", ",name,fname,gname)` returns `[ { "name": { "fname": "Doe", "gname": "John" }, ... ]`.
It is possible to specify one or more filtering operation of the same kind (e.g. `require=given_name&require=family_name`). In addition, these filtering operations are applied in the order presented above - first all the `require` operation, then all the `filter` operations followed by all the `sort` operation, and finally the `format` and the `json` operation (if applicable). It is worth mentioning that each of the aforementioned rules is applied in order, and it works on the structure returned after the execution of the previous rule.
Example: `<api_operation_url>?require=doi&filter=date:>2015&sort=desc(date)`."""
return markdown(result)
def __operations(self, conf):
"""This method returns the description of all the operations defined in the API."""
result = """## Operations [back to top](#toc)
The operations that this API implements are:
"""
ops = "\n"
for op in conf["conf_json"][1:]:
params = []
for p in findall(PARAM_NAME, op["url"]):
p_type = "str"
p_shape = ".+"
if p in op:
p_type, p_shape = findall("^\s*([^\(]+)\((.+)\)\s*$", op[p])[0]
params.append("<em>%s</em>: type <em>%s</em>, regular expression shape <code>%s</code>" % (p, p_type, p_shape))
result += "\n* [%s](#%s): %s" % (op["url"], op["url"], op["description"].split("\n")[0])
ops += """<div id="%s">
<h3>%s <a href="#operations">back to operations</a></h3>
%s
<p class="attr"><strong>Accepted HTTP method(s)</strong> <span class="attr_val method">%s</span></p>
<p class="attr params"><strong>Parameter(s)</strong> <span class="attr_val">%s</span></p>
<p class="attr"><strong>Result fields type</strong><span class="attr_val">%s</span></p>
<p class="attr"><strong>Example</strong><span class="attr_val"><a target="_blank" href="%s">%s</a></span></p>
<p class="ex attr"><strong>Exemplar output (in JSON)</strong></p>
<pre><code>%s</code></pre></div>""" % (op["url"], op["url"], markdown(op["description"]),
", ".join(split("\s+", op["method"].strip())), "</li><li>".join(params),
", ".join(["%s <em>(%s)</em>" % (f, t) for t, f in
findall(FIELD_TYPE_RE, op["field_type"])]),
conf["website"] + conf["base_url"] + op["call"], op["call"], op["output_json"])
return markdown(result) + ops
def __footer(self):
"""This method returns the footer of the API documentation."""
result = """This API and the related documentation has been created with <a href="https://github.com/opencitations/ramose" target="_blank">RAMOSE</a>, the *Restful API Manager Over SPARQL Endpoints*, developed by <a href="http://orcid.org/0000-0003-0530-4305" target="_blank">Silvio Peroni</a> and <a href="https://marilenadaquino.github.io">Marilena Daquino</a>."""
return markdown(result)
def __css(self):
return """
@import url('https://fonts.googleapis.com/css2?family=Karla:wght@300;400&display=swap');
@media screen and (max-width: 850px) {
aside { display: none; }
main, #operations, .dashboard, body>footer {margin-left: 15% !important;}
#operations > ul:nth-of-type(1) li { display:block !important; max-width: 100% !important; }
h3 a[href] {display:block !important; float: none !important; font-size: 0.5em !important;}
a {overflow: hidden; text-overflow: ellipsis;}
.info_api, .api_calls {display: block !important; max-width: 100% !important;}
}
* {
font-family: 'Karla', Geneva, sans-serif;
}
body {
margin: 3% 15% 7% 0px;
line-height: 1.5em;
letter-spacing: 0.02em;
font-size : 1em;
font-weight:300;
color: #303030;
text-align: justify;
background-color: #edf0f2;
}
aside {
height : 100%;
width: 20%;
position: fixed;
z-index: 1;
top: 0;
left: 0;
/*background-color: #404040;*/
overflow-x: hidden;
background-color: white;
box-shadow:0px 10px 30px 0px rgba(133,66,189,0.1);
}
p strong {
text-transform: uppercase;
font-size: 0.9em;
}
aside h4 {
padding: 20px 9%;
margin: 0px !important;
color: #9931FC;
text-align: left !important;
}
.sidebar_menu , .sidebar_submenu {
list-style-type: none;
padding-left:0px !important;
margin-top: 10px;
}
.sidebar_menu > li {
padding: 2% 0px;
border-top : solid 0.7px grey;
}
.sidebar_menu a {
padding: 1% 9%;
background-image: none !important;
color: grey;
display: block;
}
.sidebar_menu a:hover {
border-left: solid 5px rgba(154, 49, 252,.5);
font-weight: 400;
}
.sidebar_submenu > li {
padding-left:0px !important;
background-color:#edf0f2;
font-size: 0.8em;
}
main , #operations , .dashboard, body>footer {
margin-left: 33%;
}
.dashboard {text-align: center;}
main h1+p , .info_api{
padding-left: 3%;
font-size: 0.9em;
line-height: 1.4em;
}
main h1+p {border-left: solid 5px rgba(154, 49, 252,.5);}
#operations h3 {
color: #9931FC;
margin-bottom: 0px;
padding: 10px;
}
#operations > ul:nth-of-type(1) {
padding-left: 0px !important;
text-align: center;
}
#operations > ul:nth-of-type(1) li {
background-color: white;
text-align: left;
display: inline-block;
overflow: hidden;
text-overflow: ellipsis;
max-width: 35%;
height: 200px;
padding:4%;
margin: 1% 2% 1% 0px;
border-radius: 10px;
box-shadow: 0px 10px 30px 0px rgba(133,66,189,0.1);
vertical-align:top;
}
#operations > div {
background-color: white;
margin-top: 20px;
padding: 2%;
border-radius: 18px;
box-shadow: 0px 10px 30px 0px rgba(133,66,189,0.1);
}
#operations > div > * {
padding: 0px 2%;
}
#operations > div ul, .params+ul{
list-style-type: none;
font-size: 0.85em;
}
#operations > div ul:nth-of-type(1) li, .params+ul li {
margin: 10px 0px;
}
#operations > div ul:nth-of-type(1) li em, .params+ul li em {
font-style: normal;
font-weight: 400;
color: #9931FC;
border-left: solid 2px #9931FC;
padding:5px;
}
.attr {
border-top: solid 1px rgba(133,66,189,0.1);
padding: 2% !important;
display:block;
vertical-align: top;
font-size: 0.8em;
text-align: left;
}
.attr strong {
width: 30%;
color: grey;
font-weight: 400;
font-style: normal;
display:inline-block;
vertical-align: top;
}
.attr_val {
max-width: 50%;
display:inline-table;
height: 100%;
vertical-align: top;
}
.method {
text-transform: uppercase;
}
.params {
margin-bottom: 0;
}
pre {
background-color: #f0f0f5;
padding: 10px;
margin-top: 0;
margin-bottom: 0;
border-radius: 0 0 14px 14px;
font-family: monospace !important;
overflow: scroll;
line-height: 1.2em;
height: 250px;
}
pre code {
font-family: monospace !important;
}
p.ex {
background-color: #f0f0f5;
margin-bottom: 0px;
padding-top: 5px;
padding-bottom: 5px;
}
h2:first-of-type {
margin-bottom: 15px;
}
ol:first-of-type {
margin-top: 0;
}
:not(pre) > code {
background-color: #f0f0f5;
color: #8585ad;
padding: 0 2px 0 2px;
border-radius: 3px;
font-family : monospace;
font-size: 1.2em !important;
}
/**:not(div) > p {
margin-left: 1.2%;
}*/
h1 {font-size: 2.5em;}
h1, h2 {
text-transform: uppercase;
}
h1, h2, h3, h4, h5, h6 {
line-height: 1.2em;
padding-top:1em;
text-align: left !important;
font-weight:400;
}
h2 ~ h2, section > h2 {
padding-top: 5px;
margin-top: 40px;
}
h2 a[href], h3 a[href] {
background-image: none;
text-transform:uppercase;
padding: 1px 3px 1px 3px;
font-size: 12pt;
float: right;
position:relative;
top: -3px;
}
h2 a[href]::before , h3 a[href]::before {
content: " \u2191";
width: 20px;
height: 20px;
display:inline-block;
color: #9931FC;
text-align:center;
margin-right: 10px;
}
/*h3 a[href] {
color:white
background-image: none;
text-transform:uppercase;
padding: 1px 3px 1px 3px;
font-size: 8pt !important;
border: 1px solid #9931FC;
float: right;
position:relative;
top: -11px;
right: -11px;
border-radius: 0 14px 0 0;
}*/
p {
overflow-wrap: break-word;
word-wrap: break-word;
}
a {
color : black;
text-decoration: none;
background-image: -webkit-gradient(linear,left top, left bottom,color-stop(50%, transparent),color-stop(0, rgba(154, 49, 252,.5)));
background-image: linear-gradient(180deg,transparent 50%,rgba(154, 49, 252,.5) 0);
background-position-y: 3px;
background-position-x: 0px;
background-repeat: no-repeat;
-webkit-transition: .15s ease;
transition: .15s ease;
}
a:hover {
color: #282828;
background-position: top 6px right 0px;
background-image: -webkit-gradient(linear,left top, left bottom,color-stop(60%, transparent),color-stop(0, #9931FC));
background-image: linear-gradient(180deg,transparent 60%,#9931FC 0);
}
footer {
margin-top: 20px;
border-top: 1px solid lightgrey;
text-align: center;
color: grey;
font-size: 9pt;
}
/* dashboard */
.info_api {
max-width: 35%;
border-radius: 15px;
text-align: left;
vertical-align: top;
background-color: #9931FC;
color: white;
}
.info_api, .api_calls {
display: inline-block;
text-align: left;
height: 200px;
padding:4%;
margin: 1% 2% 1% 0px;
border-radius: 10px;
box-shadow: 0px 10px 30px 0px rgba(133,66,189,0.1);
vertical-align:top;
}
.api_calls {
max-width: 40%;
background-color: white;
scroll-behavior: smooth;
overflow: auto;
overflow-y: scroll;
scrollbar-color: #9931FC rgb(154, 49, 252);
border-radius: 10px;
}
.api_calls div {padding-bottom:2%;}
.api_calls:hover {
overflow-y: scroll;
}
.api_calls h4, .info_api h2 {padding-top: 0px !important; margin-top: 0px !important;}
.api_calls div p {
padding: 0.2em 0.5em;
border-top: solid 1px #F8F8F8;
}
.date_log , .method_log {
color: grey;
font-size: 0.8em;
}
.method_log {margin-left: 15px;}
.date_log {display:inline-grid;}
.group_log:nth-child(odd) {
margin-right:5px;
font-size: 0.9em;
}
.group_log:nth-child(even) {
display: inline-grid;
vertical-align: top;
}
.status_log {padding-right:15px;}
.status_log::before {
content: '';
display: inline-block;
width: 1em;
height: 1em;
vertical-align: middle;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
background-color: grey;
margin-right: 0.8em;
}
.code_200::before {
background-color: #00cc00;
}
.code_404::before {
background-color: #cccc00;
}
.code_500::before {
background-color: #cc0000;
}
"""
def __css_path(self, css_path=None):
"""Add link to a css file if specified in argument -css"""
return """<link rel="stylesheet" type="text/css" href='"""+css_path+"""'>""" if css_path else ""
def logger_ramose(self):
"""This method adds logging info to a local file"""
# logging
logFormatter = logging.Formatter("[%(asctime)s] [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
rootLogger = logging.getLogger()
fileHandler = logging.FileHandler("ramose.log")
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
def __parse_logger_ramose(self):
"""This method reads logging info stored into a local file, so as to be browsed in the dashboard.
Returns: the html including the list of URLs of current working APIs and basic logging info """
with open("ramose.log") as l_f:
logs = ''.join(l_f.readlines())
rev_list = set()
rev_list_add = rev_list.add
rev_list = [x for x in list(reversed(logs.splitlines())) if not (x in rev_list or rev_list_add(x))]
html = """
<p></p>
<aside>
<h4>RAMOSE API DASHBOARD</h4>
<ul id="sidebar_menu" class="sidebar_menu">"""
for api_url, api_dict in self.conf_doc.items():
html +="""
<li><a class="btn active" href="%s">%s</a></li>
""" % (api_url, api_dict["conf_json"][0]["title"])
html += """
</ul>
</aside>
<header class="dashboard">
<h1>API MONITORING</h1>"""
for api_url, api_dict in self.conf_doc.items():
clean_list = [l for l in rev_list if api_url in l and "debug" not in l]
api_logs_list = ''.join(["<p>"+self.clean_log(l,api_url) +"</p>" for l in clean_list if self.clean_log(l,api_url) !=''])
api_title = api_dict["conf_json"][0]["title"]
html += """
<div class="info_api">
<h2>%s</h2>
<a id="view_doc" href="%s">VIEW DOCUMENTATION</a><br/>
<a href="%s">GO TO SPARQL ENDPOINT</a><br/>
</div>
<div class="api_calls">
<h4>Last calls</h4>
<div>
%s
</div>
</div>
""" % ( api_title,api_url, api_dict["tp"], api_logs_list)
return html
def get_documentation(self, css_path=None, base_url=None):
"""This method generates the HTML documentation of an API described in configuration file."""
if base_url is None:
first_key = next(iter(self.conf_doc))
conf = self.conf_doc[first_key]
else:
conf = self.conf_doc['/'+base_url]
return 200, """<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%s</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width" />
<style>%s</style>
%s
</head>
<body>
<aside>%s</aside>
<main>%s</main>
<section id="operations">%s</section>
<footer>%s</footer>
</body>
</html>""" % (self.__title(conf), self.__css(), self.__css_path(css_path), self.__sidebar(conf), self.__header(conf), self.__operations(conf), self.__footer())
def get_index(self, css_path=None):
"""This method generates the index of all the HTML documentations that can be
created from the configuration file."""
return """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>RAMOSE</title>
<meta name="description" content="Documentation of RAMOSE API Manager">
<style>%s</style>
%s
</head>
<body>
%s
<footer>%s</footer>
</body>
</html>
""" % (self.__css(), self.__css_path(css_path), self.__parse_logger_ramose(), self.__footer())
def store_documentation(self, file_path, css_path=None):
"""This method stores the HTML documentation of an API in a file."""
html = self.get_documentation(css_path)[1]
with open(file_path, "w+", encoding='utf8') as f:
f.write(html)
def clean_log(self, l, api_url):
"""This method parses logs lines into structured data."""
full_str = ''
if len(l.split("- - ",1)) > 1:
s = l.split("- - ",1)[1]
date = s[s.find("[")+1:s.find("]")]
method = s.split('"')[1::2][0].split()[0]
cur_call = s.split('"')[1::2][0].split()[1].strip()
status = sub(r"\D+", "", s.split('"',2)[2])
if cur_call != api_url+'/':
full_str = "<span class='group_log'><span class='status_log code_"+status+"'>"+status+"</span>"+"<span class='date_log'>"+date+"</span><span class='method_log'>"+method+"</span></span>"+"<span class='group_log'><span class='call_log'><a href='"+cur_call+"' target='_blank'>"+cur_call+"</a></span></span>"
return full_str
class DataType(object):
def __init__(self):
"""This class implements all the possible data types that can be used within
the configuration file of RAMOSE. In particular, it provides methods for converting
a string into the related Python data type representation."""
self.func = {
"str": DataType.str,
"int": DataType.int,
"float": DataType.float,
"duration": DataType.duration,
"datetime": DataType.datetime
}
def get_func(self, name_str):
"""This method returns the method for handling a given data type expressed as a string name."""
return self.func.get(name_str)
@staticmethod
def duration(s):
"""This method returns the data type for durations according to the XML Schema
Recommendation (https://www.w3.org/TR/xmlschema11-2/#duration) from the input string.
In case the input string is None or it is empty, an high duration value
(i.e. 2000 years) is returned."""
if s is None or s == "":
d = parse_duration("P2000Y")
else:
d = parse_duration(s)
return datetime(1983, 1, 15) + d
@staticmethod
def datetime(s):
"""This method returns the data type for datetime according to the ISO 8601
(https://en.wikipedia.org/wiki/ISO_8601) from the input string. In case the input string is None or
it is empty, a low date value (i.e. 0001-01-01) is returned."""
default = datetime(1, 1, 1, 0, 0)
if s is None or s == "":
d = parse("0001-01-01", default=default)
else:
d = parse(s, default=default)
return d
@staticmethod
def str(s):
"""This method returns the data type for strings. In case the input string is None, an empty string
is returned."""
if s is None:
l = ""
else:
l = str(s).lower()
return l
@staticmethod
def int(s):
"""This method returns the data type for integer numbers from the input string. In case the input string is
None or it is empty, a low integer value is returned."""
if s is None or s == "":
i = -maxsize
else:
i = int(s)
return i
@staticmethod
def float(s):
"""This method returns the data type for float numbers from the input string. In case the input string is
None or it is empty, a low float value is returned."""
if s is None or s == "":
f = float(-maxsize)
else:
f = float(s)
return f
class Operation(object):
def __init__(self, op_complete_url, op_key, i, tp, sparql_http_method, addon):
""" This class is responsible for materialising a API operation to be run against a SPARQL endpoint.
It takes in input a full URL referring to a call to an operation (parameter 'op_complete_url'),
the particular shape representing an operation (parameter 'op_key'), the definition (in JSON) of such
operation (parameter 'i'), the URL of the triplestore to contact (parameter 'tp'), the HTTP method
to use for the SPARQL request (paramenter 'sparql_http_method', set to either 'get' or 'post'), and the path
of the Python file which defines additional functions for use in the operation (parameter 'addon')."""
self.url_parsed = urlsplit(op_complete_url)
self.op_url = self.url_parsed.path
self.op = op_key
self.i = i
self.tp = tp
self.sparql_http_method = sparql_http_method
self.addon = addon
self.operation = {
"=": eq,
"<": lt,
">": gt
}
self.dt = DataType()
# START: Ancillary methods
@staticmethod
def get_content_type(ct):
"""It returns the mime type of a given textual representation of a format, being it either
'csv' or 'json."""
content_type = ct
if ct == "csv":
content_type = "text/csv"
elif ct == "json":
content_type = "application/json"
return content_type
@staticmethod
def conv(s, query_string, c_type="text/csv"):
"""This method takes a string representing a CSV document and converts it in the requested format according
to what content type is specified as input."""
content_type = Operation.get_content_type(c_type)
# Overrite if requesting a particular format via the URL
if "format" in query_string:
req_formats = query_string["format"]
for req_format in req_formats:
content_type = Operation.get_content_type(req_format)
if "application/json" in content_type:
with StringIO(s) as f:
r = []
for i in DictReader(f):
r.append(dict(i))
# See if any restructuring of the final JSON is required
r = Operation.structured(query_string, r)
return dumps(r, ensure_ascii=False, indent=4), content_type
else:
return s, content_type
@staticmethod
def pv(i, r=None):
"""This method returns the plain value of a particular item 'i' of the result returned by the SPARQL query.
In case 'r' is specified (i.e. a row containing a set of results), then 'i' must be the index of the item
within that row."""
if r is None:
return i[1]
else:
return Operation.pv(r[i])
@staticmethod
def tv(i, r=None):
"""This method returns the typed value of a particular item 'i' of the result returned by the SPARQL query.
The type associated to that value is actually specified by means of the particular configuration provided
in the specification file of the API - field 'field_type'.
In case 'r' is specified (i.e. a row containing a set of results), then 'i' must be the index of the item
within that row."""
if r is None:
return i[0]
else:
return Operation.tv(r[i])
@staticmethod
def do_overlap(r1, r2):
"""This method returns a boolean that says if the two ranges (i.e. two pairs of integers) passed as inputs
actually overlap one with the other."""
r1_s, r1_e = r1
r2_s, r2_e = r2
return r1_s <= r2_s <= r1_e or r2_s <= r1_s <= r2_e
@staticmethod
def get_item_in_dict(d_or_l, key_list, prev=None):
"""This method takes as input a dictionary or a list of dictionaries and browses it until the value
specified following the chain indicated in 'key_list' is not found. It returns a list of all the
values that matched with such search."""
if prev is None:
res = []
else:
res = prev.copy()
if type(d_or_l) is dict:
d_list = [d_or_l]
if type(d_or_l) is list:
d_list = d_or_l
for d in d_list:
key_list_len = len(key_list)
if key_list_len >= 1:
key = key_list[0]
if key in d:
if key_list_len == 1:
res.append(d[key])
else:
res = Operation.get_item_in_dict(d[key], key_list[1:], res)
return res
@staticmethod
def add_item_in_dict(d_or_l, key_list, item, idx):
"""This method takes as input a dictionary or a list of dictionaries, browses it until the value
specified following the chain indicated in 'key_list' is not found, and then substitutes it with 'item'.
In case the final object retrieved is a list, it selects the object in position 'idx' before the
substitution."""
key_list_len = len(key_list)
if key_list_len >= 1:
key = key_list[0]
if type(d_or_l) is list:
if key_list_len == 1:
d_or_l[idx][key] = item
else:
for i in d_or_l:
Operation.add_item_in_dict(i, key_list, item, idx)
else:
if key in d_or_l:
if key_list_len == 1: