在 api 中使用 python 为 sqlachomy 生成 ID

问题描述 投票:0回答:1

您似乎在 Stack Overflow 上遇到了格式化代码的问题。这是您帖子的修订版本,具有正确的代码格式:


为 Flask-SQLAlchemy 中的项目生成 6 位 ID 号**

Stack Overflow 社区您好,

我目前正在开发 Flask-SQLAlchemy 项目,需要一些关于为项目生成唯一的 6 位 ID 号的指导。

我正在考虑两种方法,希望了解哪种方法更好的建议:

方法一:UUID生成器

``蟒蛇 导入uuid

defgenerate_id(): 返回 str(uuid.uuid4())[:6]


And then using it in my model:

``python
class Item(db.Model):
    id = db.Column(db.String(6), primary_key=True, default=generate_id, unique=True)
    # Other item attributes
``

**OR**

**Approach 2: String Attribute**

``python
class Item(db.Model):
    id = db.Column(db.String(6), primary_key=True, unique=True)
    # Other item attributes
``

I want to ensure the generated IDs are unique, and I'm looking for the most efficient and best practice approach. Any insights or alternative methods would be greatly appreciated!

my whole code:

**class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    last_name = db.Column(db.String(50), nullable=False)
    birthdate = db.Column(db.DateTime, nullable=False)
    phone = db.Column(db.String(15), nullable=False)
    e_mail = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(256), nullable=False)
    city = db.Column(db.String(50), nullable=False)
    street = db.Column(db.String(50), nullable=False)

    def __init__(self, name, last_name, birthdate, phone, e_mail, password, city, street):
        self.name = name
        self.last_name = last_name
        self.birthdate = birthdate
        self.phone = phone
        self.e_mail = e_mail
        self.password = password
        self.city = city
        self.street = street
    **



Thank you.

---

python api flask sqlalchemy flask-sqlalchemy
1个回答
0
投票

如果您希望您的 ID 是唯一的,那么将“唯一”标志设置为 true 绝对是一个好主意。
如果我理解正确的话,你的问题是你并不真正知道如何生成ID。

我向您推荐这篇关于如何生成“随机”字符串的文章:https://pynative.com/python-generate-random-string/

这里是文章中符合您要求的一些代码:

import secrets
import string

# secure random string
secure_str = ''.join((secrets.choice(string.ascii_letters) for i in range(6)))
print(secure_str)
# Output QQkABL

注意:您有可能会出错(总会有),因为 6 个字母的组合数量有限。根据我给你的代码,有 19,770,609,664。 165,553 代后,您有 50% 的机会发生碰撞!

© www.soinside.com 2019 - 2024. All rights reserved.