AttributeError:使用与后端无关的GUID类型时,“ UUID”对象没有属性“替换” [英] AttributeError: 'UUID' object has no attribute 'replace' when using backend-agnostic GUID type

查看:134
本文介绍了AttributeError:使用与后端无关的GUID类型时,“ UUID”对象没有属性“替换”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用SQLAlchemy 1.1.5的Postgresql数据库中使用uuid类型的主键ID,并使用pg8000适配器连接到数据库。我使用了 与后端无关的GUID类型食谱(来自SQLAlchemy文档)。

I want to have a primary key id with type uuid in a Postgresql database using SQLAlchemy 1.1.5, connecting to the database with the pg8000 adapter. I used the Backend-agnostic GUID Type recipe from the SQLAlchemy documentation.

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

When I want to insert into the database, I get the following error

  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)

我的资源或控制器看起来像这样

My resource or controller looks like this

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

self.session.add(item)
self.session.commit()


推荐答案

pg8000 PostgreSQL数据库适配器返回 uuid.UUID()对象(请参见其类型映射文档,SQLAlchemy已将其传递给 TypeDecorator.process_result_value ()方法

The pg8000 PostgreSQL database adapter is returning a uuid.UUID() object (see their type mapping documentation, and SQLAlchemy has passed that to the TypeDecorator.process_result_value() method.

文档中给出的实现期望使用 string ,因此,失败:

The implementation given in the documentation expected a string, however, so this fails:

>>> 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'

快速的解决方法是无论如何都将值强制为字符串:

The quick work-around is to force the value to be a string anyway:

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

或者您可以先测试类型:

or you can test for the type first:

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

我已经提交了拉动要求est#403 来解决此问题(自合并以来)。

I've submited pull request #403 to fix this in the documentation (since merged).

这篇关于AttributeError:使用与后端无关的GUID类型时,“ UUID”对象没有属性“替换”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆