TypeError:需要字节字符串值序列,但找到类型为str的值

2022-05-08 00:00:00 python python-3.x mod-wsgi

问题描述

我正在尝试使用mod_wsgifor Python3运行一个简单的"Hello world"应用程序。我正在使用Fedora 23。以下是我的阿帕奇虚拟主机配置:

<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_wsgifor Python2(sudo dnf remove python3-mod_wsgi -y && sudo dnf install mod_wsgi -y && sudo apachectl restart),它工作得很好,但当我使用Python3时,我得到了一个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

unicode

显然,变量output本身需要具有字节字符串,而不是推荐答案字符串。它不仅需要为response_headers更改,也需要为使用的任何地方的更改(因此第6行的str(len(output)).encode('utf-8')不起作用,就像我一直在尝试的那样)。

所以在我的案例中,解决方案是:

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]

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

相关文章