我一直在尝试从 Plolty Dash 开发一个多页模板应用程序。我正在尝试在成功登录时实现重定向。项目结构如下:
multipage
├── app.py
├── apps
│ ├── app1.py
│ ├── app2.py
│ ├── app3.py
├── index.py
└── static
└── base.css
我拥有的代码如下:
index.py(起点)
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from app import app, server
from apps import app1, app2, app3
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='page-content')
])
@app.callback(Output('page-content', 'children'),
[Input('url', 'pathname')])
def display_page(pathname):
if pathname == '/':
return app3.layout
else:
return '404'
if __name__ == '__main__':
server.run(debug=True)
在这里,当用户访问/
登录页面(app3.py)时将被渲染。
应用程序.py
import dash
import os
import flask
app = dash.Dash()
server = app.server
app.config.supress_callback_exceptions = True
external_css = [
'https://codepen.io/chriddyp/pen/bWLwgP.css',
'/static/base.css'
]
for css in external_css:
app.css.append_css({"external_url": css})
@app.server.route('/static/<path:path>')
def static_file(path):
static_folder = os.path.join(os.getcwd(), 'static')
return flask.send_from_directory(static_folder, path)
app2.py(登录代码)
import flask
from dash.dependencies import Input, Output, State, Event
import dash_html_components as html
import dash_core_components as dcc
from apps import app1
from app import app
layout = html.Div(children=[
# content
html.Div(id='login',children=[
html.H3("Please log in", hidden=False, id="page_header"),
# login form
html.Form(children=[
html.P(children=["Username: ", dcc.Input(type='text', id='username', placeholder='username')]),
html.P(children=["Password: ", dcc.Input(type='password', id='password', placeholder='password')]),
html.Button(children=['Login'], type='submit', id='login_button')
], style={'width': '30%', 'margin': '0 auto'}, id="login_form", hidden=False)
], style={'display': 'block', 'text-align': 'center', 'padding': 2}),
html.Br(),
html.Hr(style={'width': '30%'}),
])
@app.callback(Output('login', 'children'),
events=[Event('login_button', 'click')],
state=[State('username', 'value'), State('password', 'value')])
def login(username, password):
if username:
print("login")
return flask.redirect('/home')
else:
print("No Luck")
在函数login(username, password)
中,如果用户是有效的,那么应用程序应该重定向到/home
并且app1.py
必须在那里呈现。
我能够通过用户交互导航到各个页面。有没有一种方法可以让我从程序中重定向。我真的是新手,请帮助我。