Demo entry 6682692

test

   

Submitted by anonymous on Dec 10, 2017 at 06:50
Language: Python. Code size: 938 Bytes.

import uuid
from sqlalchemy import types
from sqlalchemy.dialects.mysql.base import MSBinary

class UUID(types.TypeDecorator):
    """
    为SQLAlchemy创建UUID类型数据
    Ref: https://stackoverflow.com/questions/183042/how-can-i-use-uuids-in-sqlalchemy
    """
    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

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).