-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdata_utils.py
More file actions
64 lines (48 loc) · 1.89 KB
/
Copy pathdata_utils.py
File metadata and controls
64 lines (48 loc) · 1.89 KB
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
import logging
from django.db import connection
logger = logging.getLogger(__name__)
# Function for getting database connection and then doing query execution
def execute_query(query_name, group_concat_max_len=None):
with connection.cursor() as cursor:
if group_concat_max_len:
cursor.execute('SET SESSION group_concat_max_len = %d' % group_concat_max_len)
cursor.execute("SET TIME ZONE 'UTC'")
cursor.execute(query_name)
description = cursor.description
rows = cursor.fetchall()
result = [dict(zip([column[0] for column in description], row)) for row in rows]
return result
# Function for getting database connection and then performing non select based statements
def execute_statement(query_name, group_concat_max_len=None):
with connection.cursor() as cursor:
if group_concat_max_len:
cursor.execute('SET SESSION group_concat_max_len = %d' % group_concat_max_len)
cursor.execute("SET TIME ZONE 'UTC'")
cursor.execute(query_name)
# Convert dict to a key value list
def dict_to_kv(dict_val):
result = [{'key': k, 'value': v} for k, v in dict_val.items()]
result.sort(key=lambda e: e['key'])
return result
# Convert string dict to native form
def dict2native(dict_val):
result = {}
if not isinstance(dict_val, dict):
return dict_val
for k, v in dict_val.items():
result[k] = v
if v == 'True': result[k] = True; continue
if v == 'False': result[k] = False; continue
if v == 'None': result[k] = None; continue
if isinstance(v, bool): continue
try:
result[k] = int(v)
continue
except Exception:
logger.info("Value is not int")
try:
result[k] = float(v)
continue
except Exception:
logger.info("Value is not float")
return result