gpt4 book ai didi

python - sqlalchemy 和 postgresql 的编码错误

转载 作者:太空狗 更新时间:2023-10-29 17:00:36 27 4
gpt4 key购买 nike

我将金字塔用于具有 postgres 数据库、wtforms、sqlalchemy 和 jinja2 的 Web 应用程序,当应用程序尝试从数据库中获取问题类型以使用 wtforms 填充选择字段时出现此错误:

Error: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)

这是 model.py 中的问题类型表:

class Mixin(object):
id = Column(Integer, primary_key=True, autoincrement=True)
created = Column(DateTime())
modified = Column(DateTime())

__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8'
}
__mapper_args__ = {'extension': BaseExtension()}

class IssueType(Mixin, Base):
__tablename__ = "ma_issue_types"
name = Column(Unicode(40), nullable=False)

def __init__(self, name):
self.name = name

进入 bd 我有这个:

# select name from ma_issue_types where id = 3;
name
------------
Teléfono

这是错误发生的地方

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

from issuemall.models import DBSession, IssueType


class IssueTypeDao(object):

def getAll(self):
dbsession = DBSession()
return dbsession.query(IssueType).all() #HERE THROWS THE ERROR

这是回溯

Traceback (most recent call last):
File "/issueMall/issuemall/controller/issueRegisterController.py", line 16, in issue_register
form = IssueRegisterForm(request.POST)
File "/env/lib/python2.7/site-packages/wtforms/form.py", line 178, in __call__
return type.__call__(cls, *args, **kwargs)
File "/env/lib/python2.7/site-packages/wtforms/form.py", line 224, in __init__
super(Form, self).__init__(self._unbound_fields, prefix=prefix)
File "/env/lib/python2.7/site-packages/wtforms/form.py", line 39, in __init__
field = unbound_field.bind(form=self, name=name, prefix=prefix, translations=translations)
File "/env/lib/python2.7/site-packages/wtforms/fields/core.py", line 301, in bind
return self.field_class(_form=form, _prefix=prefix, _name=name, _translations=translations, *self.args, **dict(self.kwargs, **kwargs))
File "/issueMall/issuemall/form/generalForm.py", line 11, in __init__
types = issueTypeDao.getAll()
File "/issueMall/issuemall/dao/master/issueTypeDao.py", line 11, in getAll
return self.__dbsession.query(IssueType).all()
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/query.py", line 2115, in all
return list(self)
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/query.py", line 2341, in instances
fetch = cursor.fetchall()
File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 3205, in fetchall
l = self.process_rows(self._fetchall_impl())
File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 3172, in _fetchall_impl
return self.cursor.fetchall()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)

我试过了,没用 ascii as default encoding in python

我试过类似的方法,但没有用

gae python ascii codec cant decode byte

return dbsession.query(IssueType.id, IssueType.name.encode('utf-8')).all() #or decode('utf-8')

最佳答案

您需要配置 Psycopg2 的客户端编码。查看SQLAlchemy documentation :

By default, the psycopg2 driver uses the psycopg2.extensions.UNICODE extension, such that the DBAPI receives and returns all strings as Python Unicode objects directly - SQLAlchemy passes these values through without change. Psycopg2 here will encode/decode string values based on the current “client encoding” setting; by default this is the value in the postgresql.conf file, which often defaults to SQL_ASCII. Typically, this can be changed to utf-8, as a more useful default:

#client_encoding = sql_ascii # actually, defaults to database
# encoding
client_encoding = utf8

A second way to affect the client encoding is to set it within Psycopg2 locally. SQLAlchemy will call psycopg2’s set_client_encoding() method (see: http://initd.org/psycopg/docs/connection.html#connection.set_client_encoding) on all new connections based on the value passed to create_engine() using the client_encoding parameter:

engine = create_engine("postgresql://user:pass@host/dbname", client_encoding='utf8')

This overrides the encoding specified in the Postgresql client configuration.

client_encoding 参数可以指定为引擎 URL 中的查询字符串:

 postgresql://user:pass@host/dbname?client_encoding=utf8

关于python - sqlalchemy 和 postgresql 的编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14783505/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com