python - 如何在 Windows 中使用 Python BaseHttpRequestHandler 将图像传输到客户端?

标签 python windows http python-imaging-library basehttprequesthandler

我知道之前已经有人问过这个问题,例如这里:How do I serve image Content-types with Python BaseHTTPServerRequestHandler do_GET method? ,但是“将文件打开模式设置为二进制”的典型答案对我不起作用。

我正在使用 Windows。所有对文本数据(html、js、css)的请求都得到了满足,没有任何问题。图像和字体请求未正确满足。返回的响应总是包含大约 150 个字节(但实际上应该是大约 50k)。因此,我想基本上是空的响应,缺少图像和字体。到目前为止,我在 Linux 下使用相同的代码没有遇到任何问题:

content = open(content_path, 'rb')
...
self.send_response(200)
self.send_header('Content-type', 'image/jpeg')
self.end_headers()
self.wfile.write(content.read) 
content.close()  

我最初使用“打开”的默认模式,在阅读了对类似问题的回复后,我添加了二进制标志,以为它可以解决问题,但事实并非如此。也许这里有一些编码问题?同样,这在 Linux 下确实有效。这是打印到控制台的“内容”的值:

<open file [my_file_path], mode 'rb' at 0x02A9BA18> with mime-type image/jpeg

如果它是相关的,我可能还应该提到,在应用程序的早期,所有图像都已由 python PIL 库调整大小。感谢您的帮助。

最佳答案

您正在发送 read 方法的字符串表示。 而是通过附加 () 来调用 read 方法:

self.wfile.write(content.read()) 

如果文件很大,file.read() 会产生问题,因为read() 会将文件内容加载到内存中。为防止这种情况,请使用 shutil.copyfileobj :

import shutil

...

self.send_response(200)
self.send_header('Content-type', 'image/jpeg')
self.end_headers()
with open(content_path, 'rb') as content:
    shutil.copyfileobj(content, self.wfile)

关于python - 如何在 Windows 中使用 Python BaseHttpRequestHandler 将图像传输到客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18565582/

相关文章:

python - 防止运行 python 脚本的并发实例

windows - 等待事件是否会受到虚假唤醒的影响?

windows - 32 位 NSIS 是否可以启动 64 位程序?

python - 无法将字符串转换为 float : 'K5'

python - 鼠兔与 celery ,连接已关闭

c# - 使用 MVC 绑定(bind)来自 POST 正文的单个值

ios - 将 curl 命令转换为 iOS

iphone - 跨 View Controller 共享 NSOperationQueue?

python - 在 Python 的单词列表中查找三个单词

c++ - 使用WFP筛选器允许端口和IP对