python - FastAPI - 如何生成随机 ID?

标签 python database api fastapi

我正在使用 FastAPI 制作简单的 CRUD API,我想做的是在创建新项目时生成唯一随机数(其他字段是地址和名称,应由用户填写)。我该怎么做?

我的代码片段带有类和 POST 函数。

app = FastAPI()

userdb = []

class User(BaseModel):
    id: int
    address: str
    name: str

@app.post("/users")
def add_user(user: User):
    userdb.append(users.dict())
    return userdb[-1]

最佳答案

uuid4通常是要走的路

在使用函数 anywhere 生成的任何 id 中,它绝对是独一无二的,具有天文可能性(请参阅 RFC-4122 Section 4.4),并且速度非常快

from uuid import uuid4

...
    unique_id = str(uuid4())

关于python - FastAPI - 如何生成随机 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67335107/

相关文章:

android - 尝试使用mainClassName时出现错误

python - 将文件转换为字典

python - 按组划分数据框的列?

python - 如何让GtkMenuToolButton在发出 'clicked'信号时打开相同的菜单?

database - 海量对象过期策略架构

database - 在 VB.NET 中使用 OLEDB 通过 DataGridView 更新 Access 数据库

c# - 在来自同一 MySQL 服务器的不同数据库的两个表中执行连接查询

rest - 如何安排 API 请求

api - 快速屏幕字体OCR技术还是API?

python - 在函数内合并数据帧