In my flask rest api app I have this model about user registration:
from sqlalchemy.dialects.postgresql import UUID
from db import db
import uuid
class UserModel(db.Model):
__tablename__ = "users"
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(250), unique=False, nullable=False)
email = db.Column(db.String(50), unique=True, nullable=False)
created = db.Column(db.String(50), unique=False, nullable=False)
uuid_user = db.Column(db.String(200), unique=True, nullable=False)
activated = db.Column(db.Boolean, default=False)
So for id primary key I set a uuid key. Into DB the value is inserted with correctly format, example:
465dc674-ca3a-11ed-afa1-0242ac120002
Now I have this function to retrieve all user for db:
@blp.route("/v0/user/<int:id>")
class User(MethodView):
@blp.response(200, UserSchema)
def get(self, id):
user = UserModel.query.get_or_404(id)
return user
and when I run get request with Postam, the value of id into response is like this:
"activated": false,
"created": "03/24/2023, 11:29:40",
"email": "<mail>@gmail.com",
"id": 2.89867639142417965323251007576809137908e+38,
and this is the userschema:
class UserSchema(Schema):
id = fields.Int(dump_only=True)
username = fields.Str(required=True)
password = fields.Str(required=True)
email = fields.Str(required=True)
created = fields.Str(required=False)
uuid_user = fields.Str(required=False)
activated = fields.Bool(required=False)
How can I retrive the id with correct uuid format into db and use it for delete or get/id ?
Thanks
Change the type of id
field in the schema from integer to UUID:
class UserSchema(Schema):
id = fields.UUID(dump_only=True)
username = fields.Str(required=True)
password = fields.Str(required=True)
email = fields.Str(required=True)
created = fields.Str(required=False)
uuid_user = fields.Str(required=False)
activated = fields.Bool(required=False)
Furthermore change the type of the route parameter as well to avoid unnecessary converting:
@blp.route("/v0/user/<uuid:id>")
class User(MethodView):
...