Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - BaseHTTPServer keep alive does not work

I have the following code for a simple BaseHTTPServer based server.

class myHandler(BaseHTTPRequestHandler):
    #Handler for the GET requests
    def do_GET(self):
        # Parse the query_str
        query_str = self.path.strip().lower()
        if query_str.startswith("/download?"):
            query_str = query_str[10:]
            opts = urlparse.parse_qs(query_str)

            # Send the html message and download file
            self.protocol_version = 'HTTP/1.1'
            self.send_response(200)
            self.send_header("Content-type", 'text/html')
            self.send_header("Content-length", 1)
            self.end_headers()
            self.wfile.write("0")

            # Some code to do some processing
            # ...
            # -----------

            self.wfile.write("1")

I was expecting the HTML page to show "1", but it shows "0". How can I update the response through keep alive?

like image 439
Nitish Satyavolu Avatar asked Sep 15 '26 15:09

Nitish Satyavolu


2 Answers

I believe you are setting self.protocol_version to 'HTTP/1.1' too late. You are doing it in your do_GET() method, at which point your request handler has already been instantiated, and the server has already inspected that instance's protocol_version property.

Better to set it on the class:

class myHandler(BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'
like image 110
Martin Del Vecchio Avatar answered Sep 17 '26 03:09

Martin Del Vecchio


Not sure what you are trying to accomplish, but if you want the 1 to be sent, you need to set your content-length to 2 or remove it entirely. The 1 is not going to overwrite the 0, so you will see 01.

like image 37
doog abides Avatar answered Sep 17 '26 04:09

doog abides



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!