[Tutor] problem with python3.5 headfirst python 2nd ed chpt 10 test drive example decorator issues

peter peterrisley47 at gmail.com
Thu Sep 28 18:35:32 EDT 2017


I am on chapter 10 of headfirst python second edition. got most of the 
prior codes to work but am stuck on this one. I will add the 
simple_webapp.py which is a decorator enabled  and checker.py which is 
the decorator. when I go into 127.0.0.1:5000 and enter I get the correct 
response. 127.0.0.1:5000/page1 gets me 'you are not logged in' also correct.

'127.0.0.1:5000/login' returns 'you are now logged in'  which is correct 
but '127.0.0.1:5000/page1' after that should return 'this is page 1' but 
instead returns 'you are not logged in'.

When I login to page 1 the 'session['logged_in'] = True' should still be 
true but apparently it has not been passed to 'check_logged_in'.

I am stumped and do not know how to proceed to figure this out.

Here are the codes

Also they are attached to this email. I am hoping someone can show me 
the errors of my ways. hopefully it is something simple but I have gone 
over it a lot and think the code is correct.

Thank you for your attention and help.

Peter Risley

checker.py

from flask import session
from functools import wraps

def check_logged_in(func):
     @wraps(func)
     def wrapper(*args, **kwargs):
         if 'logged _in' in session:
             return func(*args, **kwargs)
         return 'You are not logged in.'
     return wrapper

simple_webapp.py

from flask import Flask, session
from checker import check_logged_in

"""this 'simple_webapp.py' , which pulls all of chp 10 code together. When
you need to restrict access to specific URLs, base your strategy on this 
webapp's mechanism.
This uses checker.py check_logged_in and which is a decorator function 
to do the work."""



app = Flask(__name__)

@app.route('/')
def hello() -> str:
     return 'Hello from the simple webapp.'


@app.route('/page1')
@check_logged_in
def page1():
     return 'this is page 1.'

@app.route('/page2')
@check_logged_in
def page2():
     return 'this is page 2.'

@app.route('/page3')
@check_logged_in
def page3():
     return 'this is page 3.'


@app.route('/login')
def do_login() -> str:
     session['logged_in'] = True
     return 'you are now logged in.'


@app.route('/logout')
def do_logout() -> str:
     session.pop('logged_in')
     return 'you are now logged out.'

app.secret_key = 'yes'

if __name__ == '__main__':
     app.run(debug=True)






More information about the Tutor mailing list