Home > Blockchain >  FastAPI - Invoke Function on API Call
FastAPI - Invoke Function on API Call

Time:10-16

I currently build an API which has a user schema that needs an ID and a timestamp:

def ts():
    d = datetime.datetime.now()
    return datetime.datetime.timestamp(d)*1000


def generate_id():
    first = ''.join(random.choice(string.ascii_lowercase   string.digits) for _ in range(8))
    second = ''.join(random.choice(string.ascii_lowercase   string.digits) for _ in range(4))
    third = ''.join(random.choice(string.ascii_lowercase   string.digits) for _ in range(4))
    fourth = ''.join(random.choice(string.ascii_lowercase   string.digits) for _ in range(4))
    fifth = ''.join(random.choice(string.ascii_lowercase   string.digits) for _ in range(12))

    _id = f'{first}-{second}-{third}-{fourth}-{fifth}'
    return _id

class User(BaseModel):
    id: str = generate_id()
    username: str
    created_timestamp: Optional[str] = ts()

This is my function to create the User:

def create_user(db: Session, user: schemas.User):
    db_item = models.User(**user.dict())
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item


# Endpoint to create a new attribute
@app.post("/entity/", response_model=schemas.User)
def create_user(user: schemas.User, db: Session = Depends(get_db)):
    db_user = crud.get_id(db, id=user.id)
    if db_user is not None:
        raise HTTPException(status_code=400, detail="ID schon vergeben")
    mail_user = crud.get_email(db, email=user.email)
    if mail_user is not None:
        raise HTTPException(status_code=400, detail="Mail bereits vergeben")
    return crud.create_user(db=db, user=user)

The endpoint itself works, however when I make a POST request, I get an error the second time, because the ID gets not "refreshed". The timestamp also stays the same and it outdated. The function seems to get called when the server starts. Is there a way to trigger the function on every API call?

CodePudding user response:

You'll have to use the default_factory functionality of pydantic.

id: str = Field(default_factory=generate_id)

This will call the function generate_id when you create the object and assign the return value to the id attribute.

  • Related