I would like to serve only limited amount of requests using python HTTPServer.
Here are a few things about my architecture: I have a client which goes to the server and asks for data. The server (pythonic HTTPServer) has a a list containing data. Each time the client asks for data it gets the next item in the list. I would like the server to stop whenever it has sent all the data in its list. The solution i've thought about is checking the number of data in list and serving only this number of times. I must note that there is only one client as I do it for testing purposes.
How do I implement it? I thought about raising an event when all the commands are sent so some thread will kill the server but maybe you have an easier way.
Thanks in advance
So you may want to refer this https://docs.python.org/2/library/basehttpserver.html#more-examples
You have to define your own keep_running()
condition. Below is my sample:
import BaseHTTPServer
httpd = BaseHTTPServer.HTTPServer(('', 8000), BaseHTTPServer.BaseHTTPRequestHandler)
mylist = range(10)
while mylist:
httpd.handle_request()
mylist.pop() # remove last item of `mylist`
When you run this code, it will listen on port 8000
. Each request you make to localhost:8000
will remove an item from mylist
. When mylist
is empty, this server will be terminated.