gpt4 book ai didi

python - 如何将 Plotly dash 应用程序放在 protected 路线后面

转载 作者:行者123 更新时间:2023-12-03 17:13:19 24 4
gpt4 key购买 nike

我有一个 plotly dash 应用程序,我想将它放在受 JWT 保护的路线后面。我的最终目标是将其包含在单独路线上的 iframe 中,但我只希望用户能够在他们有访问 token 的情况下获取 dash 应用程序的 html。

我已重试在获取请求中返回应用程序本身。

应用程序.py

import dash
from flask import Flask, jsonify, request
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity
)

server = Flask(__name__)

server.config['JWT_SECRET_KEY'] = 'super-secret' # Change this!
jwt = JWTManager(server)

@server.route('/login', methods=['POST'])
def login():
if not request.is_json:
return jsonify({"msg": "Missing JSON in request"}), 400

username = request.json.get('username', None)
password = request.json.get('password', None)
if not username:
return jsonify({"msg": "Missing username parameter"}), 400
if not password:
return jsonify({"msg": "Missing password parameter"}), 400

if username != 'test' or password != 'test':
return jsonify({"msg": "Bad username or password"}), 401

# Identity can be any data that is json serializable
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token), 200

@server.route('/')
@jwt_required
def index():
return 'Hello world flask app'

app = dash.Dash(
__name__,
server=server,
routes_pathname_prefix='/'
)

app.config.suppress_callback_exceptions = True

索引.py

from app import app
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
from combination_1 import Combination
import callbacks

app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id="root_div")

])

@app.callback(
Output('root_div', 'children'),
[Input('url', 'pathname')]
)
def attatch_graphs(pathname):
return Combination(comb_id='comb_1').return_div()

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

最佳答案

我将分享一些我在研究这个问题时发现的资源:

  • Dash 提供 library named dash-auth ,您可以使用 pip install dash-auth 进行安装
  • 安装库后,您将能够使用 import dash_auth ,您会注意到 HTTP Basic Auth 的子模块, OAuth和“PlotlyAuth”。根据 from dash_auth.plotly_auth import deprecation_notice 中的文字,“PlotlyAuth”已被弃用
  • 此模块的源代码似乎是 https://github.com/plotly/dash-auth
  • 文档位于 https://dash.plotly.com/authentication促销页面位于 https://plotly.com/dash/authentication/
  • 据推测,JWT 可以使用 Flask 的 Response.set_cookie 进行集成. Here are details about that approach ,请注意作者使用rep.set_cookie('custom-auth-session', username)
  • Github 上有一个使用 Dash, Flask, and Flask-Login 的示例.此配置也存在于 separate StackOverflow question .但是,这个库 doesn't supports JWT .您可以使用 Flask-JWT-Extended 库实现类似的架构。
  • 关于python - 如何将 Plotly dash 应用程序放在 protected 路线后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57629586/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com