解决:Python3 WSGI-AssertionError: write() argument must be a bytes instance

1.Problem Code:

 1 #!/usr/local/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 from wsgiref.simple_server import make_server
 5 
 6 def new():
 7     return '<html><head></head><body><h1 style="color:blue;">liuhonglei is so handsome</h1></body></html>'
 8 
 9 def index():
10     return '/index'
11 
12 URLS = {
13     "/new": new,
14     "/index": index
15 }
16 
17 def RunServer(environ, start_response):
18     start_response('200 OK', [('Content-Type', 'text/html')])
19     url = environ['PATH_INFO']
20     if url in URLS.keys():
21         func_name = URLS[url]
22         ret = func_name()
23     else:
24         ret = '404'
25     return ret
26 
27 if __name__ == '__main__':
28     httpd = make_server('', 8000, RunServer)
29     httpd.serve_forever()
Problem Code

2.Problem Desscription:

 1 127.0.0.1 - - [01/Jun/2020 22:32:51] "GET /new HTTP/1.1" 200 93
 2 Traceback (most recent call last):
 3   File "D:\software\python\python3InstallDocuments\lib\wsgiref\handlers.py", line 138, in run
 4     self.finish_response()
 5   File "D:\software\python\python3InstallDocuments\lib\wsgiref\handlers.py", line 184, in finish_response
 6     self.write(data)
 7   File "D:\software\python\python3InstallDocuments\lib\wsgiref\handlers.py", line 279, in write
 8     "write() argument must be a bytes instance"
 9 AssertionError: write() argument must be a bytes instance
10 127.0.0.1 - - [01/Jun/2020 22:32:51] "GET /favicon.ico HTTP/1.1" 500 59
Problem Description Code

3.Causation:

It's all because of WSGI is made for python 2, so you can face some troubles using it in python3. If you dont want to change library's behavior like in first answer, workaround is to encode all text data like:

1 def application(environ,start_response):
2     response_body = 'Hello World'
3     return [response_body.encode()]
Causation Code

4.Corrected Code:

 1 #!/usr/local/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 from wsgiref.simple_server import make_server
 5 
 6 
 7 def new():
 8     ret_str = '<html><head></head><body><h1 style="color:blue;">liuhonglei is so handsome</h1></body></html>'
 9     return [ret_str.encode('utf-8')]
10 
11 
12 def index():
13     ret_str = '/index'
14     return [ret_str.encode('utf-8')]
15 
16 
17 URLS = {
18     "/new": new,
19     "/index": index
20 }
21 
22 
23 def RunServer(environ, start_response):
24     start_response('200 OK', [('Content-Type', 'text/html')])
25     url = environ['PATH_INFO']
26     if url in URLS.keys():
27         func_name = URLS[url]
28         ret = func_name()
29     else:
30         ret = '404'.encode('utf-8')
31     return ret
32 
33 
34 if __name__ == '__main__':
35     httpd = make_server('', 8000, RunServer)
36     httpd.serve_forever()
Corrected Code

 

posted @ 2020-06-01 22:49  遥~  阅读(679)  评论(0编辑  收藏  举报