Home Ask Login Register

Developers Planet

Your answer is one click away!

wbruntra February 2016

Creating restricted pages in google app engine

I'm having trouble creating admin pages on my Python Google App Engine site. I think the answer should be pretty straightforward, but honestly, I've been trying to understand how classes inheriting from other classes, or using functions to wrap other functions, and I just can't seem to get a good understanding of it.

Basically, my site has two kinds of pages: the main page, and then some pages that allow the user to perform admin actions. The main page can be seen by anyone without signing in. The other pages are for admins. The only users with accounts are admins, so I've set up webapp2 sessions, and as long as


returns something that's enough to be allowed access to the other pages.

Here are my handlers:

class BaseHandler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render(self, template, **kw):
        self.response.out.write(render_str(template, **kw))

    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

            # Dispatch the request.
            # Save all sessions.

    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

class MainHandler(BaseHandler):
    def get(self):
        animals = Animal.query().fetch(100)

class AdminHandler(BaseHandler):
    def get(self):
        if self.session.get('username'):

class ReorderHandler(BaseHandler):
    def get(self):
    def post(self):


Brent Washburne February 2016

Here's a brute-force way to ensure a user is logged in for every page (except the login page), or it redirects them to the login page:

def dispatch(self):
    # Get a session store for this request.
    self.session_store = sessions.get_store(request=self.request)

    if not self.session['username'] and self.request.get('path') != '/login':
        return redirect('/login')

A better way is to add this code to the top of every get() and put() routine:

def get(self):
    if not self.session['username']:
        return redirect('/login')

An even better way is to turn that code into a decorator so all you need to add is one line:

def get(self):

Post Status

Asked in February 2016
Viewed 3,826 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life