Completed
Push — master ( ce9cc4...380669 )
by Chris
01:06
created

format_charts()   A

Complexity

Conditions 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
3
"""
4
flask_jsondash.db_adapters
5
~~~~~~~~~~~~~~~~~~~~~~~~~~
6
7
A translation adapter for making queries between storage types.
8
9
Types are either:
10
1. PostgreSQL json fields
11
2. MongoDB collections.
12
"""
13
14
import json
15
from datetime import datetime as dt
16
17
from pymongo import MongoClient
18
19
from . import settings
20
21
DB_NAME = settings.ACTIVE_DB
22
23
24
if DB_NAME == 'mongo':
25
    client = MongoClient(host=settings.DB_URI, port=settings.DB_PORT)
26
    conn = client[settings.DB_NAME]
27
    coll = conn[settings.DB_TABLE]
28
else:
29
    raise NotImplementedError(
30
        'Mongodb is the only supported database right now.')
31
32
33
def reformat_data(data, c_id):
34
    """Format/clean existing config data to be re-inserted into database."""
35
    data.update(dict(id=c_id, date=dt.now()))
36
    return data
37
38
39
def format_charts(data):
40
    """Form chart POST data for JSON usage within db."""
41
    modules = []
42
    for item in data:
43
        if item.startswith('module_'):
44
            val_json = json.loads(data[item])
45
            modules.append(val_json)
46
    return modules
47
48
49
def count(**kwargs):
50
    """Standard db count."""
51
    if DB_NAME == 'mongo':
52
        return coll.count(**kwargs)
53
    else:
54
        raise NotImplemented('{} is not supported.'.format(DB_NAME))
55
56
57
def read(**kwargs):
58
    """Read a record."""
59
    if DB_NAME == 'mongo':
60
        if kwargs.get('c_id') is None:
61
            return coll.find(**kwargs)
62
        else:
63
            return coll.find_one(dict(id=kwargs.pop('c_id')))
64
    else:
65
        raise NotImplemented('{} is not supported.'.format(DB_NAME))
66
67
68
def update(c_id, data=None, fmt_charts=True):
69
    """Update a record."""
70
    if data is None:
71
        return
72
    if DB_NAME == 'mongo':
73
        charts = format_charts(data) if fmt_charts else data.get('modules')
74
        save_conf = {
75
            '$set': {
76
                'name': data.get('name', 'NONAME'),
77
                'modules': charts,
78
                'date': dt.now()
79
            }
80
        }
81
        save_conf['$set'].update(**data)
82
        coll.update(dict(id=c_id), save_conf)
83
    else:
84
        raise NotImplemented('{} is not supported.'.format(DB_NAME))
85
86
87
def create(data=None):
88
    """Add a new record."""
89
    if data is None:
90
        return
91
    if DB_NAME == 'mongo':
92
        coll.insert(data)
93
    else:
94
        raise NotImplemented('{} is not supported.'.format(DB_NAME))
95
96
97
def delete(c_id):
98
    """Delete a record."""
99
    if DB_NAME == 'mongo':
100
        coll.delete_one(dict(id=c_id))
101
    else:
102
        raise NotImplemented('{} is not supported.'.format(DB_NAME))
103
104
105
def delete_all():
106
    """Delete ALL records. Separated function for safety.
107
108
    This should never be used for production.
109
    """
110
    if DB_NAME == 'mongo':
111
        coll.remove()
112
    else:
113
        raise NotImplemented('{} is not supported.'.format(DB_NAME))
114