sanic.response.json() 无法序列化bytes和datetime.datetime(),该如何处理?
试图
# server.py
from sanic import Sanic
from sanic.response import json
from utils.dbhelper_mysql import DBHelper_MySQL
app = Sanic(__name__)
app.update_config('./config.py')
db = DBHelper_MySQL(
app.config.get('MYSQL_HOST'),
app.config.get('MYSQL_NAME'),
app.config.get('MYSQL_USER'),
app.config.get('MYSQL_PASSWORD'),
sanic=app,
minsize=1,
maxsize=10
)
@app.route('/')
async def index(request):
sql = 'SELECT * FROM categories;'
data = await app.ctx.db.query(sql)
print(data)
return json(data)
if __name__ == '__main__':
app.run()
查询方法
# dbhelper_mysql
async def query(self, query, *parameters, **kwparameters):
"""Returns a row list for the given query and parameters."""
if not self.pool:
await self.init_pool()
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
try:
await cur.execute(query, kwparameters or parameters)
ret = await cur.fetchall()
except pymysql.err.InternalError:
await conn.ping()
await cur.execute(query, kwparameters or parameters)
ret = await cur.fetchall()
return ret
数据表结构及内容
-- 创建分类表
CREATE TABLE IF NOT EXISTS `categories` (
`id` BINARY ( 16 ) NOT NULL COMMENT '主键id',
`pid` BINARY ( 16 ) COMMENT '父id,一级分类父id为空',
`name` VARCHAR ( 64 ) NOT NULL COMMENT '分类名称',
`alias` VARCHAR ( 64 ) NOT NULL COMMENT '分类别名',
`summary` TEXT COMMENT '分类描述',
`level` CHAR ( 1 ) NOT NULL COMMENT '分类级别,1:一级分类,2:二级分类,3:三级分类',
`status` CHAR ( 1 ) NOT NULL COMMENT '分类状态,H:隐藏,S:显示,T:垃圾箱,R:毁灭、彻底删除',
`create_time` DATETIME ( 6 ) DEFAULT CURRENT_TIMESTAMP ( 6 ) COMMENT '创建时间',
`modify_time` DATETIME ( 6 ) DEFAULT CURRENT_TIMESTAMP ( 6 ) ON UPDATE CURRENT_TIMESTAMP ( 6 ) COMMENT '修改时间',
CONSTRAINT chk_c_level CHECK ( `level` = '1' OR `level` = '2' OR `level` = '3' ),
CONSTRAINT chk_c_status CHECK ( `status` = 'H' OR `status` = 'S' OR `status` = 'T' OR `status` = 'R' ),
UNIQUE KEY idx_c_name(`name`),
UNIQUE KEY idx_c_alias ( `alias` ),
PRIMARY KEY ( `id` )
);
-- 初始化分类信息
INSERT INTO `categories` (`id`,`name`,`alias`,`summary`,`level`,`status`) VALUES (UUID_TO_BIN(UUID(),TRUE),'信息技术','Tech','IT技术相关学习内容记录','1','S');
INSERT INTO `categories` (`id`,`name`,`alias`,`summary`,`level`,`status`) VALUES (UUID_TO_BIN(UUID(),TRUE),'读书笔记','Books','课外阅读相关记录','1','S');
INSERT INTO `categories` (`id`,`name`,`alias`,`summary`,`level`,`status`) VALUES (UUID_TO_BIN(UUID(),TRUE),'自考本科','zkbk','计算机应用专业自考本科学习笔记','1','S');
报错内容,无法序列化
[{'id': b'\x11\xeb\xc6\xc5\xa7\x1dS\xed\x9b\x86\x02B\xac\x11\x00\x02', 'pid': None, 'name': '信息技术', 'alias': 'Tech', 'summary': 'IT技术相关学习内容记录', 'level': '1', 'status': 'S', 'create_time': datetime.datetime(2021, 6, 6, 12, 49, 37, 946120), 'modify_time': datetime.datetime(2021, 6, 6, 12, 49, 37, 946120)}, {'id': b'\x11\xeb\xc6\xc5\xa7\x1e!w\x9b\x86\x02B\xac\x11\x00\x02', 'pid': None, 'name': '读书笔记', 'alias': 'Books', 'summary': '课外阅读相关记录', 'level': '1', 'status': 'S', 'create_time': datetime.datetime(2021, 6, 6, 12, 49, 37, 955711), 'modify_time': datetime.datetime(2021, 6, 6, 12, 49, 37, 955711)}, {'id': b'\x11\xeb\xc6\xc5\xa7\x1e\xcc\xf1\x9b\x86\x02B\xac\x11\x00\x02', 'pid': None, 'name': '自考本科', 'alias': 'zkbk', 'summary': '计算机应用专业自考本科学习笔记', 'level': '1', 'status': 'S', 'create_time': datetime.datetime(2021, 6, 6, 12, 49, 37, 960102), 'modify_time': datetime.datetime(2021, 6, 6, 12, 49, 37, 960102)}]
[2021-06-07 07:58:21 +0800] [13012] [ERROR] Exception occurred while handling uri: 'http://127.0.0.1:8000/'
Traceback (most recent call last):
File "E:\PythonProgram\fckm_sanic\venv\lib\site-packages\sanic\app.py", line 724, in handle_request
response = await response
File "E:\PythonProgram\fckm_sanic\server.py", line 36, in index
return json(data)
File "E:\PythonProgram\fckm_sanic\venv\lib\site-packages\sanic\response.py", line 270, in json
dumps(body, **kwargs),
File "D:\Python39\lib\json\__init__.py", line 234, in dumps
return cls(
File "D:\Python39\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "D:\Python39\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "D:\Python39\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论