AttributeError:'UUID'对象没有属性'replace'

时间:2017-11-22 08:27:39

标签: python python-2.7 postgresql sqlalchemy uuid

我想使用SQLAlchemy在postgresql数据库中使用类型为uuid的主键id。我使用了GUID脚本here

当我想插入数据库时​​,我收到以下错误

  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()

我在debian 8上使用sqlalchemy 1.1.5和postgresql以及pg8000适配器。我该如何解决这个问题?

5 个答案:

答案 0 :(得分:7)

pg8000 PostgreSQL数据库适配器返回uuid.UUID()个对象(请参阅type mapping documentation,SQLAlchemy已将其传递给TypeDecorator.process_result_value() method

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

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

我已提交pull request #403来修复此文档(自合并以来)。

答案 1 :(得分:4)

这应该解决它:

id = Column(GUID(as_uuid=True), ...)

来自https://bitbucket.org/zzzeek/sqlalchemy/issues/3323/in-099-uuid-columns-are-broken-with

  

“如果要传递UUID()对象,则必须将as_uuid标志设置为True。”

答案 2 :(得分:0)

在整个系统中使用UUID时,这可能相当令人沮丧。在某些情况下,可能难以控制UUID是作为字符串还是作为原始UUID进入。要解决这个问题,这样的解决方案可能会起作用。我附上了文档的例子,以确保其他一切仍然成立。

# TODO: Set this up such that the normal uuid interface is available as a pass through
import uuid

class UUID(uuid.UUID):

    def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
                       int=None, version=None):

        if hex and (issubclass(type(hex), uuid.UUID) or isinstance(hex, uuid.UUID)):
            hex = str(hex)

        super(UUID, self).__init__(hex=hex, bytes=bytes, bytes_le=bytes_le, fields=fields, int=int, version=version)

print(UUID(uuid4())) # Now this works!

print(UUID('{12345678-1234-5678-1234-567812345678}'))
print(UUID('12345678123456781234567812345678'))
print(UUID('urn:uuid:12345678-1234-5678-1234-567812345678'))
print(UUID(bytes=b'\x12\x34\x56\x78' * 4)) # Python 3 requires this to be prefixed with b''. Docs appear to be mainly for Python 2
print(UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' +
              b'\x12\x34\x56\x78\x12\x34\x56\x78'))
print(UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)))
print(UUID(int=0x12345678123456781234567812345678))

请自行决定使用,这只是一个例子。

答案 3 :(得分:0)

我遇到了不使用表格而影响我的ORM的问题。我正在运行psycopg2。对我来说,解决方法是:

sudo pip install psycopg2-binary

重新启动apache之后,从psycopg2-binary版本2.7.5+开始,我再也没有看到该错误

答案 4 :(得分:0)

我遇到了同样的问题,搜索了两天,然后才发现错误之前的代码包含错误:

它收到以下错误,指的是python和sqlalchemy中的错误

import pandas as pd

df = pd.DataFrame({'myfield': [1, 4, 5]}, index=pd.date_range('2015-01-01', periods=3))
df = df.reset_index()
print("Index value: ", df.iloc[-1].name) #pandas-series
#Convert to python datetime
print("Index datetime: ", df.iloc[-1].name.to_pydatetime()) 

但是事实证明,在此之前,有一个进程向我的数据库函数发送了错误的对象

offertemodule_1  |   File "/opt/packages/database/models.py", line 79, in process_bind_param
offertemodule_1  |     return "%.32x" % uuid.UUID(value).int
offertemodule_1  |   File "/usr/local/lib/python3.7/uuid.py", line 157, in __init__
offertemodule_1  |     hex = hex.replace('urn:', '').replace('uuid:', '')
offertemodule_1  | sqlalchemy.exc.StatementError: (builtins.AttributeError) 'builtin_function_or_method' object has no attribute 'replace'
offertemodule_1  | [SQL: SELECT product.id AS product_id, product.supplier_id AS product_supplier_id, product.supplier_product_url AS product_supplier_product_url, product.supplier_product_id AS product_supplier_product_id, product.title AS product_title, product.description AS product_description, product.brand AS product_brand, product.product_line AS product_product_line, product.buying_price_ex_vat AS product_buying_price_ex_vat, product.buying_vat AS product_buying_vat, product.vat_pct AS product_vat_pct, product.advise_price AS product_advise_price, product.estimated_days_leadtime AS product_estimated_days_leadtime, product.product_category AS product_product_category, product.nestedproducts AS product_nestedproducts, product.atttibutes_meta AS product_atttibutes_meta, product.statistics_meta AS product_statistics_meta, product.active AS product_active, product.created AS product_created, product.created_by AS product_created_by, product.modified AS product_modified, product.modified_by AS product_modified_by
offertemodule_1  | FROM product
offertemodule_1  | WHERE product.id = %(id_1)s]
offertemodule_1  | [parameters: [immutabledict({})]]

应该是(请注意“ product_id”)

@ns_products.route('/<string:product_id>')
@api.response(404, 'product not found.')
class Details(Resource):
    @api.marshal_with(product)
    @api.doc(security='jwt')
    @jwt_required
    def get(self, product_id):
        '''Returns a single product instance'''
        return Product.get(id)`

因此,存储在product_id中的uuid字符串实际上是一个本机python对象'id'。因此,它尝试将字符串处理为uuid并失败。