misc.py 1.82 KB
Newer Older
1
2
from binascii import hexlify
import os
Vladislav Rykov's avatar
Vladislav Rykov committed
3
4
import psycopg2
import json
5
6
7
8
9
10

def rand_str(length):
    if length % 2 == 0:
        return hexlify(os.urandom(length//2))
    else:
        return hexlify(os.urandom(length//2 + 1))
Vladislav Rykov's avatar
Vladislav Rykov committed
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

def prep_id_range(devlist):
    r = range(1,255)

    for dev in devlist:
        del r[r.index(dev[1])]

    s = ''
    inr = False
    for i in range(len(r)-1):
        if r[i+1] - r[i] > 1:
            if inr:
                s += str(r[i])+'], '
                inr = False
            else:
                s += str(r[i])+', '
        else:
            if not inr:
                s += '['+str(r[i])+'-'
                inr = True
   
    if r[-1] - r[-2] > 1:
        if inr:
            s += str(r[-1])+']'
        else:
            s += str(r[-1])
    else:
        if not inr:
            s += str(r[-1])
        else:
            s += str(r[-1])+']'

    return s
Vladislav Rykov's avatar
Vladislav Rykov committed
44
45
46
47

# decorator implementation
def with_psql(f):
    def _with_psql(*args, **kwargs):
Vladislav Rykov's avatar
Vladislav Rykov committed
48
49
50
51
52
53
54
55
        db_conf = read_json_file('db.conf')
        conn = psycopg2.connect(
                database = db_conf['name'], 
                user = db_conf['user'], 
                password = db_conf['password'],
                host = db_conf['host'],
                port = db_conf['port']
            )
Vladislav Rykov's avatar
Vladislav Rykov committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
        cur = conn.cursor()

        try:
            res = f(cur, *args, **kwargs)
        except (Exception, psycopg2.DatabaseError) as error:
            conn.rollback()
            res = (False, error)
        else:
            conn.commit()
        finally:
            cur.close()
            conn.close()
    
        return res
    return _with_psql

Vladislav Rykov's avatar
Vladislav Rykov committed
72
73
74
75
76
77
78
79
80
def read_json_file(path):
    json_dict = None
    try:
        with open(path) as json_file:
            json_dict = json.load(json_file)
    except Exception, e:
        print("{} : {}".format(path, e))

    return json_dict