我试图找到一种方法,在一定数量的访问/下载后关闭Python网络服务器。 我只是使用以下代码运行Python Web服务器:
import http.server, socketserver port = 8800 handler = http.server.SimpleHTTPRequestHandler httpd = socketserver.TCPServer(("", port), handler) httpd.serve_forever()在达到一定数量的下载/文件访问后,我想停止投放。
单个文件访问通常记录为:
192.168.0.1- - [01/Jan/1970 00:00:00] "GET /file.txt HTTP/1.1" 200 -有没有办法直接解析Web服务器的日志并做出相应的反应?
例如,如果达到了一定次数的"GET .* 200 - ,请停止投放。
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.
最满意答案
您可以计算请求数,并在达到特定金额后退出http服务器。 这是一个非常基本的例子,它可以如何工作:
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()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()更多推荐
发布评论