Pydantic: Support for PostgreSQL BYTEA type

Created on 31 Jul 2019  路  4Comments  路  Source: samuelcolvin/pydantic

Question

Hi!
I would like to handle PostgreSQL BYTEA data. For that I need to be able to read hexadecimal encoded data such as: '\x0b10100991..'
How would I extend the BaseModel to support this type correctly? Something like this is not working:

from pydantic import BaseModel,

class bytea(BaseModel):
    whatever: str


class ExampleBase(BaseModel):
    atdb: bytea = None
    class Config:
        orm_mode = True
        json_encoders = {
            bytea: lambda v: bytes.fromhex(v).decode('utf-8')
        }


class ExampleCreate(ExampleBase):
    pass
question

All 4 comments

Implement a Custom data type or use validators.

As future reference:

class ByteA:
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not isinstance(v, bytes):
            raise ValueError(f'`bytes` expected not {type(v)}')
        return binascii.b2a_hex(v)

Looks good, except:

  • bytea should definitely not inherit from BaseModel
  • generally classes should be CamelCase, not lowercase

Right, I have updated it accordingly. Thank you Samuel!

Was this page helpful?
0 / 5 - 0 ratings