# python3生成snowflake雪花ID {#python3生成snowflake雪花id}
本文讲解python3如何生成snowflake雪花ID。python提供了一种机制,提供了一个生成snowflake ID的服务,然后在代码中通过请求该服务来获取一个snowflake ID。
# 1. 安装pysnowflake {#_1-安装pysnowflake}
执行命令pip3 install pysnowflake
wangshibiao@wangshibiaodeMacBook-Pro ~/workspace/project/data_process_script/init_fuwuhao_users pip3 install pysnowflake
Collecting pysnowflake
Downloading pysnowflake-0.1.3.tar.gz (4.0 kB)
Collecting six
Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
Requirement already satisfied: requests in /usr/local/lib/python3.9/site-packages (from pysnowflake) (2.27.0)
Collecting tornado
Downloading tornado-6.1-cp39-cp39-macosx_10_9_x86_64.whl (416 kB)
|████████████████████████████████| 416 kB 368 kB/s
Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.9/site-packages (from requests->pysnowflake) (2.0.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.9/site-packages (from requests->pysnowflake) (2021.10.8)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.9/site-packages (from requests->pysnowflake) (3.3)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.9/site-packages (from requests->pysnowflake) (1.26.7)
Building wheels for collected packages: pysnowflake
Building wheel for pysnowflake (setup.py) ... done
Created wheel for pysnowflake: filename=pysnowflake-0.1.3-py3-none-any.whl size=4590 sha256=28cd46c7f14a9a938b15e50d58d875ba420d9188bfe45718d4b966bfd232dbf6
Stored in directory: /Users/wangshibiao/Library/Caches/pip/wheels/4b/aa/aa/76216a658617f7bb26b67f6e02676eec0bd50e4fefdfee52f1
Successfully built pysnowflake
Installing collected packages: tornado, six, pysnowflake
Successfully installed pysnowflake-0.1.3 six-1.16.0 tornado-6.1
WARNING: You are using pip version 21.0.1; however, version 21.3.1 is available.
You should consider upgrading via the '/usr/local/opt/python@3.9/bin/python3.9 -m pip install --upgrade pip' command.
wangshibiao@wangshibiaodeMacBook-Pro ~/workspace/project/data_process_script/init_fuwuhao_users
# 2. 启动snowflake服务 {#_2-启动snowflake服务}
执行命令snowflake_start_server
wangshibiao@wangshibiaodeMacBook-Pro ~/workspace/project/data_process_script/init_fuwuhao_users snowflake_start_server
Starting snowflake start at localhost:8910
# 3. 通过代码生成snowflake ID {#_3-通过代码生成snowflake-id}
封装了一个生成snowflake ID的方法,如下: 示例如下:
# 生成一个snowflake id
# python3生成snowflake的步骤:
# 1. pip3 install pysnowflake
# 2. 运行snowflake_start_server
# 3. 代码中调用snowflake.client.get_guid()获取一个snowflake ID
def generate_snowflake_id():
# 配置snowflake服务的主机配置,若不配置, 则默认使用localhost:8910
snowflake_server_host = 'localhost'
snowflake_server_port = 8910
snowflake.client.setup(snowflake_server_host, snowflake_server_port)
return snowflake.client.get_guid()