簡體   English   中英

在Python 3中通過wsgiref.simple_server提供JPG文件 - “write()參數必須是字節實例”

[英]Serving JPG files via wsgiref.simple_server in Python 3 - “write() argument must be a bytes instance”

我試圖在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文件。

我究竟做錯了什么?

將數據作為列表返回

return [data]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM