1

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.

4
  • 3
    You can set attribute and then, use super() for inheritance: self.dummy_var = None super().__init__(*args, **kwargs) Commented Jun 12, 2020 at 17:08
  • Hi @Baris this indeed did resolve the AttributeError, so thanks a lot! Just another question: the counter (calc_value()) does not seem to work properly. Do you know if a class instance is created each time the request.get('...') in the second script is used? It seems for each request the init method of the RequestHandler Class is called.. Commented Jun 12, 2020 at 17:33
  • Hi @mulm, you're welcome. Unfortunately, I don't have an answer to this question. Commented Jun 12, 2020 at 17:43
  • 1
    You're pass the class , not an instance of it in the server = HTTPServer(('', port), RequestHandler) statement. Commented Jun 12, 2020 at 17:44

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.