
在构建基于 Eel 的 Web 应用时,经常会遇到需要在 Python 函数执行过程中更新前端界面的需求,例如显示图片。然而,如果 Python 函数执行时间过长,会导致前端界面阻塞,图片无法及时加载,直到 Python 函数执行完毕。为了解决这个问题,我们需要将耗时的 Python 函数异步执行,避免阻塞主线程。
问题的关键在于,Eel 的 eel.expose 装饰器将 Python 函数暴露给 JavaScript 调用,但默认情况下,JavaScript 对 Python 函数的调用是同步的。这意味着 JavaScript 代码会等待 Python 函数执行完毕才会继续执行。因此,当 generate() 函数调用 eel.set_image() 后,浏览器会等待 generate() 函数完全执行完毕,才会渲染 <img> 标签。
为了解决这个问题,我们需要将耗时的 Python 代码放入一个异步任务中执行。这样,generate() 函数可以立即返回,允许浏览器继续渲染页面,而异步任务会在后台执行,不会阻塞主线程。
Celery 是一个流行的 Python 异步任务队列。它可以将任务分发给多个 worker 执行,从而提高程序的并发能力和响应速度。
立即学习“Python免费学习笔记(深入)”;
1. 安装 Celery 和 Redis (或 RabbitMQ):
首先,需要安装 Celery 和一个消息代理,例如 Redis 或 RabbitMQ。Redis 通常更容易设置,因此我们这里使用 Redis 作为示例。
pip install celery redis
2. 创建 Celery 配置文件 (celeryconfig.py):
# celeryconfig.py broker_url = 'redis://localhost:6379/0' # Redis 连接 URL result_backend = 'redis://localhost:6379/0' # Redis 连接 URL task_serializer = 'json' result_serializer = 'json' accept_content = ['json'] timezone = 'Asia/Shanghai' # 设置时区,根据你的实际情况修改 enable_utc = True
3. 修改 Python 代码:
import eel
import celery
from celery import Celery
# 初始化 Celery
celery_app = Celery('my_app', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0')
celery_app.config_from_object('celeryconfig')
@celery_app.task
def long_running_task(source, keyword):
# code that takes a long time to execute 2
# 模拟耗时操作
import time
time.sleep(5)
print(f"Task completed with source: {source}, keyword: {keyword}")
return "Task completed"
@eel.expose
def generate(source, keyword):
eel.set_image() # 立即更新图片
long_running_task.delay(source, keyword) # 异步执行耗时任务
return "Image updated, task started in background"
@eel.expose
def set_image():
# This function doesn't need to do anything in Python anymore,
# as it's primarily handled by the Javascript code.
print("set_image called from javascript")
4. 修改 JavaScript 代码:
eel.expose(set_image);
function set_image() {
document.getElementById("zoom-animate").innerHTML = '<img src="temp.png">';
}
function generate() {
let source = document.getElementById("source").value;
let keyword = document.getElementById("keyword").value;
eel.generate(source, keyword).then(result => {
console.log(result); // 输出 "Image updated, task started in background"
});
}5. 启动 Celery worker:
在终端中运行以下命令来启动 Celery worker:
celery -A your_module worker -l info
将 your_module 替换为包含 Celery 应用的 Python 文件的名称。例如,如果你的 Python 文件名为 main.py,则命令为 celery -A main worker -l info。
解释:
通过使用 Celery 这样的异步任务队列,我们可以将耗时的 Python 代码放入后台执行,避免阻塞前端界面,从而提高 Web 应用的响应速度和用户体验。这种方法特别适用于需要在 Python 函数执行过程中更新前端界面的场景,例如显示进度条、加载图片等。
以上就是使用 Eel 和 Python 在 Web 前端异步加载图片的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号