0

I am new to Python and I am trying to use Flask to build a simple REST-API. I want to count how many lists are recieved from post method. To make it simple, I have this situation:

#imports to use Flask and json...

myList = list ()
myInt = int()

class MyResource(Resource):
    def post(self):
        # Reciving JSON and parsing it to a list
        myList = json.loads(recivedJSON)
        myInt += 1
        # other method stuff...

While I can use myList without a single warning, when I try to increment myInt, appears the error:

Unresolved refercence 'myInt'

I tried to instatiate myInt inside MyResource and then calling it by self.myInt. In order to understand what is going on, I increment myInt and then print it.

#imports to use Flask and json... 

myList = list ()

class MyResource(Resource):
   myInt = int()

    def post(self):
        # Reciving JSON and parsing it to a list
        myList = json.loads(recivedJSON)
        self.myInt += 1
        print(self.myInt)
        # other method stuff...

In this way, the error doesn't show up but every time I invoke the post method, the print output of myInt is 1. It means that myInt is always 0 foreach post invoking.

How can I fix that ?

Wuagliono
  • 162
  • 1
  • 11

1 Answers1

2

Instantiate myInt inside MyResource is a good idea but you need to reference it as MyResource.myInt and not self.myInt.

The reason is that when you do self.myInt you actually create a new variable called myInt only available for this instance of MyResource class.

Viper
  • 405
  • 3
  • 11