【问题标题】:TypeError: sequence of byte string values expected, value of type str foundTypeError:预期的字节字符串值序列,找到类型 str 的值
【发布时间】:2016-01-17 12:43:10
【问题描述】:

我正在尝试使用mod_wsgi 为 Python 3 运行一个简单的“hello world”应用程序。我使用的是 Fedora 23。这是我的 Apache 虚拟主机配置:

<VirtualHost *:80>
    ServerName localhost
    ServerAdmin admin@localhost
    # ServerAlias foo.localhost
    WSGIScriptAlias /headers /home/httpd/localhost/python/headers/wsgi.py
    DocumentRoot /home/httpd/localhost/public_html
    ErrorLog /home/httpd/localhost/error.log
    CustomLog /home/httpd/localhost/requests.log combined
</VirtualHost>

wsgi.py:

def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'

    response_headers = [('Content-Type', 'text/plain'),
                        ('Content-Length', str(len(output)))]

    start_response(status, response_headers)

    return [output]

如果我将mod_wsgi 用于 Python 2 (sudo dnf remove python3-mod_wsgi -y &amp;&amp; sudo dnf install mod_wsgi -y &amp;&amp; sudo apachectl restart),它可以正常工作,但是在使用 Python 3 时会出现 500 内部服务器错误。这是错误日志:

mod_wsgi (pid=899): Exception occurred processing WSGI script '/home/httpd/localhost/python/headers/wsgi.py'.
TypeError: sequence of byte string values expected, value of type str found

更新

str(len(output)) 上使用encode()(或encode('utf-8'))也不起作用。现在我明白了:

Traceback (most recent call last):
  File "/home/httpd/localhost/python/headers/wsgi.py", line 8, in application
    start_response(status, response_headers)
TypeError: expected unicode object, value of type bytes found

【问题讨论】:

标签: python python-3.x mod-wsgi


【解决方案1】:

显然变量output 本身需要有一个字节字符串而不是一个unicode 字符串。它不仅需要更改response_headers,而且需要使用output 的所有地方(所以第6 行的str(len(output)).encode('utf-8') 不起作用,就像我一直在尝试的那样)。 p>

所以我的解决方案是:

def application(environ, start_response):
    status = '200 OK'
    output = b'Hello World!'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

(我在官方 mod_wsgi repo 上的 one of the tests 中找到了,正如 Rolbrok 在 cmets 中所建议的那样。)

【讨论】:

  • 这个让我今晚长出了一些白发!在凌晨 4:00 来到这里之前,我偶然发现了解决方案。大约3小时后就要上班了。只是想知道为什么需要这样做,是否有任何进一步的阅读?
  • 这是为什么呢?我让事情变得不必要的复杂。
【解决方案2】:

背景

这个问题是因为Python 3默认UTF-8造成的,因为今天我们发现有很多非母语的英文字符,最好能容纳下。 HTTP 仅适用于 ASCII 字符。它不能很好地处理 UTF-8。因此,Apache 和 mod_wsgi 都不适用于 UTF 8。

解决方案

因此,在准备好整个 html 字符串后,您可以使用内置的 python 函数 - bytes() 对其进行类型转换。这需要一个字符串并给出一个字节字符串。

示例代码

html = "This "
html += "is the code"
html = bytes(html, encoding= 'utf-8')
response_header = [('Content-type', 'text/html')]
start_response(status, response_header)
yield html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2015-11-11
    • 2016-10-31
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多