我正在尝试在 Python3 中创建一个 HTTP 服务器。一开始,我只想要一个提供单个 JPG 文件的服务器。这是我的代码:
from wsgiref.simple_server import make_server
def simple_app(environ, start_response):
headers = [('Content-type', 'image/jpeg')]
start_response('200 OK', headers)
data = b''
filename = r'sunset-at-dusk.jpg'
with open(filename, 'rb', buffering=0) as f:
data = f.readall()
print(type(data)) #<class 'bytes'>
return data
httpd = make_server('', 8001, simple_app)
print("Serving on port 8001...")
httpd.serve_forever()
当我尝试通过 HTTP 访问服务器时,出现以下错误。
127.0.0.1 - - [01/Jun/2016 08:37:43] "GET / HTTP/1.1" 200 0 Traceback (most recent call last): File "C:\Anaconda3\lib\wsgiref\handlers.py", line 138, in run
self.finish_response() File "C:\Anaconda3\lib\wsgiref\handlers.py", line 180, in finish_response
self.write(data) File "C:\Anaconda3\lib\wsgiref\handlers.py", line 266, in write
"write() argument must be a bytes instance" AssertionError: write() argument must be a bytes instance
'sunset-at-dusk.jpg' 是与我的脚本位于同一文件夹中的有效 JPG 文件。
我究竟做错了什么?