问题描述
在此模板中,我正在从API中检索比特币的价格。在实际的时候,价格只会在刷新页面时更新,而我希望无需更新即可动态更新整个页面。
In this template i'm retrieving the price of Bitcoin from an API. At the actual moment, the price will be updated only when the page is refreshed, while i would like it to be updated without refreshing the whole page, dynamically.
这是我的观点:
def home(request):
symbol = "BTCUSDT"
tst = client.get_ticker(symbol=symbol)
test = tst['lastPrice']
context={"test":test}
return render(request,
"main/home.html", context
)
模板的行如下所示:
<h3> var: {{test}} </h3>
这里有两个问题:
1)从我所了解的一点来看,Django本身不是异步的,因此我需要找到一种方法来实时更新模板的该部分,而不必刷新整个页面。
1) From the little i know, Django itself is not asynchronous, so i need to find a way to update that part of the template in real time, without having to refresh the whole page.
2)实际上,打开/刷新页面时需要API,但是要流传输价格,应该始终运行。我尝试了这个(糟糕的)解决方案:在视图中添加 while true
,但是当然它破坏了我的代码,只执行了while语句。
2) At the actual moment, the API is requested when the page is opened/refreshed, but to stream the price, it should be always running. I tried this (awful) solution: add a while true
in the view, but of course it broke my code, executing only the part the while statement.
任何建议都会感激:)
推荐答案
您应该按顺序分离前端和后端动态更新DOM内容而无需每次都渲染整个DOM。
You should separate your frontend and backend in order to dynamically update the DOM contents without needing to render the whole DOM each time.
前端的职责是在用户执行操作时请求并获取最新值保证刷新或获取更新的数据。该请求需要通过例如异步方式发出AJAX。较新的JS框架,例如React,Vue使用虚拟DOM,它们使用中间虚拟DOM来推动更新并最终一次更新真实DOM。
The responsibility of frontend would be to request and fetch the latest values when a user does an action that warrant a refresh or fetching of updated data. The request need to made asynchronously via e.g. AJAX. The newer JS frameworks e.g. React, Vue use virtual DOM that use an intermediate virtual DOM that they use to push the updates and finally update the real DOM in a single go; which makes them very performant.
(Django)后端应该公开一个API,该API会接收来自后端的(AJAX)请求以获取特定资源,并为它们提供服务。
The (Django) backend should expose an API that would take (AJAX) requests from backend for specific resources, and serve them.
DRF(Django REST框架)是Django的一个不错的框架,它公开了REST端点,您可以通过AJAX从前端调用它并获得响应,以便前端可以进行必要的更新。
A nice framework for Django is DRF (Django REST Framework), which exposes REST endpoints that you can call from frontend via AJAX and get reponse back so that the frontend can do necessary updates.
这是一个错误的高级视图,旨在为您提供一个想法,可以通过更深入地了解实现。
这篇关于如何实时更新Django模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!