【问题标题】:What is the best way to check that a url namespace is unique?检查 url 命名空间是否唯一的最佳方法是什么?
【发布时间】:2015-05-19 21:07:29
【问题描述】:

我正在尝试为我的“Page”网页生成一个唯一的命名空间(“7FH98T”)。起初我在考虑生成一个命名空间,然后查询数据库以检查命名空间是否不存在,但我在想如果有 500'000 个页面,那么每次创建新页面时查询所有命名空间不会很有效。

我意识到我可以只运行 db.session.commit(),如果出现异常,只需回滚并生成一个新的命名空间,但我宁愿在 generate_namespace() 函数中处理检查唯一性。

这是我的代码。我希望我清楚地解释了我想要做的事情。提前致谢。

class Page(db.Model):
    __tablename__ = 'pages'
    id = db.Column(db.Integer, primary_key=True)
    namespace = db.Column(db.String(6), unique=True)

    @staticmethod
    def generate_namespace():
        import random
        import string

        while unique == False:
            namespace = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
            p = Page.query.filter_by(namespace=namespace).first()
            if not p:  # Is this really the best way to do this?
                continue
            else:
                unique = True

        return namespace

【问题讨论】:

  • 至少根据您在代码中的注释,这是最好的方法。
  • 至于重复查询(尽管您必须在每页查询多次的可能性是天文数字),请在命名空间列上创建一个hashbtree 索引。跨度>

标签: python-3.x flask sqlalchemy


【解决方案1】:

If you need a unique identifier then one solution is to generate a UUID

import uuid

class Page(db.Model):
    __tablename__ = 'pages'
    id = db.Column(db.Integer, primary_key=True)
    namespace = db.Column(db.String(6), unique=True)

    @staticmethod
    def generate_namespace():
        namespace = uuid.uuid4() # Will produce a unique to the world identifier.
        return namespace

另外,我强烈建议您将导入保留在模块的顶部。导入需要很长时间。

【讨论】:

    猜你喜欢
    • 2020-12-08
    • 2011-05-25
    • 1970-01-01
    • 2021-12-29
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    相关资源
    最近更新 更多