SQLAlchemy 和 UnicodeDecodeError

SQLAlchemy and UnicodeDecodeError(SQLAlchemy 和 UnicodeDecodeError)
本文介绍了SQLAlchemy 和 UnicodeDecodeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要了

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

当我将来自我使用 SQLAlchemy 访问的 MySQL 数据库的文本传递给这个函数时:

when I pass text coming from a MySQL database, which I am accessing using SQLAlchemy, to this function:

re.compile(ur"<([^>]+)>", flags=re.UNICODE).sub(u" ", s)

数据库编码为 utf-8,我什至将编码传递给 SQLAlchemy 的 create_engine 函数.

The database encoding is utf-8 and I am even passing the encoding to the create_engine function of SQLAlchemy.

这是我查询数据库的方式:

This is how I am querying the database:

doc = session.query(Document).get(doc_id)
s = doc.title

根据建议,我将 s.decode('utf-8') 传递给 sub .上面的错误消失了,但对于不同的文档,我得到了不同的错误:

By suggestion, I passed s.decode('utf-8') to sub . The error above disappeared, but I get a different error for a different document:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xeb in position 449: invalid continuation byte

数据库表定义如下:

CREATE TABLE `articles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) DEFAULT NULL,
  `cdate` datetime DEFAULT NULL,
  `link` varchar(255) DEFAULT NULL,
  `content` text,
  UNIQUE KEY `id` (`id`),
  UNIQUE KEY `link_idx` (`link`)
) ENGINE=InnoDB AUTO_INCREMENT=4127834 DEFAULT CHARSET=utf8;

任何帮助将不胜感激

推荐答案

我已经解决了这个问题.title 列由 SQLAlchemy 作为 str 而不是 Unicode 返回.我认为将 encoding='utf8' 作为参数添加到 create_engine 会解决这个问题,但是,正确的方法是将它传递到数据库 URI 中:mysql://me@myserver/mydatabase?charset=utf8 .

I have solved the issue. The title column was being returned by SQLAlchemy as a str and not Unicode. I thought adding encoding='utf8' as an argument to create_engine would take care of this, however, the right way to do it is to pass it in the database URI: mysql://me@myserver/mydatabase?charset=utf8 .

感谢您的所有回答!

这篇关于SQLAlchemy 和 UnicodeDecodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)