loglan_db.model_init.InitBase.__init__()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
nop 2
crap 2
1
# -*- coding: utf-8 -*-
2
3 1
"""
4
Initial common functions for LOD Model Classes
5
"""
6
7 1
from datetime import datetime
8 1
from typing import List, Set
9
10 1
from loglan_db import db
11
12
13 1
class InitBase:
14
    """
15
    Init class for common methods
16
    """
17
18 1
    def __repr__(self) -> str:
19 1
        return str(self.__dict__)
20
21 1
    def __str__(self) -> str:
22 1
        return str({
23
            k: v for k, v in sorted(self.__dict__.items())
24
            if not str(k).startswith("_") and k not in ["created", "updated"]})
25
26 1
    def __init__(self, **kwargs):
27 1
        for key in kwargs:
28 1
            setattr(self, key, kwargs[key])
29
30 1
    @classmethod
31
    def from_dict(cls, dic):
32
        """
33
34
        Args:
35
            dic:
36
37
        Returns:
38
39
        """
40 1
        return cls(**dic)
41
42 1
    def export(self):
43
        """
44
        Export record data from DB
45
        Should be redefine in model's class
46
        :return:
47
        """
48
49 1
    def import_(self):
50
        """
51
        Import txt data to DB
52
        Should be redefine in model's class
53
        :return:
54
        """
55
56 1
    @staticmethod
57 1
    def stringer(value) -> str:
58
        """
59
        Convert variable to string
60
        Args:
61
            value:
62
63
        Returns:
64
65
        """
66 1
        return str(value) if value else str()
67
68
69 1
class DBBase:
70
    """Common methods and attributes for basic models"""
71 1
    created = db.Column(db.TIMESTAMP, default=datetime.now(), nullable=False)
72 1
    updated = db.Column(db.TIMESTAMP, onupdate=db.func.now())
73 1
    __table__ = None
74 1
    __mapper__ = None
75 1
    id = None
76
77 1
    def save(self) -> None:
78
        """
79
        Add record to DB
80
        :return:
81
        """
82 1
        db.session.add(self)
83 1
        db.session.commit()
84
85 1
    def update(self, data) -> None:
86
        """
87
        Update record in DB
88
        :param data:
89
        :return:
90
        """
91 1
        for key, item in data.items():
92 1
            setattr(self, key, item)
93 1
        db.session.commit()
94
95 1
    def delete(self) -> None:
96
        """
97
        Delete record from DB
98
        :return:
99
        """
100 1
        db.session.delete(self)
101 1
        db.session.commit()
102
103 1
    @classmethod
104 1
    def get_all(cls) -> List:
105
        """
106
        Get all model objects from DB
107
        :return:
108
        """
109 1
        return db.session.query(cls).all()
110
111 1
    @classmethod
112 1
    def get_by_id(cls, cid: int):
113
        """
114
        Get model object from DB by it's id
115
        :param cid: cls id
116
        :return:
117
        """
118 1
        return db.session.query(cls).filter(cls.id == cid).first()
119
120 1
    @classmethod
121 1
    def attributes_all(cls) -> Set[str]:
122
        """
123
        :return:
124
        """
125 1
        return set(cls.__mapper__.attrs.keys())
126
127 1
    @classmethod
128 1
    def attributes_basic(cls) -> Set[str]:
129
        """
130
        :return:
131
        """
132 1
        return set(cls.attributes_all() - cls.relationships())
133
134 1
    @classmethod
135 1
    def attributes_extended(cls) -> Set[str]:
136
        """
137
        :return:
138
        """
139 1
        return set(cls.attributes_all() - cls.foreign_keys())
140
141 1
    @classmethod
142 1
    def relationships(cls) -> Set[str]:
143
        """
144
        :return:
145
        """
146 1
        return set(cls.__mapper__.relationships.keys())
147
148 1
    @classmethod
149 1
    def foreign_keys(cls) -> Set[str]:
150
        """
151
        :return:
152
        """
153 1
        return set(cls.attributes_all() - cls.relationships() - cls.non_foreign_keys())
154
155 1
    @classmethod
156 1
    def non_foreign_keys(cls) -> Set[str]:
157
        """
158
        :return:
159
        """
160
        return {column.name for column in cls.__table__.columns if not column.foreign_keys}
161