본문 바로가기

대장간

파이썬(Python) Dash와 Flask 함께 사용하기

첫 번째: Dash 안에 Flask

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import flask

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server, external_stylesheets=external_stylesheets)

# Flask Route
@server.route('/hello')
def hello():
    return 'Hello, Flask Server!'

app.layout = html.Div([
    dcc.Input(id='my-id', value='initial value', type='text'),
    html.Div(id='my-div')
])

# Dash Callback
@app.callback(
    Output(component_id='my-div', component_property='children'),
    [Input(component_id='my-id', component_property='value')]
)
def update_output_div(input_value):
    return 'You\'ve entered "{}"'.format(input_value)


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

9번째, 10번째 줄과 같이 설정해주면, Dash 서버 안에서 Flask를 사용할 수 있다.

 

웹브라우저에서 127.0.0.1:8050 으로 접속하면 Dash Layout이 실행되고,

 

127.0.0.1:8050/hello로 접속하면 Flask Route가 실행되는 것을 확인 할 수 있다.

 

 

 

 

두 번째: Flask 안에 Dash

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import flask
import werkzeug
from werkzeug.serving import run_simple

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

server = flask.Flask(__name__)
dash_app1 = dash.Dash(__name__, server=server, url_base_pathname='/dashboard1/', external_stylesheets=external_stylesheets)
dash_app2 = dash.Dash(__name__, server=server, url_base_pathname='/dashboard2/', external_stylesheets=external_stylesheets)


# dash_app1 : Graph Dashboad
dash_app1.layout = html.Div(children=[
    html.H1(children='Hello Dash'),
    html.Div(children='''
        Dash: A web application framework for Python.
    '''),
    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
            ],
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
    )
])

# dash_app2 : Callback Input Output Dashboard
dash_app2.layout = html.Div([
    dcc.Input(id='my-id', value='initial value', type='text'),
    html.Div(id='my-div')
])

# Dash Callback for dash_app2
@dash_app2.callback(
    Output(component_id='my-div', component_property='children'),
    [Input(component_id='my-id', component_property='value')]
)
def update_output_div(input_value):
    return '(dash app2) You\'ve entered "{}"'.format(input_value)


# Flask Route
@server.route('/')
def index():
    return 'Index Main Page'

@server.route('/hello')
def hello():
    return 'Hello, Flask Server!'

@server.route('/dashboard1')
def render_dashboard1():
    return flask.redirect('/graph')

@server.route('/dashboard2')
def render_dashboard2():
    return flask.redirect('/ioForm')

app = werkzeug.DispatcherMiddleware(server, {
    '/graph': dash_app1.server,
    '/ioForm': dash_app2.server
})

run_simple('127.0.0.1', 8080, app, use_reloader=True, use_debugger=True)
# if __name__ == '__main__':
#     app.run_server(debug=True)

 

결과는 동영상으로!! 확인~~

 

더 많은 예시는 공식 홈페이지 참고!!

https://dash.plot.ly/integrating-dash