简体   繁体   English

FastAPI - 如何生成随机 ID?

[英]FastAPI - how to generate random ID?

I'm making simple CRUD API using FastAPI and what I want to do is generate unique random when creating new item (other fields are address and name which should be filled by user).我正在使用 FastAPI 制作简单的 CRUD API,我想做的是在创建新项目时生成唯一的随机数(其他字段是地址和名称,应由用户填写)。 How can I do that?我怎样才能做到这一点?

There is fragment of my code with class and a POST function.我的代码片段有 class 和 POST function。

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 is often the way to go uuid4通常是 go 的方式

It'll be absolutely unique amongst any id ever generated with the function anywhere with astronomical likelihood (refer to RFC-4122 Section 4.4 ) and is very fast它在任何使用function生成的任何 id 中都是绝对独一无二的(请参阅RFC-4122 第 4.4 节),并且速度非常快

from uuid import uuid4

...
    unique_id = str(uuid4())

Another option - often what you want is for this ID to not necessarily be random, but rather to be some auto-incremented index from your database.另一种选择 - 通常你想要的是这个 ID 不一定是随机的,而是来自你的数据库的一些自动递增的索引。 The FastAPI docs give an example of this: FastAPI 文档给出了一个例子:

...

notes = sqlalchemy.Table(
    "notes",
    metadata,
    sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column("text", sqlalchemy.String),
    sqlalchemy.Column("completed", sqlalchemy.Boolean),
)

...
class NoteIn(BaseModel):
    text: str
    completed: bool

class Note(BaseModel):
    id: int
    text: str
    completed: bool

...

@app.post("/notes/", response_model=Note)
async def create_note(note: NoteIn):
    query = notes.insert().values(text=note.text, completed=note.completed)
    last_record_id = await database.execute(query)
    return {**note.dict(), "id": last_record_id}

https://fastapi.tiangolo.com/advanced/async-sql-databases/?h=id#about-notedict-id-last_record_id https://fastapi.tiangolo.com/advanced/async-sql-databases/?h=id#about-notedict-id-last_record_id

In your case you would use separate models for UserIn and User .在您的情况下,您将为UserInUser使用单独的模型。 Then in your example you would then assign the ID in the response model as the index in your userdb list (which in a real app would probably not just be a list, but a database).然后在您的示例中,您将在响应 model 中分配 ID 作为userdb列表中的索引(在实际应用程序中,它可能不仅仅是一个列表,而是一个数据库)。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

userdb = []

class UserIn(BaseModel):
    address: str
    name: str

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

@app.post("/users")
def add_user(user_in: UserIn) -> User:
    userdb.append(user_in)
    user_out_dict = userdb[-1].dict()
    user_out_dict.update({"id": len(userdb)-1})
    return User(**user_out_dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM