zoukankan      html  css  js  c++  java
  • 对数据库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
  • 相关阅读:
    JAVA邀请码生成器
    Mybatis+Spring实现Mysql读写分离
    Apache HttpComponents 工具类 [ HttpUtil ]
    JAVA短信验证码 工具类
    Spring 集成 Redis
    Java图片高保真缩放工具类
    JAVA Sftp 上传下载
    java项目小手册
    WebSocket前后端实现
    页面PC端 / 移动端整屏纵向翻页,点击/触摸滑动效果功能代码非插件
  • 原文地址:https://www.cnblogs.com/52-qq/p/11286570.html
Copyright © 2011-2022 走看看