python - 具有非 ascii 列的 SQLAlchemy 映射表到类

标签 python sql-server sqlalchemy mapper

item = Table('Item', metadata, autoload=True, autoload_with=engine, encoding = 'cp1257')

class Item(object):
    pass

from sqlalchemy.orm import mapper
mapper(Item, item)

我得到错误:

line 43, in <module>
    mapper(Item, item) 
  File "C:\Python27\lib\site-packages\sqlalchemy\orm\__init__.py", line 890, in mapper
    return Mapper(class_, local_table, *args, **params)
  File "C:\Python27\lib\site-packages\sqlalchemy\orm\mapper.py", line 211, in __init__
    self._configure_properties()
  File "C:\Python27\lib\site-packages\sqlalchemy\orm\mapper.py", line 578, in _configure_properties
    setparent=True)
  File "C:\Python27\lib\site-packages\sqlalchemy\orm\mapper.py", line 618, in _configure_property
    self._log("_configure_property(%s, %s)", key, prop.__class__.__name__)
  File "C:\Python27\lib\site-packages\sqlalchemy\orm\mapper.py", line 877, in _log
    (self.non_primary and "|non-primary" or "") + ") " + 
  File "C:\Python27\lib\site-packages\sqlalchemy\util.py", line 1510, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "C:\Python27\lib\site-packages\sqlalchemy\sql\expression.py", line 3544, in description
    return self.name.encode('ascii', 'backslashreplace')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xeb in position 7: ordinal not in range(128)

我正在连接到 MSSQL。表自动加载似乎工作。我只在尝试映射时遇到此错误。 谢谢大家的帮助!

最佳答案

将表映射到类会在类上创建映射属性。默认情况下,属性与列具有相同的名称。由于 python 2.x 仅允许使用 ascii 标识符,因此如果您有非 ascii 列名,则会失败。

我能想到的唯一解决方案是在将表映射到类时为标识符指定一个不同的名称。

下面的例子就是这样做的。请注意,为简单起见,我在代码上创建了表格,因此任何人都可以在没有现有表格的情况下运行代码。但是您可以对反射表执行相同的操作。

#-*- coding:utf-8 -*-

import sqlalchemy as sa
import sqlalchemy.orm

engine = sa.create_engine('sqlite://', echo=True) # new memory-only database
metadata = sa.MetaData(bind=engine)

# create a table. This could be reflected from the database instead:
tb = sa.Table('foo', metadata, 
    sa.Column(u'id', sa.Integer, primary_key=True),
    sa.Column(u'nomé', sa.Unicode(100)),
    sa.Column(u'ãéìöû', sa.Unicode(100))
)    
tb.create()

class Foo(object):
    pass

# maps the table to the class, defining different property names 
# for some columns:
sa.orm.mapper(Foo, tb, properties={
    'nome': tb.c[u'nomé'],
    'aeiou': tb.c[u'ãéìöû']
})

之后,您可以使用 Foo.nome 来引用 nome 列,使用 Foo.aeiou 来引用 ãéìöû 列。

关于python - 具有非 ascii 列的 SQLAlchemy 映射表到类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5829077/

相关文章:

caching - 如何记住查询 SQLAlchemy 关系的结果(以实现缓存)?

sqlalchemy:撤消 MetaData.remove(表)

python - 如何插入多对多关系的记录?

python - 使用 Sklearn 进行机器学习(Iris Flower)的 Python 代码出错

sql-server - Azure 数据库需要更改防火墙,但设置中缺少

Python、PEP-8 和多行字典格式化

java - 在不指定架构的情况下调用 MSSQL 函数

sql - 带条件的子查询内连接

Python: `key not in my_dict` 但 `key in my_dict.keys()`

python - 将包含 '[' , ']' 的字符串数组转换为 int 数组