python - Default login_required rather than adding decorator everywhere -


i'm using flask-httpauth handle authentication in app. have lot of views, , don't want add login_required every 1 of them. how can make login required default?

from flask.ext.httpauth import httpbasicauth auth = httpbasicauth()  @auth.verify_password def verify_password(username, password):     return username == '111' , password == '222'  @app.route('/') @app.route('/home/') @auth.login_required def index():     return 'hello'  @app.route('/route2/') def route2():     return 'route2'  app.secret_key = 'a0zr98j/3yx r~xhh!jmn]lwx/,?rt' 

you can add before_request function require login default, , create simple login_exempt decorator few routes don't require it.

make sure exempt static files, otherwise won't load unauthenticated users.

flask-httpauth's login_required doesn't have way separate require logic view decorator, need go through little dance require auth without running view.

def login_exempt(f):     f.login_exempt = true     return f  # dummy callable execute login_required logic login_required_dummy_view = auth.login_required(lambda: none)  @app.before_request def default_login_required():     # exclude 404 errors , static routes     # uses split handle blueprint static routes     if not request.endpoint or request.endpoint.rsplit('.', 1)[-1] == 'static':         return       view = current_app.view_functions[request.endpoint]       if getattr(view, 'login_exempt', false):          return       return login_required_dummy_view()  # example, login page shouldn't require login @app.route('/login', methods=['get', 'post']) @login_exempt def login():     pass 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -