0

I'm trying to find a way, to shut down a Python webserver after a certain number of accesses/downloads. I simply run a Python webserver with the following code:

import http.server, socketserver

port = 8800
handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", port), handler)
httpd.serve_forever()

I want to stop serving, after a certain number of downloads/file-accesses have been reached.

A single file access is usually logged as:

192.168.0.1- - [01/Jan/1970 00:00:00] "GET /file.txt HTTP/1.1" 200 -

Is there a way to directly parse the logs of the webserver and react accordingly?

For instance, if a certain number of occurrences of "GET .* 200 -have been reached, stop serving.

4
  • Well, you can subclass http.server.SimpleHTTPRequestHandler and make the derived class do whatever you want with the requests. Commented Oct 25, 2017 at 14:18
  • Hi @SaAtomic, do you need inner-python solution? or could be an external one, let's say, in unix-like bash scripting? Commented Oct 25, 2017 at 14:21
  • You could extend the server to do what you want. Commented Oct 25, 2017 at 14:21
  • @RafaelAguilar I'd prefer Python, but I'm open for suggestions. How would you accomplish this in bash? Commented Oct 26, 2017 at 5:27

1 Answer 1

1

You could count the number of requests and exit the http server after a specific amount is reached. This is a very basic example how it could work:

import http.server, socketserver
import sys

def shutdown(fn):
    def wrapper(*args, **kw):
        cls = args[0]

        if cls.count > 5:
            print ("shutting down server")
            sys.exit(0) 
        else:
            return fn(*args,**kw)
    return wrapper


class myHandler(http.server.SimpleHTTPRequestHandler):
    count = 0

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    @shutdown
    def do_GET(self, *args, **kwargs):
        myHandler.count += 1
        super().do_GET(*args, **kwargs)

    @shutdown
    def do_POST(self, *args, **kwargs):
        self.count += 1
        super().do_POST(*args, **kwargs)


port = 8800
handler = myHandler
httpd = socketserver.TCPServer(("", port), handler)
httpd.serve_forever()
Sign up to request clarification or add additional context in comments.

2 Comments

needs some fine-tuning, as the shutdown doesn't work right now - but I can definitely use this as for my project! thank you very much!
The exit function does not work, as it simply raises a SystemExit exception and doesn't know what to do with it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.