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

无法将字符串转为字节字符串,请求协助解决mod_wsgi报错问题

解决mod_wsgi中字符串转字节串的TypeError问题

错误原因

Python 3环境下,mod_wsgi要求Web应用返回的响应内容必须是字节字符串(bytes类型),你当前返回的是普通字符串(str类型),因此触发了TypeError: sequence of byte string values expected, value of type str found错误。

两种解决方法

  • 方法一:编码字符串为字节串
    在返回HTML内容时,调用encode('utf-8')将普通字符串转换为字节串:

    return [html.encode('utf-8')]
    
  • 方法二:直接定义字节串
    在HTML字符串前添加b前缀,直接定义为字节串类型:

    html = b'<html>\n' \
           b'<body>\n' \
           b'<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \
           b'mod wsgi Test Page\n' \
           b'</div>\n' \
           b'</body>\n' \
           b'</html>\n'
    

修改后的完整代码示例(方法一)

def application(environ, start_response):
    status = '200 OK'
    html = '<html>\n' \
           '<body>\n' \
           '<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \
           'mod wsgi Test Page\n' \
           '</div>\n' \
           '</body>\n' \
           '</html>\n'
    response_header = [('Content-type', 'text/html; charset=utf-8')]
    start_response(status, response_header)
    return [html.encode('utf-8')]

注:建议在响应头的Content-type中添加charset=utf-8,确保客户端能正确解析编码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:45:32