bib2html.py: Add incollection bibtype
[shutils.git] / restpublish.py
1 #!/usr/bin/env python3
2 #
3 # FLASK_APP=restpublish.py flask run
4
5 import datetime
6
7 import flask
8 from flask_restful import Resource, Api
9
10
11 class Element:
12 def __init__(self, key, value):
13 self.key = key
14 self.update(value)
15
16 def update(self, value):
17 self.value = value
18 self.ctime = datetime.datetime.now()
19
20 def is_expired(self, maxage):
21 return datetime.datetime.now() - self.ctime >= maxage
22
23
24 class ElementStore:
25 def __init__(self):
26 self.key_dict = dict()
27 self.chronolist = list()
28
29 def insert(self, key, value):
30 if key in self.key_dict:
31 el = self.key_dict[key]
32 el.update(value)
33 else:
34 el = Element(key, value)
35 self.key_dict[key] = el
36 self.chronolist.append(el)
37 return el
38
39 def remove(self, key):
40 del self.key_dict[key]
41 self.chronolist = [el for el in self.chronolist if el.key != key]
42
43 def garbagecollect(self):
44 maxage = datetime.timedelta(7)
45 oldestctime = datetime.datetime.now() - maxage
46 def is_expired(el):
47 return el.ctime < oldestctime
48
49 # Get idx such that self.chronolist[:idx] is expired and
50 # self.chronolist[idx:] is not expired.
51 idx = 0
52 while idx < len(self.chronolist) - 1:
53 if not is_expired(self.chronolist[idx]):
54 break
55 idx += 1
56
57 for el in self.chronolist[:idx]:
58 del self.key_dict[el.key]
59
60 self.chronolist = self.chronolist[idx:]
61
62
63 class EntryPoint(Resource):
64 def get(self):
65 return { 'elements': [el.key for el in store.chronolist] }
66
67 class ElementPoint(Resource):
68 def get(self, key):
69 if key not in store.key_dict:
70 return { 'message': 'No such element'}, 404
71
72 el = store.key_dict[key]
73 return { 'key': key, 'value': el.value, 'ctime': str(el.ctime) }
74
75 def delete(self, key):
76 if key in store.key_dict:
77 store.remove(key)
78 return { 'message': 'ok'}
79
80 def post(self, key):
81 req = flask.request.get_json(force=True)
82
83 if 'value' not in req:
84 return {'message': 'No value given.'}, 403
85
86 el = store.insert(key, req['value'])
87 store.garbagecollect()
88 return { 'key': key, 'value': el.value, 'ctime': str(el.ctime) }
89
90
91 # Map of keys to values
92 store = ElementStore()
93
94 app = flask.Flask(__name__)
95 api = Api(app)
96 api.add_resource(EntryPoint, "/")
97 api.add_resource(ElementPoint, "/<key>")
98