Python全栈应用开发利器Dash 3.x新版本介绍(3)

更多Dash应用开发干货知识、案例,欢迎关注"玩转Dash"微信公众号👇

大家好我是费老师,在前两期文章中,我们针对Python生态中++强大++ 且++灵活++ 的全栈应用开发 框架Dash,介绍了其3.x新版本中的部分更新内容🧐:

而今天的文章中,我们将继续介绍Dash3.x新版本中的其他重磅💥新功能,今天要介绍的是新版本中对异步编程的新增支持。

Dash应用开发新增异步编程支持

3.1.0版本开始,得益于底层依赖的Flask当前对异步编程 较为稳定的支持,在Dash中我们可以编写异步函数形式的服务端回调函数 。终端执行下面的命令,即可完成额外异步依赖的安装:

bash 复制代码
pip install dash[async] -U

对于了解Python异步编程的朋友,可以将应用中相关的计算场景轻松改造为异步形式 ,从而大幅度降低计算耗时,下面我们举例演示:

异步形式的回调函数

针对服务端回调函数 场景,为了进行直观对比 ,我们先来看一个同步写法下的示例应用:

python 复制代码
import time
import dash
import random
from dash import html
import feffery_antd_components as fac
from dash.dependencies import Input, Output
from feffery_dash_utils.style_utils import style

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        fac.AntdSpace(
            [
                fac.AntdButton(
                    "执行计算",
                    id="execute",
                    type="primary",
                    loadingChildren="计算中",
                ),
                fac.AntdText(id="result"),
            ]
        )
    ],
    style=style(padding=50),
)


def job():
    time.sleep(1)

    return random.randint(0, 100)


@app.callback(
    Output("result", "children"),
    Input("execute", "nClicks"),
    running=[[Input("execute", "loading"), True, False]],
    prevent_initial_call=True,
)
def sync_callback_demo(nClicks):
    start = time.time()

    # 模拟耗时计算任务过程
    results = [job() for _ in range(5)]

    return f"本次计算结果:{results}, 计算耗时:{round(time.time() - start, 2)} 秒"


if __name__ == "__main__":
    app.run(debug=True)

在对应的回调函数sync_callback_demo()中,我们调用了5次 具有一定模拟计算耗时的job()函数,因此每次点击按钮执行计算后,都要耗时约5秒

而在3.1.0版本之后的Dash中,我们可以使用Python中的异步编程相关写法,编写异步形式的回调函数,与前面同步形式示例做对比,异步形式示例代码如下:

python 复制代码
import time
import dash
import random
import asyncio
from dash import html
import feffery_antd_components as fac
from dash.dependencies import Input, Output
from feffery_dash_utils.style_utils import style

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        fac.AntdSpace(
            [
                fac.AntdButton(
                    "执行计算",
                    id="execute",
                    type="primary",
                    loadingChildren="计算中",
                ),
                fac.AntdText(id="result"),
            ]
        )
    ],
    style=style(padding=50),
)


async def async_job():
    await asyncio.sleep(1)

    return random.randint(0, 100)


@app.callback(
    Output("result", "children"),
    Input("execute", "nClicks"),
    running=[[Input("execute", "loading"), True, False]],
    prevent_initial_call=True,
)
async def async_callback_demo(nClicks):
    start = time.time()

    # 模拟耗时计算任务过程
    coros = [async_job() for _ in range(5)]
    results = await asyncio.gather(*coros)

    return f"本次计算结果:{results}, 计算耗时:{round(time.time() - start, 2)} 秒"


if __name__ == "__main__":
    app.run(debug=True)

因为利用asyncio.gather()进行多个异步函数的整合执行,所以同样的计算操作,耗时得到有效降低,只需要约1秒

基于这项新特性,我们就可以在相关场景下进行有效的异步改造,从而提升计算效率⚡。

篇幅有限,更多新版本Dash更新相关内容,接下来的数篇文章我们继续为大家盘点,敬请期待~


以上就是本文的全部内容,对Dash应用开发感兴趣的朋友,欢迎添加微信号CNFeffery,备注"dash学习"加入我们的技术交流群,一起成长一起进步。

相关推荐
lipku1 小时前
数字人直播开源项目LiveStream
python·开源·数字人·数字人直播
阿童木写作1 小时前
Python实现亚马逊商品图批量智能抠图教程
人工智能·python
axinawang2 小时前
第24课:while循环的应用
python
三亚兴嘉装饰2 小时前
三亚服装店装修
python
小柯南敲键盘2 小时前
速卖通AI图片翻译API集成实战
人工智能·python
tqs_123453 小时前
Agent智能体+Skill插件引擎+Milvus混合检索 技术沉淀
java·python·milvus
眼泪划过的星空3 小时前
LangChain 两大基础提示词模板:PromptTemplate 与 ChatPromptTemplate 详解
人工智能·python·langchain
狗都不学爬虫_3 小时前
AI逆向 - 99aq中心滑块验证+登录(wasm纯算)
爬虫·python·网络爬虫
天才测试猿4 小时前
实例介绍:Unittest框架及自动化测试实现流程
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
veminhe4 小时前
元数据索引有关的错
人工智能·python