I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please?
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler from time import sleep class ThreadingServer(ThreadingMixIn, HTTPServer): pass class RequestHandler(SimpleHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/plain') sleep(5) response = 'Slept for 5 seconds..' self.send_header('Content-length', len(response)) self.end_headers() self.wfile.write(response) ThreadingServer(('', 8000), RequestHandler).serve_forever()
A multithreaded server is any server that has more than one thread. Because a transport requires its own thread, multithreaded servers also have multiple transports. The number of thread-transport pairs that a server contains defines the number of requests that the server can handle in parallel.
Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading. However, Python does have a threading library. The GIL does not prevent threading.
Yes it can multi-thread, but generally one uses Celery to do the equivalent. You can read about how in the celery-django tutorial. It is rare that you actually want to force the user to wait for the website.
Apache HTTPD and nginx are the two common web servers used with python.
I have developed a PIP Utility called ComplexHTTPServer that is a multi-threaded version of SimpleHTTPServer.
To install it, all you need to do is:
pip install ComplexHTTPServer
Using it is as simple as:
python -m ComplexHTTPServer [PORT]
(By default, the port is 8000.)
Check this post from Doug Hellmann's blog.
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import threading class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() message = threading.currentThread().getName() self.wfile.write(message) self.wfile.write('\n') return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" if __name__ == '__main__': server = ThreadedHTTPServer(('localhost', 8080), Handler) print 'Starting server, use <Ctrl-C> to stop' server.serve_forever()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With