Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2DB-related helper utilities. Taken from database.py 

3file at https://github.com/cookiecutter-flask/cookiecutter-flask 

4""" 

5import os 

6import sys 

7 

8sys.path.append(os.getcwd()) 

9from init import db 

10 

11 

12class CRUDMixin: 

13 """ 

14 Mixin that adds convenience methods for 

15 CRUD (create, read, update, delete) operations. 

16 """ 

17 

18 @classmethod 

19 def create(cls, **kwargs): 

20 """Create a new record and save it in the database. 

21 

22 Returns: 

23 DB Class Object: returns the created record 

24 """ 

25 instance = cls(**kwargs) 

26 return instance.save() 

27 

28 def update(self, commit=True, **kwargs): 

29 """Update specific fields of a record 

30 

31 Args: 

32 commit (bool, optional): flag whether to commit. Defaults to True. 

33 

34 Returns: 

35 Db Class object: returns the updated record if committed, 

36 None otherwise 

37 """ 

38 for attr, value in kwargs.items(): 

39 setattr(self, attr, value) 

40 if commit: 

41 self.save() 

42 return self 

43 return None 

44 

45 def save(self, commit=True): 

46 """Save the record. 

47 

48 Args: 

49 commit (bool, optional): flag whether to commit. Defaults to True. 

50 

51 Returns: 

52 Db Class object: returns the record saved to db session 

53 """ 

54 db.session.add(self) 

55 if commit: 

56 db.session.commit() 

57 return self 

58 

59 def delete(self, commit=True): 

60 """Remove the record from the database. 

61 

62 Args: 

63 commit (bool, optional): flag whether to commit. Defaults to True. 

64 

65 Returns: 

66 Db Class object: returns the updated record if committed, 

67 None otherwise 

68 """ 

69 db.session.delete(self) 

70 if commit: 

71 db.session.commit() 

72 return self 

73 return None 

74 

75 

76class YoModel(CRUDMixin, db.Model): 

77 """Base model class that includes CRUD convenience methods.""" 

78 

79 __abstract__ = True 

80 

81 

82class PkModel(YoModel): 

83 """ 

84 Base model class that includes CRUD convenience methods, 

85 plus adds a 'primary key' column named 'id'. 

86 """ 

87 

88 __abstract__ = True 

89 id = db.Column(db.Integer, primary_key=True) 

90 

91 @classmethod 

92 def get_by_id(cls, record_id): 

93 """Get record by ID. 

94 

95 Args: 

96 record_id (int): ID of record to get 

97 

98 Returns: 

99 DB Class object: object identified by record_id if any, 

100 None otherwise 

101 """ 

102 if any( 

103 ( 

104 isinstance(record_id, (str, bytes)) and record_id.isdigit(), 

105 isinstance(record_id, (int, float)), 

106 ) 

107 ): 

108 return cls.query.get(int(record_id)) 

109 return None