简体   繁体   English

SQLAlchemy和Postgres UnicodeDecodeError

[英]SQLAlchemy and Postgres UnicodeDecodeError

The problem I am facing is same as posted here SQLAlchemy and UnicodeDecodeError . 我面临的问题与此处发布的SQLAlchemy和UnicodeDecodeError相同 When I fetch results from a table I get the error: 当我从表中获取结果时,出现错误:

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

The two solutions proposed are using sy.setdefaultencoding('utf8') in python and passing additional charset argument to the connection string as follows: 提出的两个解决方案是在python中使用sy.setdefaultencoding('utf8')并将附加的charset参数传递给连接字符串,如下所示:

conn_str='postgresql+psycopg2://'+str(dbhost)+':' + str(port) + '/postgres?charset=utf8'

Both solution seem not to fix the problem. 两种解决方案似乎都不能解决问题。 What else can I debug? 我还能调试什么? The table is essentially GIS data for various countries. 该表实质上是各个国家的GIS数据。 So the tables have special character. 因此表具有特殊性。

It seems that encoding is different from server to client. 服务器和客户端的编码似乎不同。 You can verify this issuing these commands: 您可以通过以下命令验证它的发出:

SHOW client_encoding; --Equivalent to: SELECT current_setting('client_encoding');
SHOW server_encoding; --Equivalent to: SELECT current_setting('server_encoding');

PostgreSQL automatic converts to client encoding. PostgreSQL自动转换为客户端编码。 Probably both are different in your environment. 在您的环境中,两者可能都不同。 You can configure client_encoding by many ways: 您可以通过多种方式配置client_encoding

  • Using SET command when open connection in you app: SET client_encoding = 'UTF-8'; 在您的应用中打开连接时使用SET命令: SET client_encoding = 'UTF-8';
  • Using set_config function when open connection in you app: SELECT set_config('client_encoding', 'UTF-8', true); 在您的应用中打开连接时使用set_config函数: SELECT set_config('client_encoding', 'UTF-8', true);
  • Configure PGCLIENTENCODING environment var in you OS: export PGCLIENTENCODING=UTF8 在您的操作系统中配置PGCLIENTENCODING环境var: export PGCLIENTENCODING=UTF8
  • Edit client_encoding in postgres config file 在postgres配置文件中编辑client_encoding
  • Use ALTER SYSTEM (you must refresh config after that with SELECT pg_reload_conf(); ): ALTER SYSTEM SET client_encoding = 'UTF-8'; 使用ALTER SYSTEM (此后必须使用SELECT pg_reload_conf();刷新配置): ALTER SYSTEM SET client_encoding = 'UTF-8';

Update: Unfortunately it's not possible to enable automatic conversion from SQL_ASCII. 更新:不幸的是,不可能从SQL_ASCII启用自动转换。

If the client character set is defined as SQL_ASCII, encoding conversion is disabled, regardless of the server's character set. 如果将客户端字符集定义为SQL_ASCII,则无论服务器的字符集如何,都将禁用编码转换。 Just as for the server, use of SQL_ASCII is unwise unless you are working with all-ASCII data. 与服务器一样,除非使用全ASCII数据,否则使用SQL_ASCII是不明智的。

Quote from Postgres documentation . 引用Postgres文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM