2016-01-17 46 views
4

我想運行一個簡單的「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 
+1

您是否嘗試過編碼的字符串?例如:'status.encode()' – Rolbrok

+0

[在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'。 –

+0

@Rolbrok:我確實忘了提及。現在我得到'TypeError:預期的unicode對象,找到的類型字節的值'。 – Sumit

回答

14

顯然變量output本身需要有一個字節的字符串,而不是一個Unicode字符串。它需要改變的不僅僅是爲response_headers,但對於到處output使用(所以str(len(output)).encode('utf-8')第6行是行不通的,就像我一直在努力)。

所以在我的情況的解決方案是:

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] 

(這是我在one of the tests官方回購的mod_wsgi發現,由Rolbrok的意見建議。)

+0

爲我工作謝謝! –

+0

這個讓我今晚成長了一些灰頭髮!在凌晨4點到達這裏之前,我偶然發現了這個解決方案。必須在大約3個小時內工作。只是想知道爲什麼這是必需的有沒有進一步的閱讀呢? –

+0

這也適用於我。謝謝! – gin93r

相關問題