首页 > 编程语言 >tortoise-orm 使用雪花算法生成主键ID

tortoise-orm 使用雪花算法生成主键ID

时间:2023-09-16 17:55:49浏览次数:38  
标签:__ tortoise int timestamp self id orm 主键 def

import time
from tortoise import Tortoise, fields, run_async
from tortoise.models import Model

from typing import Any


class Snowflake:
    def __init__(self, machine_id: int):
        """
        生成雪花算法ID
        :param machine_id: 机器ID
        """
        self.machine_id: int = machine_id
        self.sequence: int = 0
        self.last_timestamp: int = -1

    @staticmethod
    def _wait_next_millis(last_timestamp) -> int:
        timestamp = int(time.time() * 1000)
        while timestamp <= last_timestamp:
            timestamp = int(time.time() * 1000)
        return timestamp

    @property
    def generate_id(self) -> int:
        timestamp = int(time.time() * 1000)
        if timestamp < self.last_timestamp:
            raise Exception("Clock moved backwards")
        if timestamp == self.last_timestamp:
            self.sequence = (self.sequence + 1) & 4095
            if self.sequence == 0:
                timestamp = self._wait_next_millis(self.last_timestamp)
        else:
            self.sequence = 0
        self.last_timestamp = timestamp
        return ((timestamp - 1288834974657) << 22) | (self.machine_id << 12) | self.sequence


class SnowflakeField(fields.BigIntField):
    SQL_TYPE = "BIGINT UNSIGNED"
    allows_generated = True

    def __init__(self, pk: bool = False, **kwargs: Any) -> None:
        if pk:
            kwargs["generated"] = bool(kwargs.get("generated", True))
        super().__init__(pk=pk, **kwargs)

    @property
    def constraints(self) -> dict:
        return {
            "ge": 1 if self.generated or self.reference else 0,
            "le": 9223372036854775807,
        }

    class _db_mysql:
        GENERATED_SQL = "BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT"


class SnowflakeIDGenerator:
    def __init__(self, model):
        self.model = model

    @staticmethod
    async def generate_id():
        snowflake = Snowflake(0)
        return snowflake.generate_id


class BaseModel(Model):
    id = SnowflakeField(pk=True, generated=False)

    @classmethod
    async def create(cls, **kwargs):
        kwargs["id"] = await SnowflakeIDGenerator(cls).generate_id()
        return await super().create(**kwargs)

    class Meta:
        abstract = True


class Event(BaseModel):
    name = fields.CharField(max_length=255)



async def run():
    await Tortoise.init(db_url="mysql://root:[email protected]:3306/test?charset=utf8mb4",modules={"models": ["__main__"]})
    await Tortoise.generate_schemas()
    count = 1
    while True:
        await Event.create(name=f"Test_{count}")
        count += 1


if __name__ == "__main__":
    run_async(run())

while True死循环写入测试过程中会出现生成重复ID情况,(≧﹏ ≦)

标签:__,tortoise,int,timestamp,self,id,orm,主键,def
From: https://www.cnblogs.com/cnxue/p/17707022.html

相关文章

  • winform 解决 窗体清晰度问题
    在C#中让Winform应用程序窗口自动适应高DPI缩放不使用其他特殊组件库的情况下添加清单文件在末尾添加:<applicationxmlns="urn:schemas-microsoft-com:asm.v3"><windowsSettings><dpiAwarexmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true&l......
  • The POM for com.xubo:service_base:jar:0.0.1-SNAPSHOT is missing, no dependency i
    报错信息[INFO]Scanningforprojects...[INFO][INFO]------------------------<com.xubo:service_edu>------------------------[INFO]Buildingservice_edu0.0.1-SNAPSHOT[INFO]--------------------------------[jar]---------------------------------[......
  • WebStorm中git中的“Local Changes”/“本地更改”视图消失如何处理
    项目场景:报表开发,打开页面,前端发起GET请求问题描述前端参数未传递到后台<FormItemlabel="查询日期:"required="required"style="display:inline;width:500px;margin-bottom:0px"><DatePickerv-model="datePick.startMonth"......
  • CF1542E1 Abnormal Permutation Pairs (easy version) 题解
    CF1542E1AbnormalPermutationPairs(easyversion)题解不会Hardversion对于第一个限制字典序,我们可以考虑枚举前\(i\)位相同,然后考虑后\(n-i\)位。我们只需要保证\(p_{i+1}<q_{i+1}\)即可。我们设\(len=n-i\)。由于前\(i\)位完全相同,所以前\(i\)位内部......
  • Wood,微型 Java ORM 框架(首次发版)
    Wood,微型JavaORM框架(支持:javasql,xmlsql,annotationsql;事务;缓存;监控;等...),零依赖!特点和理念:跨平台:可以嵌入到JVM脚本引擎(js,groovy,lua,python,ruby)及GraalVM支持的部分语言。很小巧:0.2Mb(且是功能完整,方案丰富;可极大简化数据库开发)。有个性:不喜欢反射(主打弱类型)、不喜......
  • 如何成功将 API 客户的 transformer 模型推理速度加快 100 倍
    ......
  • springmvc中设置文件的上传与下载,首先需要导入依赖,之后需要在springmvc.xml中配置问价
    2023-09-16导入依赖<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency>设置文件上传解析器springmvc.xml<?xml......
  • 跨平台的PHP开发IDE-PhpStorm 2023 mac+win版
    PhpStorm2023是一款专门为PHP开发人员设计的集成开发环境(IDE)。→→↓↓载PhpStorm2023mac/win它提供了丰富的功能,包括代码编辑、调试、版本控制、自动完成、代码检查、测试等,可以帮助开发人员更高效地编写和维护PHP代码。此外,它还支持多种框架,包括Symfony、Laravel、Yii、Zen......
  • RWKV解读:在Transformer的时代的新RNN
    转载地址:https://zhuanlan.zhihu.com/p/656323242作者:徐传飞在Transformer时代,介绍一个非Transformer架构的新网络——RWKV,RWKV是一种创新的深度学习网络架构,它将Transformer与RNN各自的优点相结合,同时实现高度并行化训练与高效推理,时间复杂度为线性复杂度,在长序列推理场景下具......
  • iview Form表单校验失效问题
    校验规则的prop名称要和v-model中的字段名称一致,否则会校验不通过,例如password输入框,prop为passwordProp,字段名称为password,即使输入字段也会校验不通过<template><Formref="formRef":model="formInline":rules="ruleInline"inline><FormItemprop=&qu......