Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

http server that counts requests

I am learning to use python to run an HTTP server and wanted to make a server that would count every time I refresh. I tried this:

from http.server import HTTPServer, BaseHTTPRequestHandler

count = 0

class HelloWorldRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        count = count + 1
        self.wfile.write(str.encode(count))

httpd = HTTPServer(("localhost",8000),HelloWorldRequestHandler)
httpd.serve_forever()

but I get an error that count doesn’t have a value.
help appriciated

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t assign to a global variable without using the global keyword:

from http.server import HTTPServer, BaseHTTPRequestHandler

count = 0

class HelloWorldRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        global count  # now you can modify/use it
        self.send_response(200)
        self.end_headers()
        count = count + 1
        self.wfile.write(str.encode(count))

httpd = HTTPServer(("localhost",8000),HelloWorldRequestHandler)
httpd.serve_forever()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading