-
Notifications
You must be signed in to change notification settings - Fork 31
/
forna_db.py
85 lines (71 loc) · 2.1 KB
/
forna_db.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
#!/usr/bin/python
"""forna_db.py: A script for storing forna sessions in a database and retrieve
a unique hash for sharing via link."""
__author__ = "Stefan Hammer"
__copyright__ = "Copyright 2015"
__version__ = "0.1"
__maintainer__ = "Stefan Hammer"
__email__ = "[email protected]"
import uuid
import sqlite3
import threading
import time
database = 'forna.db'
def init():
"""
If the database does not exist, create it
"""
conn = sqlite3.connect(database)
c = conn.cursor()
c.execute('''CREATE TABLE if not exists share
(date timestamp, uuid text, json text, static integer)''')
conn.commit()
conn.close()
# start cleanup scheduler
clean_thread = threading.Thread(target = cleanup)
clean_thread.daemon = True
clean_thread.start()
def cleanup():
while(True):
conn = sqlite3.connect(database)
c = conn.cursor()
c.execute('''DELETE FROM share WHERE date < DATE('now','-50 days') AND static == 0''')
conn.commit()
conn.close()
print " * Cleaning up database"
time.sleep(60*60*24)
def put(json):
"""
Store a json file in the database
@param json: The JSON content
"""
identifier = uuid.uuid4().hex
conn = sqlite3.connect(database)
c = conn.cursor()
c.execute('''INSERT INTO share VALUES (DATE('now'),?,?,?)''', (identifier, json, 0,))
conn.commit()
conn.close()
return identifier
def get(identifier):
"""
Get json object by its uuid:
@param uuid: The unique identifier
"""
conn = sqlite3.connect(database)
c = conn.cursor()
c.execute('SELECT json FROM share WHERE uuid=(?)', (identifier,))
result = c.fetchone()
if result is None:
raise NameError("This identifier is not available (any more)!")
return result[0]
def set_static(identifier):
"""
set to static by its uuid:
@param uuid: The unique identifier
"""
conn = sqlite3.connect(database)
c = conn.cursor()
c.execute('UPDATE share SET static=1 WHERE uuid=(?)', (identifier,))
conn.commit()
conn.close()
return "done";