对数据库ID进行散裂化计算

import basehash


class Hasher:
    """
    对数据库ID进行散列化计算
    """
    base36 = basehash.base62(11)

    @classmethod
    def from_model(cls, obj):
        if obj.pk is None:
            return None
        return cls.make_hash(obj.pk)

    @classmethod
    def make_hash(cls, object_pk):
        return cls.base36.hash('%(object_pk)d' % {
            'object_pk': object_pk
        })

    @classmethod
    def to_object_pk(cls, obj_hash):
        unhashed = '%d' % cls.base36.unhash(obj_hash)
        object_pk = int(unhashed)
        return object_pk
class BaseModel(models.Model):
    """自定义Model基类"""
    create_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    delete_at = models.DateTimeField(null=True, blank=True, default=None, verbose_name='删除时间')

    class Meta:
        abstract = True

    @property
    def hash(self):
        return Hasher.from_model(self)
class HashRetrieveViewSetMixin(GenericViewSet):
    """使用Hash检索对象的ViewSet基类"""

    def get_object(self):
        queryset = self.filter_queryset(self.get_queryset())

        obj = self.get_obj_from_hash(self.kwargs['pk'], queryset)
        self.check_object_permissions(self.request, obj)

        return obj

    def get_obj_from_hash(self, hash_id, queryset):
        """根据hash_id获取obj对象"""
        pk = self.hash_to_pk(hash_id)
        obj = get_object_or_404(queryset, pk=pk)
        return obj

    @staticmethod
    def hash_to_pk(hash_id):
        """Hash 转 id"""
        try:
            pk = Hasher.to_object_pk(hash_id)
        except ValueError:
            raise ParseError('parse error')
        return pk

 

posted @ 2019-08-02 09:07 前方、有光 阅读(...) 评论(...) 编辑 收藏