How to merge Flask login with a Dash application?

二次信任 提交于 2020-06-10 03:57:33

问题


I have to design a web-app that provides Flask services and Dash services. For example I would like to create a login in Flask, combined with a Dash application. The problem is that I can't bind the flask login with dash. I would need a method like '@require_login' that filters access to even Dash services. The code is as follows:

app_flask = Flask(__name__)

app_flask.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////login.db'
app_flask.config['SECRET_KEY'] = 'thisissecret'

db = SQLAlchemy(app_flask)
login_manager = LoginManager()
login_manager.init_app(app_flask)

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(30), unique=True)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app_flask.route('/')
def index():
    user = User.query.filter_by(username='admin').first()
    login_user(user)
    return 'You are now logged in!'

@app_flask.route('/logout')
@login_required
def logout():
    logout_user()
    return 'You are now logged out!'

@app_flask.route('/home')
@login_required
def home():
    return 'The current FLASK user is ' + current_user.username

# TODO how to add login_required for dash? 
app_dash = Dash(server=app_flask, url_base_pathname='/dash/')
app_dash.layout = html.H1('MY DASH APP')


if __name__ == '__main__':
    app_dash.run_server(debug=True)

回答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.


回答2:


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')



来源:https://stackoverflow.com/questions/52286507/how-to-merge-flask-login-with-a-dash-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!