http server that counts requests

Question:

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

Asked By: kfir648

||

Answers:

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()
Answered By: Xiddoc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.