BasicHTTPServer, SimpleHTTPServer and concurrency

依然范特西╮ 提交于 2019-12-04 03:43:46

问题


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.")

回答1:


You can make your own threading or forking class with a mixin inheritance from SocketServer:

import SocketServer
import BaseHTTPServer

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

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).




回答2:


You might also look at CherryPy -- it's pretty simple, too, and has multiple request threads with no additional effort. Although your needs may be modest now, CP has a lot of nice capabilities that may benefit you in the future.




回答3:


Depending on what your requirements are, another option might be to hook in Paste. Though, based on your example, it may be overkill. Something to keep in the toolbox.



来源:https://stackoverflow.com/questions/2455606/basichttpserver-simplehttpserver-and-concurrency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!