vendredi 5 février 2021

Creating a Delayed Response in a Python 2 HTTP Server

I'm creating a very simple HTTP server in python 2 for testing.

I would like to randomly delay by a fixed amount the reply to a GET request without closing the connection to the server or shutting down the server first.

Here is the current code I would like to modify:

# Only runs under Python 2

import BaseHTTPServer
import time
from datetime import datetime

class SimpleRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        print "incoming request: " + self.path
        self.wfile.write('HTTP-1.0 200 Okay\r\n\r\n')
        self.wfile.write(modes(self.path))

def run(server_class = BaseHTTPServer.HTTPServer,
    handler_class = SimpleRequestHandler):
    server_address = ('', 80)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

def modes(argument):
    # returns value based on time of day to simulate data
    curr_time = datetime.now()
    seconds = int(curr_time.strftime('%S'))

    if seconds < 20:
        return "reply1"
    elif seconds >= 20 and seconds < 40:
        return "reply2"
    else:
        return "reply3"

run ( )

The delay would be be added every, say, 3rd or 4th time a GET is received but when the delay times out, a properly formed response would be sent.

Thanks.

Aucun commentaire:

Enregistrer un commentaire