How To Merge Flask Login With A Dash Application?
Solution 1:
This line, app_dash = Dash(server=app_flask, url_base_pathname='/dash/')
, creates new view_functions
in app_flask
identified by its url_base_pathname
.
You can debug and inspect the value of app_flask.view_functions
before and after the creation of app_dash
.
Now that we know which view_functions
are created by app_dash
, we can apply login_required
to them manually.
for view_func in app_flask.view_functions:
if view_func.startswith(app_dash.url_base_pathname):
app_flask.view_functions[view_func] = login_required(app_flask.view_functions[view_func])
The `app_dash` endpoints will now be protected.Solution 2:
It would be better if you block all requests by using @app.before_request
, and only allow the request if logged in or if the endpoint is marked as public.
defcheck_route_access():
if request.endpoint isNone:
return redirect("/login")
func = app.view_functions[request.endpoint]
if (getattr(func, "is_public", False)):
return# Access granted# check if user is logged in (using session variable)
user = session.get("user", None)
ifnot user:
redirect("/login")
else:
return# Access granted```
Now all endpoints will be checked, even dash app endpoints.
Add this decorator named public_route
:
def public_route(function):
function.is_public = Truereturnfunction
And add the decorator to the public methods, like login, error pages etc.
@public_route@app.route("/login")
def login():
# show/handle login page
# call did_login(username) when somebody successfully logged in
def did_login(username):
session["user"] = username
This way you never need the @login_required
anymore because all endpoints require login unless stated otherwise by @public_route
.
Solution 3:
A solution : session from flask (work with cookie)
from flask import session
it's an exemple :
@login_manager.user_loader
def load_user(user_id):
# I think here it's good
session["uid"] = user_id
return User.query.get(int(user_id))
# TODO how to add login_required for dash?
if "uid" in session :
app_dash = Dash(server=app_flask, url_base_pathname='/dash/')
app_dash.layout = html.H1('MY DASH APP')
Post a Comment for "How To Merge Flask Login With A Dash Application?"