18

我想在使用 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()
4

6 回答 6

24

这应该解决它:

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

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

“如果你想传递一个UUID()对象,as_uuid标志必须设置为 True。”

于 2018-10-27T09:54:11.420 回答
12

pg8000PostgreSQL 数据库适配器正在返回一个uuid.UUID()对象(请参阅他们的类型映射文档,并且 SQLAlchemy 已将其传递给TypeDecorator.process_result_value()方法

但是,文档中给出的实现需要一个string,所以失败了:

>>> 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以在文档中解决此问题(自合并以来)。

于 2017-11-22T08:53:24.183 回答
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))

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

于 2018-06-12T18:24:28.057 回答
0

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

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

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({})]]

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

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

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

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

于 2020-12-08T19:33:49.787 回答
0

这里的实际问题是你有default=uuid.uuid4,postgres 需要一个 UUID 格式的字符串。你会想要类似的东西default=lambda: str(uuid.uuid4())

于 2021-10-20T17:47:14.143 回答
-1

我在不使用表单的情况下遇到了影响我的 ORM 的问题。我正在运行 psycopg2。我的解决方法是:

sudo pip install psycopg2-binary

重新启动 apache 后,我再也没有看到 psycopg2-binary 版本 2.7.5+ 的错误

于 2019-05-30T03:37:48.237 回答