SoFunction
Updated on 2025-03-01

Django python snowflake algorithm implementation method

Django python snowflake algorithm implementation

The snowflake algorithm is encapsulated into a Django project, creating a custom module or application, and placing the algorithm implementation in it.

Create a new app in your Django project

(For example, named snowflake):

python  startapp snowflake

Create a file in the directory of the new application

And put the implementation code of the snowflake algorithm in it:

# snowflake/
import time

class Snowflake:
    def __init__(self, worker_id, epoch=0):
        self.worker_id = worker_id
         = epoch

         = 0
        self.last_timestamp = -1

    def generate_id(self):
        timestamp = int(() * 1000)

        if timestamp == self.last_timestamp:
             = ( + 1) & 4095
            if  == 0:
                timestamp = self.wait_next_millis(timestamp)
        else:
             = 0

        self.last_timestamp = timestamp

        return ((timestamp - ) << 22) | (self.worker_id << 12) | 

    def wait_next_millis(self, last_timestamp):
        timestamp = int(() * 1000)
        while timestamp <= last_timestamp:
            timestamp = int(() * 1000)
        return timestamp

Add the newly created app to the INSTALLED_APPS property of :

# 
INSTALLED_APPS = [
    ...
    'snowflake',
    ...
]

You can use the snowflake algorithm anywhere in your Django project.

# Use the snowflake algorithm in your view or model#Modify worker_id=1 according to distributed method to prevent high concurrency ID duplication.from  import Snowflake
def my_view(request):
    snowflake = Snowflake(worker_id=1)
    unique_id = snowflake.generate_id()
    print(unique_id)
    # Use a unique ID to perform other operations

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.