Hiro
Hiro

Reputation: 31

GAE counting visitors using cookie

This codes count the number of time we have visited the page, until browser is closed, using cookies. Which I am not getting. Please help

class MainPage(Handler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        visits = self.request.cookies.get('visits','0')
        if visits.isdigit():
            visits = int(visits) + 1
        else:
            visits= 0  

        self.response.headers.add_header('Set-Cookie', 'visits=%s' %visits)
        self.write("you've been here %s times" %visits)

I just want to know what is happening in these two lines

visits = self.request.cookies.get('visits','0')

and

self.response.headers.add_header('Set-Cookie', 'visits=%s' %visits)

Upvotes: 0

Views: 87

Answers (2)

Hiro
Hiro

Reputation: 31

Now I understand these two lines:

visits = self.request.cookies.get('visits','0')
  • self.request= requesting from the browser
    • self.request.cookies = requesting cookies[basically a dictionary] from the browser
    • self.request.cookies.get('visits')= looking for cookie whose key is visits
    • self.request.cookies.get("visits",0)= if key not found make this key value 0 and return
    • so now visits in LHS equals to 0 , as for now cookies not contain visits cookie

self.response.headers.add_header('Set-Cookie', 'visits=%s' %visits)

  • self.response= sending from the server to browser
    • self.response.headers.add_header('Set-Cookie', 'visits=%s' %visits)=adding cookie to header as it is defined in header, and setting visits in the cookie

Upvotes: 0

minou
minou

Reputation: 16563

Rather than just give you the answer, I'll help you figure out how to get it.

self.request and self.response are properties of the MainPage class. To figure out what these two things are doing you need to find out where they were defined.

The MainPage class is a subclass of the Handler class. You don't show the definition of the Handler class but somewhere in your code you will find that it is a subclass of webapp2.RequestHandler.

To find what the two lines in your code are doing, you should go read the online documentation for webapp2.

Upvotes: 1

Related Questions