reddit-image-wall-getter/hash_compressor_distributed/webproj/thumbnailer/models.py

58 lines
1.6 KiB
Python
Raw Normal View History

2020-07-20 01:54:26 +00:00
import json
from typing import List
from django.db import connection, models
# Create your models here.
class TruncatableMixin:
@classmethod
def truncate_table(cls):
cursor = connection.cursor()
cursor.execute('TRUNCATE TABLE "{0}"'.format(cls._meta.db_table))
cursor.execute('ALTER SEQUENCE {0}_id_seq RESTART WITH 1'.format(cls._meta.db_table.lower()))
class ToJsonableMixin:
def to_jsonable(self):
internal_dict = self.__dict__.copy()
if '_state' in internal_dict:
del internal_dict['_state']
return internal_dict
NESTED_JSON_FIELDS: List[str] = []
def to_jsonable_nested(self):
data = self.to_jsonable()
for nested_json_field in type(self).NESTED_JSON_FIELDS:
field = data[nested_json_field]
if field is not None:
data[nested_json_field] = json.loads(data[nested_json_field])
return data
class Job(models.Model, TruncatableMixin, ToJsonableMixin):
NESTED_JSON_FIELDS = ['result']
hsh = models.CharField(max_length=255, null=False, blank=False)
file = models.TextField(null=False, blank=False)
taken_at = models.DateTimeField(default=None, null=True, blank=True)
result = models.TextField(default=None, null=True, blank=True)
class Log(models.Model, TruncatableMixin, ToJsonableMixin):
NESTED_JSON_FIELDS = ['sender', 'content']
sender = models.TextField(null=False, blank=False)
content = models.TextField(null=False, blank=False)
class Meta:
abstract = True
class ErrorLog(Log):
pass
class PerformanceLog(Log):
pass