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"""LICENSE 

2Copyright 2020 Hermann Krumrey <hermann@krumreyh.com> 

3 

4This file is part of stockstert. 

5 

6stockstert is free software: you can redistribute it and/or modify 

7it under the terms of the GNU General Public License as published by 

8the Free Software Foundation, either version 3 of the License, or 

9(at your option) any later version. 

10 

11stockstert is distributed in the hope that it will be useful, 

12but WITHOUT ANY WARRANTY; without even the implied warranty of 

13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

14GNU General Public License for more details. 

15 

16You should have received a copy of the GNU General Public License 

17along with stockstert. If not, see <http://www.gnu.org/licenses/>. 

18LICENSE""" 

19 

20 

21from typing import Dict, Any 

22from stockstert.flask import db 

23 

24 

25class ModelMixin: 

26 """ 

27 A mixin class that specifies a couple of methods all database 

28 models should implement 

29 """ 

30 

31 id = db.Column( 

32 db.Integer, primary_key=True, nullable=False, autoincrement=True 

33 ) 

34 """ 

35 The ID is the primary key of the table and increments automatically 

36 """ 

37 

38 def __json__(self, include_children: bool = False) -> Dict[str, Any]: 

39 """ 

40 Generates a dictionary containing the information of this model 

41 :param include_children: Specifies if children data models will be 

42 included or if they're limited to IDs 

43 :return: A dictionary representing the model's values 

44 """ 

45 raise NotImplementedError() # pragma: no cover 

46 

47 def __str__(self) -> str: 

48 """ 

49 :return: The string representation of this object 

50 """ 

51 data = self.__json__() 

52 _id = data.pop("id") 

53 return "{}:{} <{}>".format(self.__class__.__name__, _id, str(data)) 

54 

55 def __repr__(self) -> str: 

56 """ 

57 :return: A string with which the object may be generated 

58 """ 

59 params = "" 

60 

61 for key, val in self.__json__().items(): 

62 params += "{}={}, ".format(key, repr(val)) 

63 params = params.rsplit(",", 1)[0] 

64 

65 return "{}({})".format(self.__class__.__name__, params) 

66 

67 def __eq__(self, other: Any) -> bool: 

68 """ 

69 Checks the model object for equality with another object 

70 :param other: The other object 

71 :return: True if the objects are equal, False otherwise 

72 """ 

73 if "__json__" in dir(other): 

74 return other.__json__() == self.__json__() 

75 else: 

76 return False # pragma: no cover 

77 

78 def __hash__(self) -> int: 

79 """ 

80 Creates a hash so that the model objects can be used as keys 

81 :return: None 

82 """ 

83 return hash(repr(self))