我寫了一個小幫助函數,用於在django模型中生成唯一的標記。您可以從模型的save()
方法中調用它。它使用定義的函數生成候選標記,在數據庫中搜索現有行中的候選標記。如果它找到一個,它會再次嘗試,否則,它將返回候選字符串。請注意,這裏存在一個小的競爭條件,但不太可能在具有足夠大的輸出範圍的令牌函數時發生。
def generate_unique_token(Model,
token_field="token",
token_function=lambda: uuid.uuid4().hex[:8]):
"""
Generates random tokens until a unique one is found
:param Model: a Model class that should be searched
:param token_field: a string with the name of the token field to search in the model_class
:param token_function: a callable that returns a candidate value
:return: the unique candidate token
"""
unique_token_found = False
while not unique_token_found:
token = token_function()
# This weird looking construction is a way to pass a value to a field with a dynamic name
if Model.objects.filter(**{token_field:token}).count() is 0:
unique_token_found = True
return token
然後,你可以簡單地通過調用
token = generate_unique_token(MyModelInstance, "token_field_name")
它甚至還支持使用令牌生成的其他方法找到一個獨特的標記。例如,如果你想使用完整的UUID,你可以簡單地調用它是這樣的:
token = generate_unique_token(MyModel, "token_field_name", lambda: uuid.uuid4().hex)
而不是重新發明輪子(通常不是一個好主意,尤其是對安全性)爲什麼不使用的溶液等[燒瓶-JWT](https://pythonhosted.org/Flask-JWT/)? –