You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python测试Flash消息内容报错:需字节类型而非字符串

解决Flask测试中Flash消息判断的类型错误问题

这个问题我之前踩过坑,其实就是类型不匹配导致的报错~

你写的代码里,response.data返回的是字节对象(bytes),而你用来判断的'Welcome back!'是普通字符串(str)。Python不允许直接用in运算符比较这两种不同类型的对象,所以才会抛出TypeError: a bytes-like object is required, not 'str'这个错误。

给你三种简单的解决方案,选哪种都可以:

方案1:将判断字符串转为字节形式

直接给字符串加上b前缀,把它变成字节对象,和response.data的类型保持一致:

response = tester.post('login', data=dict(username='test', password='lol'), follow_redirects=True)
assert b'Welcome back!' in response.data

方案2:把response.data解码为字符串

用decode()方法将字节对象转成utf-8编码的字符串(如果你的页面用了其他编码,替换成对应编码即可,比如gbk):

response = tester.post('login', data=dict(username='test', password='lol'), follow_redirects=True)
assert 'Welcome back!' in response.data.decode('utf-8')

方案3:使用get_data(as_text=True)直接获取字符串

Flask的测试响应对象提供了更直观的方法,as_text=True参数会自动帮你解码字节流为字符串:

response = tester.post('login', data=dict(username='test', password='lol'), follow_redirects=True)
assert 'Welcome back!' in response.get_data(as_text=True)

个人更推荐方案3,代码可读性更高,也不用手动处理编码问题~

内容的提问来源于stack exchange,提问作者user11229055

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:42:09