is there any pool for ThreadingMixIn and ForkingMixIn for SocketServer?

陌路散爱 提交于 2019-12-04 06:01:18

You could use a pool from concurrent.futures (in stdlib since Python 3.2):

from BaseHTTPServer   import HTTPServer, test
from SimpleHTTPServer import SimpleHTTPRequestHandler
from SocketServer     import ThreadingMixIn

from concurrent.futures import ThreadPoolExecutor # pip install futures

class PoolMixIn(ThreadingMixIn):
    def process_request(self, request, client_address):
        self.pool.submit(self.process_request_thread, request, client_address)

def main():
    class PoolHTTPServer(PoolMixIn, HTTPServer):
        pool = ThreadPoolExecutor(max_workers=40)

    test(HandlerClass=SimpleHTTPRequestHandler, ServerClass=PoolHTTPServer)

if __name__=="__main__":
    main()

As you can see the implementation for a threading case is rather trivial.

If you save it to server.py then you could run it as:

$ python -mserver

This command uses upto 40 threads to serve requests on http://your_host:8000/.

The main use case of HTTPServer is for testing purposes.

I've started a project that solves this issue

https://github.com/muayyad-alsadi/python-PooledProcessMixIn

maybe you want to join me finish the TODOs (clean up after CTRL+C)

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