我想運行一個簡單的「Hello World」使用mod_wsgi
爲Python 3.應用我使用的Fedora 23,這裏是我的Apache虛擬主機配置:類型錯誤:預期字節字符串值的順序,類型海峽的價值發現
<VirtualHost *:80>
ServerName localhost
ServerAdmin [email protected]
# 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 && sudo dnf install mod_wsgi -y && 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
您是否嘗試過編碼的字符串?例如:'status.encode()' – Rolbrok
[在Python 3下,WSGI應用程序必須返回一個字節字符串作爲變量'output'。它不能是一個Unicode對象或一些其它類型](http://stackoverflow.com/questions/31918319/python-3-4-mod-wsgi-get-syntaxerror-invalid-syntax-r#comment51750828_31918319)< - - 我沒有嘗試,有一段時間沒有在Apache中使用'mod_wsgi'。 –
@Rolbrok:我確實忘了提及。現在我得到'TypeError:預期的unicode對象,找到的類型字節的值'。 – Sumit