Last active
May 9, 2020 06:20
-
-
Save maou-shonen/6ce26c6cbe1521dd5ea89a8407db438f to your computer and use it in GitHub Desktop.
sqlalchemy BinaryUUID (mysql/mariadb)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from uuid import UUID | |
from sqlalchemy.types import TypeDecorator | |
from sqlalchemy.dialects.mysql import BINARY | |
class BinaryUUID(TypeDecorator): | |
impl = BINARY(16) | |
def process_bind_param(self, value, dialect=None): | |
if not value: | |
return None | |
if isinstance(value, UUID): | |
return value.bytes | |
else: | |
raise ValueError('value {} is not a valid UUID'.format(value)) | |
def process_result_value(self, value, dialect=None): | |
if not value: | |
return None | |
else: | |
return UUID(bytes=value) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from uuid import uuid4 | |
from sqlalchemy import Column | |
from sqlalchemy.ext.declarative import declarative_base | |
from .BinaryUUID import BinaryUUID | |
Base = declarative_base() | |
from .Base import BinaryUUID | |
class User(Base): | |
__tablename__ = 'users' | |
id = Column(BinaryUUID(), primary_key=True, default=uuid4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment