当前位置: 首页 > web >正文

Django【应用 01】django-plotly-dash安装及使用

django-plotly-dash 的使用文档:https://django-plotly-dash.readthedocs.io/en/stable/introduction.html 以下内容大部分保留原文档的内容,添加实际的步骤和必要的说明。

django-plotly-dash安装及使用

  • 1.安装配置
    • 1.1 安装
    • 1.2 注册组件
    • 1.3 配置框架
    • 1.4 注册路由
    • 1.5 更新数据库
    • 1.6 Note
  • 2.Simple usage
  • 3.效果

1.安装配置

The package requires version 3.2 or greater of Django, and a minimum Python version needed of 3.8. 这句话很重要,Django 的版本不能低于3.2 Python 的版本不能低于 3.8。这就导致之前的 Dockerfile无法使用了:

FROM python:3.7-slim-stretch
WORKDIR /app
COPY requirements.txt ./
RUN pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
COPY . .
EXPOSE 8086
CMD python manage.py runserver 0.0.0.0:8086

1.1 安装

Use pip to install the package, preferably to a local virtualenv:

pip install django_plotly_dash

实测使用 conda无法进行安装,之前安装过 Django 在安装 django_plotly_dash 时卸载了旧版本,安装了新版本:

Installing collected packages: dpd-components, Django, channels, dash-bootstrap-components, django_plotly_dashAttempting uninstall: DjangoFound existing installation: Django 3.2.12Uninstalling Django-3.2.12:Successfully uninstalled Django-3.2.12
Successfully installed Django-4.2.20 channels-4.2.2 dash-bootstrap-components-1.7.1 django_plotly_dash-2.4.5 dpd-components-0.1.0

项目的 repuirements.txt文件修改为:

django==4.2.20
django_plotly_dash==2.4.5
ngender==0.1.1
networkx==2.4.0

1.2 注册组件

Then, add django_plotly_dash to INSTALLED_APPS in the Django settings.py file:

INSTALLED_APPS = [...'django_plotly_dash.apps.DjangoPlotlyDashConfig',
...
]
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','django_plotly_dash.apps.DjangoPlotlyDashConfig'
]

The project directory name django_plotly_dash can also be used on its own if preferred, but this will stop the use of readable application names in the Django admin interface.

1.3 配置框架

Also, enable the use of frames within HTML documents by also adding to the settings.py file:

X_FRAME_OPTIONS = 'SAMEORIGIN'

Further, if the header and footer tags are in use then django_plotly_dash.middleware.BaseMiddleware should be added to MIDDLEWARE in the same file. This can be safely added now even if not used.

此外,如果使用了页眉和页脚标签,那么django_plotly_dash.middleware。BaseMiddleware应该在同一个文件中添加到MIDDLEWARE中。即使不使用,现在也可以安全地添加。

If assets are being served locally through the use of the global serve_locally or on a per-app basis, then django_plotly_dash.middleware.ExternalRedirectionMiddleware should be added, along with the whitenoise package whose middleware should also be added as per the instructions for that package. In addition, dpd_static_support should be added to the INSTALLED_APPS setting.

如果资产是通过使用全局server_local或基于每个应用在本地提供的,那么django_plotly_dash.middleware。应该添加ExternalRedirectionMiddleware,以及whitenoise包,该包的中间件也应该按照该包的说明添加。此外,应该将dpd_static_support添加到INSTALLED_APPS设置中。

Django 也只是入门会用,所以这部分我是不太懂的。

1.4 注册路由

The application’s routes need to be registered within the routing structure by an appropriate include statement in a urls.py file:

urlpatterns = [...path('django_plotly_dash/', include('django_plotly_dash.urls')),
]

The name within the URL is not important and can be changed.

1.5 更新数据库

For the final installation step, a migration is needed to update the database:

./manage.py migrate
Operations to perform:Apply all migrations: admin, auth, contenttypes, django_dash_demo, django_plotly_dash, sessions
Running migrations:Applying django_plotly_dash.0001_initial... OKApplying django_plotly_dash.0002_add_examples... OK

数据库会添加两张表:

  • django_plotly_dash_dashapp
  • django_plotly_dash_statelessapp

It is important to ensure that any applications are registered using the DjangoDash class. This means that any python module containing the registration code has to be known to Django and loaded at the appropriate time.

确保所有应用程序都是使用django类注册的,这一点很重要。这意味着Django必须知道任何包含注册码的python模块,并在适当的时候加载。

1.6 Note

An easy way to register the Plotly app is to import it into views.py or urls.py as in the following example, which assumes the plotly_app module (plotly_app.py) is located in the same folder as views.py:

``from . import plotly_app``

Once your Plotly app is registered, plotly_app tag in the plotly_dash tag library can then be used to render it as a dash component. See Simple usage for a simple example.

安装步骤的 Extra steps for live stateFurther configuration用到的时候再进行说明。

2.Simple usage

To use existing dash applications, first register them using the DjangoDash class. This replaces the Dash class from the dash package.

使用 django_plotly_dash 要使用 DjangoDash 类来注册实例。

Taking a simple example inspired by the excellent getting started guide:

import dash
from dash import dcc, htmlfrom django_plotly_dash import DjangoDashapp = DjangoDash('SimpleExample')   # replaces dash.Dashapp.layout = html.Div([dcc.RadioItems(id='dropdown-color',options=[{'label': c, 'value': c.lower()} for c in ['Red', 'Green', 'Blue']],value='red'),html.Div(id='output-color'),dcc.RadioItems(id='dropdown-size',options=[{'label': i,'value': j} for i, j in [('L','large'), ('M','medium'), ('S','small')]],value='medium'),html.Div(id='output-size')])@app.callback(dash.dependencies.Output('output-color', 'children'),[dash.dependencies.Input('dropdown-color', 'value')])
def callback_color(dropdown_value):return "The selected color is %s." % dropdown_value@app.callback(dash.dependencies.Output('output-size', 'children'),[dash.dependencies.Input('dropdown-color', 'value'),dash.dependencies.Input('dropdown-size', 'value')])
def callback_size(dropdown_color, dropdown_size):return "The chosen T-shirt is a %s %s one." %(dropdown_size,dropdown_color)

我们看一个菜鸟上的实例,使用的是 dash.Dash进行实例化的:

import dash
from dash import dcc, html  # dcc 是 Dash 核心组件库,html 是 HTML 组件库# 创建一个 Dash 应用实例
app = dash.Dash(__name__)# 定义应用的布局
app.layout = html.Div(children=[# 添加一个标题html.H1(children='你好,Dash!'),# 添加一段描述文字html.Div(children='''Dash:一个用于 Python 的 Web 应用框架。'''),# 添加一个图表dcc.Graph(id='example-graph',  # 图表的 ID,用于回调函数figure={'data': [  # 图表的数据{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': '上海'},{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': '北京'},],'layout': {  # 图表的布局'title': 'Dash 数据可视化示例'  # 图表的标题}})
])# 运行应用
if __name__ == '__main__':app.run_server(debug=True)  # 启动应用,debug=True 表示开启调试模式

Note that the DjangoDash constructor requires a name to be specified. This name is then used to identify the dash app in templates:

{%load plotly_dash%}{%plotly_app name="SimpleExample"%}

Direct use in this manner, without any application state or use of live updating, is equivalent to inserting an iframe containing the URL of a Dash application.

Note

The registration code needs to be in a location that will be imported into the Django process before any model or template tag attempts to use it. The example Django application in the demo subdirectory achieves this through an import in the main urls.py file, but any views.py would also be sufficient.

3.效果

点击 Blue 和 S 显示:
在这里插入图片描述
点击 Red 和 M 显示:
在这里插入图片描述

http://www.xdnf.cn/news/1990.html

相关文章:

  • Java 设计模式心法之第22篇 - 备忘录 (Memento) - 捕获与恢复对象状态的“时光机”
  • 力扣-160.相交链表
  • 制作一款打飞机游戏23:编辑器ui
  • kafka与flume的整合、spark-streaming
  • Virtio 技术解析 | 框架、设备实现与实践指南
  • 【分布式系统中的“瑞士军刀”_ Zookeeper】一、Zookeeper 快速入门和核心概念
  • EasyRTC音视频实时通话嵌入式SDK,打造社交娱乐低延迟实时互动的新体验
  • Golang日志模块之xlog
  • 58、微服务保姆教程(一)
  • classfinal 修改过源码,支持jdk17 + spring boot 3.2.8
  • BGE-m3 和 BCE-Embedding 模型对比分析
  • 深度强化学习(DRL)实战:从AlphaGo到自动驾驶
  • 三串口进行试验
  • Golang | 倒排索引
  • 前端技术Ajax实战
  • 机器学习基础理论 - 判别模型 vs 生成模型
  • Kafka和其他组件的整合
  • 从零开始学习人工智能Day5-Python3 模块
  • 25%甘油(灭菌)保存菌液以及10%甘油(普通)保存蛋白的原理及操作-实验操作系列-010
  • 驱动开发硬核特训 · Day 21(下篇): 深入剖析 PCA9450 驱动如何接入 regulator 子系统
  • WordPress AI插件能自动写高质量文章吗,如何用AI提升网站流量
  • django.db.utils.OperationalError: (1050, “Table ‘你的表名‘ already exists“)
  • 第十四届蓝桥杯刷题——day20
  • 【大语言模型】大语言模型(LLMs)在工业缺陷检测领域的应用
  • NAT穿透
  • 59、微服务保姆教程(二)Nacos--- 微服务 注册中心 + 配置中心
  • Java知识日常巩固(三)
  • tkinter的窗口构建、原生组件放置和监测事件
  • 互联网实验室的质量管控痛点 质检LIMS系统在互联网企业的应用
  • [FPGA基础] DMA