|
1
|
|
|
# -*- coding: utf-8 -*- |
|
2
|
|
|
|
|
3
|
|
|
""" |
|
4
|
|
|
flask_jsondash.adapters.dbmongo |
|
5
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
6
|
|
|
|
|
7
|
|
|
Adapters for various storage engines. |
|
8
|
|
|
""" |
|
9
|
|
|
|
|
10
|
|
|
from datetime import datetime as dt |
|
11
|
|
|
|
|
12
|
|
|
|
|
13
|
|
|
class Db(object): |
|
14
|
|
|
"""Adapter for all mongo operations.""" |
|
15
|
|
|
|
|
16
|
|
|
def __init__(self, client, conn, coll, formatter): |
|
17
|
|
|
"""Setup connection.""" |
|
18
|
|
|
self.client = client |
|
19
|
|
|
self.conn = conn |
|
20
|
|
|
self.coll = coll |
|
21
|
|
|
self.formatter = formatter |
|
22
|
|
|
|
|
23
|
|
|
def count(self, **kwargs): |
|
24
|
|
|
"""Standard db count.""" |
|
25
|
|
|
return self.coll.count(**kwargs) |
|
26
|
|
|
|
|
27
|
|
|
def read(self, **kwargs): |
|
28
|
|
|
"""Read a record.""" |
|
29
|
|
|
if kwargs.get('c_id') is None: |
|
30
|
|
|
return self.coll.find(**kwargs) |
|
31
|
|
|
else: |
|
32
|
|
|
return self.coll.find_one(dict(id=kwargs.pop('c_id'))) |
|
33
|
|
|
|
|
34
|
|
|
def update(self, c_id, data=None, fmt_charts=True): |
|
35
|
|
|
"""Update a record.""" |
|
36
|
|
|
if data is None: |
|
37
|
|
|
return |
|
38
|
|
|
charts = self.formatter(data) if fmt_charts else data.get('modules') |
|
39
|
|
|
save_conf = { |
|
40
|
|
|
'$set': { |
|
41
|
|
|
'name': data.get('name', 'NONAME'), |
|
42
|
|
|
'modules': charts, |
|
43
|
|
|
'date': dt.now() |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
save_conf['$set'].update(**data) |
|
47
|
|
|
self.coll.update(dict(id=c_id), save_conf) |
|
48
|
|
|
|
|
49
|
|
|
def create(self, data=None): |
|
50
|
|
|
"""Add a new record.""" |
|
51
|
|
|
if data is None: |
|
52
|
|
|
return |
|
53
|
|
|
self.coll.insert(data) |
|
54
|
|
|
|
|
55
|
|
|
def delete(self, c_id): |
|
56
|
|
|
"""Delete a record.""" |
|
57
|
|
|
self.coll.delete_one(dict(id=c_id)) |
|
58
|
|
|
|
|
59
|
|
|
def delete_all(self): |
|
60
|
|
|
"""Delete ALL records. Separated function for safety. |
|
61
|
|
|
|
|
62
|
|
|
This should never be used for production. |
|
63
|
|
|
""" |
|
64
|
|
|
self.coll.remove() |
|
65
|
|
|
|