SaAtomic
SaAtomic

Reputation: 749

Shut Python webserver down after a defined number of accesses/downloads

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.

Upvotes: 0

Views: 148

Answers (1)

Maurice Meyer
Maurice Meyer

Reputation: 18136

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()

Upvotes: 1

Related Questions