20

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)

これを試してみましたが、PythonのデフォルトエンコーディングとしてASCIIが機能しませんでした

私はこのようなことを試みましたが、うまくいきませんでした

gae python asciiコーデックはバイトをデコードできません

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

2 に答える 2

48

Psycopg2 のクライアント エンコーディングを構成する必要があります。SQLAlchemy のドキュメントを参照してください。

デフォルトでは、psycopg2 ドライバーはpsycopg2.extensions.UNICODE拡張子を使用し、DBAPI がすべての文字列を Python Unicode オブジェクトとして直接受け取り、返すようにします。SQLAlchemy はこれらの値を変更せずに渡します。Psycopg2 は、現在の「クライアント エンコーディング」設定に基づいて文字列値をエンコード/デコードします。postgresql.confデフォルトでは、これはファイル内の値であり、多くの場合、デフォルトでSQL_ASCII. utf-8通常、これは、より便利なデフォルトとしてに変更できます。

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

クライアントのエンコーディングに影響を与える 2 つ目の方法は、Psycopg2 内でローカルに設定することです。SQLAlchemy は、パラメーターを使用して渡された値に基づいて、すべての新しい接続でpsycopg2 のset_client_encoding()メソッド ( http://initd.org/psycopg/docs/connection.html#connection.set_client_encodingを参照) を呼び出します。create_engine()client_encoding

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

これは、Postgresql クライアント構成で指定されたエンコーディングをオーバーライドします。

client_encodingパラメータは、エンジン URL でクエリ文字列として指定できます。

 postgresql://user:pass@host/dbname?client_encoding=utf8
于 2013-02-09T13:43:21.847 に答える