loon_base_model.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import os
  2. import time
  3. import datetime
  4. from django.db import models
  5. from django.utils.translation import gettext_lazy as _
  6. from django.conf import settings
  7. from django.db.migrations.serializer import BaseSerializer
  8. from django.db.migrations.writer import MigrationWriter
  9. machine_id = settings.MACHINE_ID
  10. base_dir = settings.BASE_DIR
  11. class SnowflakeIDGenerator:
  12. def __init__(self):
  13. self.machine_flag = machine_id
  14. self.sequence = 0
  15. # get clock_flag from file
  16. clock_flag_file = os.path.join(base_dir,'clock_flag.txt')
  17. if os.path.exists(clock_flag_file):
  18. with open(clock_flag_file, 'r') as f:
  19. try:
  20. clock_flag = int(f.read())
  21. if clock_flag > 7:
  22. raise Exception('clock flag larger then 7')
  23. except Exception as e:
  24. clock_flag = 0
  25. with open(clock_flag_file, 'w') as f2:
  26. f2.write('0')
  27. else:
  28. clock_flag = 0
  29. with open(clock_flag_file, 'w') as f2:
  30. f2.write('0')
  31. self.clock_flag = clock_flag
  32. self.last_timestamp = -1
  33. def __call__(self):
  34. timestamp = int(time.time()*1000)
  35. if timestamp < self.last_timestamp:
  36. # clock backwards issue. 3bit for clock flag
  37. self.clock_flag = (self.clock_flag + 1) % 8
  38. if timestamp == self.last_timestamp:
  39. self.sequence = (self.sequence + 1) % 4096
  40. # if self.sequence == 0:
  41. # timestamp = self.wait_next_millis(self.last_timestamp)
  42. else:
  43. self.sequence = 0
  44. self.last_timestamp = timestamp
  45. # 3bit for clock flag, 7bit for machine id.
  46. return ((timestamp - 1288834974657) << 22) | (self.clock_flag << 19) | (self.machine_flag << 12) | self.sequence
  47. # def wait_next_millis(self, last_timestamp):
  48. # timestamp = int(time.time()*1000)
  49. # while timestamp <= last_timestamp:
  50. # timestamp = int(time.time()*1000)
  51. # return timestamp
  52. # class UnixTimestampField(models.DateTimeField):
  53. # """UnixTimestampField: creates a DateTimeField that is represented on the
  54. # database as a TIMESTAMP field rather than the usual DATETIME field.
  55. # """
  56. #
  57. # def __init__(self, *args, **kwargs):
  58. # super().__init__(**kwargs)
  59. # self.null = True
  60. #
  61. # def db_type(self, connection):
  62. # return "timestamp"
  63. #
  64. # def to_python(self, value):
  65. # return datetime.date.fromtimestamp(value)
  66. #
  67. # def get_db_prep_value(self, value):
  68. # if value == None:
  69. # return None
  70. # return datetime.date.strftime('%Y%m%d%H%M%S', value.timetuple())
  71. class BaseModel(models.Model):
  72. """
  73. basic tenant' model
  74. """
  75. id = models.BigIntegerField(primary_key=True)
  76. label = models.CharField('label', max_length=5000, blank=True, default='')
  77. creator_id = models.BigIntegerField("creator's id", default=0)
  78. created_at = models.DateTimeField("created_at", auto_now_add=True)
  79. updated_at = models.DateTimeField("updated_at", auto_now=True)
  80. def save(self, *args, **kwargs):
  81. self.id = SnowflakeIDGenerator().__call__()
  82. super(BaseModel, self).save(*args, **kwargs)
  83. def get_dict(self):
  84. fields = []
  85. for field in self._meta.fields:
  86. fields.append(field.name)
  87. dict_result = {}
  88. import datetime
  89. for attr in fields:
  90. if attr == "creator_id":
  91. from apps.account.models import User
  92. user_queryset = User.objects.filter(id=getattr(self, attr)).first()
  93. if user_queryset:
  94. creator_info = dict(id=user_queryset.id, name=user_queryset.name, alias=user_queryset.alias)
  95. else:
  96. creator_info = dict(id=getattr(self, attr), name="", alias="")
  97. dict_result["creator"] = creator_info
  98. elif attr == "tenant":
  99. pass
  100. elif attr == "password":
  101. pass
  102. elif isinstance(getattr(self, attr), datetime.datetime):
  103. dict_result[attr] = getattr(self, attr).strftime('%Y-%m-%d %H:%M:%S %z')
  104. elif isinstance(getattr(self, attr), datetime.date):
  105. dict_result[attr] = getattr(self, attr).strftime('%Y-%m-%d %z')
  106. else:
  107. dict_result[attr] = getattr(self, attr)
  108. return dict_result
  109. def get_raw_dict(self):
  110. """
  111. raw dict, do not convert ForeignKey and manytomanyfield
  112. :return:
  113. """
  114. pass
  115. # def get_dict(self):
  116. # role_dict_info = super().get_dict()
  117. # creator_obj = User.objects.filter(username=getattr(self, 'creator')).first()
  118. # if creator_obj:
  119. # role_dict_info['creator_info'] = dict(creator_id=creator_obj.id, creator_alias=creator_obj.alias,
  120. # creator_username=creator_obj.username)
  121. # else:
  122. # role_dict_info['creator_info'] = dict(creator_id=0, creator_alias='', creator_username=getattr(self, 'creator'))
  123. # return role_dict_info
  124. class Meta:
  125. abstract = True
  126. class BaseCommonModel(BaseModel):
  127. """
  128. basic model
  129. """
  130. tenant_id = models.BigIntegerField("tenant_id", default=1)
  131. class Meta:
  132. abstract = True
  133. # class DecimalSerializer(BaseSerializer):
  134. # def serialize(self):
  135. # return repr(self.value), {"from decimal import Decimal"}
  136. #
  137. #
  138. # MigrationWriter.register_serializer(SnowflakeIDGenerator, DecimalSerializer)