flask - I want custom types registered in sqlalchemy to be recognized as primitive types during migration - Stack Overflow

I created a type UUIDBinary to change uuid7 from string to binary when registering and binary to string

I created a type UUIDBinary to change uuid7 from string to binary when registering and binary to string when retrieving. model looks like this.

models/common.py

from uuid6 import UUID
from sqlalchemy.types import TypeDecorator, BINARY

class UUIDBinary(TypeDecorator):
    impl = BINARY
    cache_ok = True

    def __init__(self, length=16):
        super().__init__()
        self.length = length

    def load_dialect_impl(self, dialect):
        return dialect.type_descriptor(BINARY(self.length))

    def process_bind_param(self, value, dialect):
        if value is None:
            return None
        if isinstance(value, str):
            return UUID(value).bytes
        return value

    def process_result_value(self, value, dialect):
        if value is None:
            return None
        return str(UUID(bytes=value))

models/users.py

    id: Mapped[str] = mapped_column(
        UUIDBinary(16), primary_key=True, default=lambda: str(uuid7())
    )

then migration file is

    sa.Column('id', app.modelsmon.UUIDBinary(length=16), nullable=False),

the error is


    sa.Column('id', app.modelsmon.UUIDBinary(length=16), nullable=False),
                    ^^^
NameError: name 'app' is not defined

To make matters worse, if I make the UUIDBinary readable in init py, I get a circular reference error

backend-1   |     from app import db
backend-1   | ImportError: cannot import name 'db' from partially initialized module 'app' (most likely due to a circular import) (/code/app/__init__.py)

I wonder if it is possible to handle this with UUIDBinary instead of changing the migration or migration env.

This is what I want to get

    sa.Column('id', Binary(length=16), nullable=False),

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745085499a4610382.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信