Skip to content

Column of type UUID fails to insert default #190

@hectorcanto

Description

@hectorcanto

Hi everyone,
With these versions:
Eve==0.7.10, Eve-SQLAlchemy==0.7.0, Cerberus==0.9.2, Flask-SQLAlchemy==2.3.2, SQLAlchemy==1.2.12, python 3.6.5, and postgres 9.5.5
I'm trying to insert a default value in a UUID primary key column defined as follows:

from sqlalchemy.dialects.postgresql import UUID
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)

I added a custom serializer:

from eve.io.base import BaseJSONEncoder
class CustomJSONEncoder(BaseJSONEncoder):
    def default(self, obj):
        if isinstance(obj, UUID):
            return str(obj)
        elif isinstance(obj, datetime):
            return obj.timestamp()

If I insert the row manually (db.session.add()) and make a GET, it works.

But when serializing the response of a POST, it fails.
The JSON serializer receives a function instead of an object.

Digging with the debugger I found that the json encoder holds this two lists:

o = SON[('id', <function uuid4 at 0x7f26fdd29158>)}
chunks = [id": "e95859ca-22dd-440f-b442-c076b8a33dc9"]

This seems incongruent.
If I go up in the callback chain until when the resource appears, I already have the id as a function, the same happens with another datetime field, while not with created_at, or updated_at (custom LAST_UPDATE).

I also tried to add a UUID Validator as suggested here:
http://docs.python-eve.org/en/latest/tutorials/custom_idfields.html#uuid-validation
and changing the schema type from string to uuid:

_DOMAIN["tasks"]["schema"]["id"]["type"] = "uuid"

Am I missing something regarding the validator or the schema?

As a workaround, I've tried to use server_default=sqlalchemy.text("uuid_generatev4()"), after installing the extension uuid-ossp, and it worked, but I prefer to have the generation on the language.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions