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
CodePudding user response:
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()