Python basehttpserver not serving requests properly

 ̄綄美尐妖づ 提交于 2019-12-04 11:45:16

You have to understand that (modern) browsers try to optimize their browsing speed using different techniques, which is why you get different results on different browsers.

In your case, the technique that caused you trouble is concurrent HTTP/1.1 session setup: in order to utilize your bandwidth better, your browser is able to start several HTTP/1.1 sessions at the same time. This allows to retrieve multiple resources (e.g. images) simultaneously.

However, BaseHTTPServer is not threaded: as soon as your browser tries to open another connection, it will fail to do so because BaseHTTPServer is already blocked by the first session that's still open. The request will never reach the server and run into a timeout. This also means that only one user can access your service at a given time. Inconvenient? Aye, but help is here:

Threads! .. and python makes this one rather easy:

Derive a new class from HTTPServer using a MixIn from socketserver.

.

Example:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading

class Handler(BaseHTTPRequestHandler):

    def do_HEAD(self):
        pass

    def do_GET(self):
        pass


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """ This class allows to handle requests in separated threads.
        No further content needed, don't touch this. """

if __name__ == '__main__':
server = ThreadedHTTPServer(('localhost', 80), Handler)
print 'Starting server on port 80...'
server.serve_forever()

From now on, BaseHTTPServer is threaded and ready to serve multiple connections ( and therefore requests ) at the same time which will solve your problem.

Instead of the ThreadingMixIn, you can also use the ForkingMixIn in order to spawn another process instead of another thread.

all the best,

creo

Note that Python basehttpserver is a very basic HTTP server far to be perfect, but that's not your first issue.

What is happening if you put the two scripts at the end of the document just before the </body> tag? Does it help?

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