在Flask应用程序中设置python仪表板

时间:2018-08-21 10:07:17

标签: python-3.x flask web-applications dashboard

我正在尝试建立一个网站,允许人们在破折号应用程序中访问各种图形。我希望用户使用用户名和密码登录,然后才能访问仪表板。到目前为止,这就是我所拥有的

from flask import Flask, flash, render_template, request, session
import os, dash
import dash_html_components as html
import dash_core_components as dcc
import flask

app = Flask(__name__)
dash_app = dash.Dash(__name__, server=app, url_base_pathname='/dash_app')
dash_app.config['suppress_callback_exceptions']=True

def index_page():
    index = html.Div([
        dcc.Link('Page 1', href='/page1'),
        html.Br(),
        dcc.Link('Page 2', href='/page2'),
        html.Br(),
        dcc.Link('Page 3', href='/page3'),
        html.Br()
    ])
    return index

dash_app.layout = html.Div(children=[
    dcc.Location(id='url', refresh=False),
    html.Div(id = 'page-content')
])

page_1 = html.Div([
    html.H1('Welcome to page 1'),
    index_page()
])

page_2 = html.Div([
    html.H1('Welcome to page 2'),
    index_page()
])

page_3 = html.Div([
    html.H1('Welcome to page 3'),
    index_page()
])

@dash_app.callback(
    dash.dependencies.Output('page-content','children'),
    [dash.dependencies.Input('url','pathname')]
)
def display_page(pathname):
    if pathname == '/page1':
        return page_1
    if pathname == '/page2':
        return page_2
    if pathname == '/page3':
        return page_3
    else:
        return index_page()

@app.route('/')
def home():
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        return flask.redirect('/dash_app')


@app.route('/login', methods=['POST'])
def do_admin_login():
    if request.form['password'] == 'password' and request.form['username'] == 'admin':
        session['logged_in'] = True
    else:
        flash('wrong password!')
    return home()

if __name__ == "__main__":
    app.secret_key = os.urandom(12)
    app.run(debug=True, port=5000)

我要解决两个问题:

  • 使用此设置,您无需登录即可访问仪表板。如果直接输入http://localhost:5000/dash_app(而不是输入用户名和密码),则可以立即看到仪表板。我只想授予已登录人员的访问权限。

  • 如果刷新浏览器页面,则在单​​击三个页面链接之一后,会收到一条消息,提示“未找到”:enter image description here我不明白为什么会这样,感觉对我来说,这与应用程序的结构有关。

问题:如何解决这两个问题?而且,更普遍地;这种结构是否符合我要实现的目标?这是在Flask应用程序中设置仪表板的正确方法吗? (我知道此登录设置不安全)

编辑:关于刷新问题,我确信这与在flask应用程序中运行的dash应用程序有关,因为当我自己运行dash应用程序时,我可以刷新{ {3}},并且渲染成功。

1 个答案:

答案 0 :(得分:-1)

您应该使用flask-security而不是构建自己的登录机制,它可以解决很多问题,例如注册,登录,注销,忘记密码等。