Warm tip: This article is reproduced from serverfault.com, please click

python-AttributeError:使用与后端无关的GUID类型时,“ UUID”对象没有属性“替换”

(python - AttributeError: 'UUID' object has no attribute 'replace' when using backend-agnostic GUID type)

发布于 2017-11-22 08:27:38

我想在使用SQLAlchemy 1.1.5的Postgresql数据库中拥有一个uuid类型的主键ID,并使用pg8000适配器连接到该数据库。我使用了SQLAlchemy文档中后端无关的GUID类型的配方

当我想插入数据库时​​,出现以下错误

  File ".../guid.py", line ???, in process_result_value
    return uuid.UUID(value)
  File "/usr/lib/python2.7/uuid.py", line 131, in __init__
    hex = hex.replace('urn:', '').replace('uuid:', '')
AttributeError: 'UUID' object has no attribute 'replace'

我的模特看起来像这样

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from guid import GUID
import uuid

base = declarative_base()

class Item(base):
    __tablename__ = 'item'

    id = Column(GUID(), default=uuid.uuid4, nullable=False, unique=True, primary_key=True)
    name = Column(String)
    description = Column(String)

    def __repr__(self):
        return "<Item(name='%s', description='%s')>" % (self.name, self.description)

我的资源或控制器如下所示

data = req.params
item = Item(name=data['name'], description=data['description'])

self.session.add(item)
self.session.commit()
Questioner
The Oracle
Viewed
0
2019-10-15 19:35:49

pg8000PostgreSQL数据库适配器返回一个uuid.UUID()对象(参见其类型映射文档,和SQLAlchemy的已通过该给TypeDecorator.process_result_value()方法

文档中给出的实现需要一个字符串,但是,这失败了:

>>> import uuid
>>> value = uuid.uuid4()
>>> uuid.UUID(value)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python2.7/uuid.py", line 133, in __init__
    hex = hex.replace('urn:', '').replace('uuid:', '')
AttributeError: 'UUID' object has no attribute 'replace'

快速的解决方法是强制将值改为字符串:

def process_result_value(self, value, dialect):
    if value is None:
        return value
    else:
        return uuid.UUID(str(value))

或者你可以先测试类型:

def process_result_value(self, value, dialect):
    if value is None:
        return value
    else:
        if not isinstance(value, uuid.UUID):
            value = uuid.UUID(value)
        return value

我已提交拉取请求#403来解决此问题(自合并以来)。