試圖按照本教程製作一個wsgi服務器Let's Build a Web Server. 但是在python 3.5.2中使用下面的代碼獲取錯誤TypeError: initial_value must be str or None, not bytes
。在Python 3.5.2中輸入錯誤
import io
env['wsgi.input'] = io.StringIO(self.request_data)
我該如何解決這個問題。提前致謝。
試圖按照本教程製作一個wsgi服務器Let's Build a Web Server. 但是在python 3.5.2中使用下面的代碼獲取錯誤TypeError: initial_value must be str or None, not bytes
。在Python 3.5.2中輸入錯誤
import io
env['wsgi.input'] = io.StringIO(self.request_data)
我該如何解決這個問題。提前致謝。
變化import StringIO
到import io
變化request_line=request_line.rstrip('\r\n')
到request_line=request_line.rstrip(b'\r\n')
變化env['wsgi.input']=StringIO.StringIO(self.request_data)
到env['wsgi.input'] = io.BytesIO(self.request_data)
變化self.client_connection.sendall(response)
到self.client_connection.sendall(response.encode())
希望現在工作得很好。
首先,該教程使用python2,所以你可以,如果你想直接將其應用到python3
根據PEP3333(更新python3 WSGI規範)遇到其他問題的wsgi.input
environ variable應該是一個字節流,而不是文本流,因此您應該使用io.BytesIO()
,而不是io.StringIO
。
您目前收到的錯誤是因爲您的self.request_data
是bytes
,但是io.StringIO()
要求其參數爲str
。