本文介绍了BasicHTTPServer,SimpleHTTPServer和并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在使用python,BasicHTTPServer和SimpleHTTPServer编写一个小型网络服务器进行测试。看来它一次处理一个请求。有没有办法让它更快一点,不搞乱太深?
基本上我的代码看起来像下面的,我想保持这个简单)。

I'm writing a small web server for testing purposes using python, BasicHTTPServer and SimpleHTTPServer. It looks like it's processing one request at a time. Is there any way to make it a little faster without messing around too deeply?Basicly my code looks as the following and I'd like to keep it this simple ;)

os.chdir(webroot)
httpd = BaseHTTPServer.HTTPServer(("", port), SimpleHTTPServer.SimpleHTTPRequestHandler)
print("Serving directory %s on port %i" %(webroot, port) )
try:
 httpd.serve_forever()
except KeyboardInterrupt:
 print("Server stopped.")


推荐答案

您可以使用:

import SocketServer
import BaseHTTPServer

class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    pass

这有它的限制,因为它不使用线程池,受限于GIT等,但它可以帮助一点(相对较少的努力)。请记住,请求将由多个线程同时提供,因此请确保在提供请求的过程中对全局/共享数据的访问(除非启动后此类数据不可变)完全锁定。

This has its limits as it doesn't use a thread pool, is limited by the GIT, etc, but it could help a little (with relatively little effort). Remember that requests will be served simultaneously by multiple threads, so be sure to put proper locking around accesses to global/shared data (unless such data's immutable after startup) done in the course of serving a request.

涵盖了相同的理由(特别是长度)。

This SO question covers the same ground (not particularly at length).

这篇关于BasicHTTPServer,SimpleHTTPServer和并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 12:18