简体   繁体   English

可以将 python -m http.server 配置为处理并发请求吗?

[英]Can python -m http.server be configured to handle concurrent requests?

I have a small demo page served with http.server.我有一个与 http.server 一起提供的小型演示页面。 I tried sharing with my coworkers but discovered that http.server remains blocked on any open connection, so concurrent users can't be served.我尝试与我的同事共享,但发现 http.server 在任何打开的连接上仍然被阻止,因此无法为并发用户提供服务。 Is there a way to run http.server to handle concurrent connections?有没有办法运行 http.server 来处理并发连接? I found nothing useful here: https://docs.python.org/3/library/http.server.html我在这里没有发现任何有用的信息: https://docs.python.org/3/library/http.server.html

IIRC there is no existing config option, but you could extend one with socketserver.ThreadingMixin if you like: IIRC没有现有的配置选项,但是如果您愿意,可以使用socketserver.ThreadingMixin扩展一个:

import sys
import socketserver
import http.server


class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True


port = int(sys.argv[1])
server = ThreadedHTTPServer(('', port), http.server.SimpleHTTPRequestHandler)
try:
    server.serve_forever()
except KeyboardInterrupt:
    pass

ps: there is a related python ticket . ps:有一个相关的python票证

You can now use ThreadingHTTPServer您现在可以使用ThreadingHTTPServer

class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass) class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass)

This class is identical to HTTPServer but uses threads to handle requests by using the ThreadingMixIn.此 class 与 HTTPServer 相同,但使用线程通过 ThreadingMixIn 处理请求。 This is useful to handle web browsers pre-opening sockets, on which HTTPServer would wait indefinitely.这对于处理 web 浏览器预打开 sockets 很有用,HTTPServer 将无限期等待。

New in version 3.7. 3.7 版中的新功能。

ThreadingHTTPServer does not handle concurrent requests from multiple browsers, but there is a workaround to do it by preventing HTTPServer from re-binding its socket every instance (answer by personal_cloud): streaming HTTP server supporting multiple connections on one port (You must fixup the imports, and append.encode() to every string argument to write().) ThreadingHTTPServer 不处理来自多个浏览器的并发请求,但有一种解决方法可以防止 HTTPServer 在每个实例中重新绑定其套接字(personal_cloud 回答):流式 HTTP 服务器支持一个端口上的多个连接(您必须修复导入, 和 append.encode() 到 write() 的每个字符串参数。)

Using that approach my Raspberry Pi 3B+ can stream its camera as a series of still JPEG images to 8 simultaneous browsers at 30 frames per second (same as it gets for 1 user).使用这种方法,我的 Raspberry Pi 3B+ 可以 stream 将其相机作为一系列静态 JPEG 图像以每秒 30 帧的速度传输到 8 个同时浏览器(与 1 个用户相同)。 This is essentially MJPEG, and is much lower latency (<< 1 second) than any video encoding.这本质上是 MJPEG,并且比任何视频编码都低得多的延迟(<< 1 秒)。 The camera uses ~70% of a core, and each stream adds ~2%;相机使用~70%的核心,每个stream增加~2%; 8 streams use ~2.5 MB/sec on the network. 8 个流在网络上使用约 2.5 MB/秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM