Random ids in sqlalchemy (pylons)

后端 未结 3 1741
星月不相逢
星月不相逢 2021-02-09 20:28

I\'m using pylons and sqlalchemy and I was wondering how I could have some randoms ids as primary_key.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 21:25

    i use this pattern and it works pretty good. source

    from sqlalchemy import types
    from sqlalchemy.databases.mysql import MSBinary
    from sqlalchemy.schema import Column
    import uuid
    
    
    class UUID(types.TypeDecorator):
        impl = MSBinary
        def __init__(self):
            self.impl.length = 16
            types.TypeDecorator.__init__(self,length=self.impl.length)
    
        def process_bind_param(self,value,dialect=None):
            if value and isinstance(value,uuid.UUID):
                return value.bytes
            elif value and not isinstance(value,uuid.UUID):
                raise ValueError,'value %s is not a valid uuid.UUID' % value
            else:
                return None
    
        def process_result_value(self,value,dialect=None):
            if value:
                return uuid.UUID(bytes=value)
            else:
                return None
    
        def is_mutable(self):
            return False
    
    
    id_column_name = "id"
    
    def id_column():
        import uuid
        return Column(id_column_name,UUID(),primary_key=True,default=uuid.uuid4)
    
    #usage
    my_table = Table('test',metadata,id_column(),Column('parent_id',UUID(),ForeignKey(table_parent.c.id)))
    

    Though zzzeek I believe is the author of sqlalchemy, so if this is wrong he would know, and I would listen to him.

提交回复
热议问题