Completed
Push — master ( 7cecba...b5cbdb )
by Chris
57s
created

get_db_handler()   A

Complexity

Conditions 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
1
# -*- coding: utf-8 -*-
2
3
"""
4
flask_jsondash.db
5
~~~~~~~~~~~~~~~~~~~~~~~~~~
6
7
A translation adapter for transparent operations between storage types.
8
"""
9
10
import json
11
from datetime import datetime as dt
12
13
from pymongo import MongoClient
14
15
from . import settings
16
from . import mongo_adapter
17
18
DB_NAME = settings.ACTIVE_DB
19
20
21
def reformat_data(data, c_id):
22
    """Format/clean existing config data to be re-inserted into database."""
23
    data.update(dict(id=c_id, date=dt.now()))
24
    return data
25
26
27
def format_charts(data):
28
    """Form chart POST data for JSON usage within db."""
29
    modules = []
30
    for item in data:
31
        if item.startswith('module_'):
32
            val_json = json.loads(data[item])
33
            modules.append(val_json)
34
    return modules
35
36
37
def get_db_handler():
38
    """Get the appropriate db adapter."""
39
    if DB_NAME == 'mongo':
40
        client = MongoClient(host=settings.DB_URI, port=settings.DB_PORT)
41
        conn = client[settings.DB_NAME]
42
        coll = conn[settings.DB_TABLE]
43
        return mongo_adapter.Db(client, conn, coll, format_charts)
44
    else:
45
        raise NotImplementedError(
46
            'Mongodb is the only supported database right now.')
47