I am aware such issues have been raised quite often already. Still, after reviewing plenty of threads I was not able to identify the issue.
#!/usr/bin/env python
# Reflects the requests with dummy responses from HTTP methods GET, POST, PUT, and DELETE
# Written by Tushar Dwivedi (2017)
import json
# from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import sys
sys.path.append(r'C:\Users\[...]')
from http.server import BaseHTTPRequestHandler,HTTPServer
from optparse import OptionParser
class RequestHandler(BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
self.dummy_var = None
def do_GET(self):
request_path = self.path
print("\n----- Request Start ----->\n")
print("request_path :", request_path)
print("self.headers :", self.headers)
print("<----- Request End -----\n")
self.send_response(200)
self.send_header("Set-Cookie", "foo=bar")
self.end_headers()
self.wfile.write(json.dumps({'value_1': str(self.calc_value()), 'value_2': '0'}).encode())
def calc_value(self):
if self.dummy_var is None:
self.dummy_var = 0
self.dummy_var = self.dummy_var + 1
return self.dummy_var
do_PUT = do_POST
do_DELETE = do_GET
def main():
port = 8000
print('Listening on localhost:%s' % port)
server = HTTPServer(('', port), RequestHandler)
server.serve_forever()
if __name__ == "__main__":
parser = OptionParser()
parser.usage = ("Creates an http-server that will echo out any GET or POST parameters, and respond with dummy data\n"
"Run:\n\n")
(options, args) = parser.parse_args()
main()
I am starting the server and making a request from a second script,
r = requests.get('http://localhost:8000').json()
Basic idea (for testing) is that each time the request is made, the dummy_var acts as a counter.
However, I get the following error:
File "C:\Users\[...]\http_server.py", line 60, in calc_value
if self.__dummy_var is None:
AttributeError: 'RequestHandler' object has no attribute 'dummy_var'
Any suggestions?
I did check the Indentation, but it seems to be all spaces, no tabs.
Since it's difficult to see the necessary changes from comments, I think it's worth sharing it here.
The solution is setting the attribute before calling __init__()
, and using super()
for cooperative inheritance. So, init method should be changed with the following lines:
def __init__(self, *args, **kwargs):
self.dummy_var = None
super().__init__(*args, **kwargs)