是否可以在Flask服务器端动态更新渲染的模板? [英] Is it possible to dynamically update a rendered template in Flask, server-side?

查看:211
本文介绍了是否可以在Flask服务器端动态更新渲染的模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个Flask网络服务器,该服务器使用内置的requests对象从JSON API中提取数据.

I currently have a Flask web server that pulls data from a JSON API using the built-in requests object.

例如:

def get_data():
    response = requests.get("http://myhost/jsonapi")
    ...
    return response

@main.route("/", methods=["GET"])
def index():
    return render_template("index.html", response=response)

这里的问题是,自然地,GET方法仅在第一次调用get_data时运行一次.为了刷新数据,我必须停止并重新启动Flask wsgi服务器.我曾尝试在True/sleep循环中包装代码的各个部分,但这会阻止werkzeug加载页面.

The issue here is that naturally the GET method is only run once, the first time get_data is called. In order to refresh the data, I have to stop and restart the Flask wsgi server. I've tried wrapping various parts of the code in a while True / sleep loop but this prevents werkzeug from loading the page.

无需重新加载页面或重新启动服务器即可动态获取我想要的数据的最Python方式是什么?

What is the most Pythonic way to dynamically GET the data I want without having to reload the page or restart the server?

推荐答案

您正在讨论的可能是两个不同的问题.

You're discussing what are perhaps two different issues.

  1. 让我们假设问题是您只调用一次动态数据源get_data(),并将其(静态)值保留在全局response中.不会显示此一次调用,但可以说它在代码中的某个位置.然后,如果您愿意刷新页面(/)以获取更新,则可以:

  1. Let's assume the problem is you're calling the dynamic data source, get_data(), only once and keeping its (static) value in a global response. This one-time-call is not shown, but let's say it's somewhere in your code. Then, if you are willing to refresh the page (/) to get updates, you could then:

@main.route("/", methods=['GET'])
def index():
    return render_template("index.html", response=get_data())

这将在每次页面加载时获取新数据.

This would fetch fresh data on every page load.

然后在问题结尾处,您询问如何无需重新加载页面或重新启动服务器即可获取我想要的数据".那是一个完全不同的问题.您将必须在代码中使用AJAX或WebSocket请求.您可以通过谷歌搜索"Flask AJAX"找到很多有关如何执行此操作的教程(例如,本教程).但这需要JavaScript AJAX调用.我建议通过搜索"Flask AJAX jQuery"查找有关如何完成此操作的示例,因为jQuery将抽象化并简化您需要在客户端执行的操作.或者,如果您希望将WebSockets用于网页之间的低延迟连接,那也是可能的.搜索示例(例如像这样的).

Then toward the end of your question, you ask how to "GET the data I want without having to reload the page or restart the server." That is an entirely different issue. You will have to use AJAX or WebSocket requests in your code. There are quite a few tutorials about how to do this (e.g. this one) that you can find through Googling "Flask AJAX." But this will require an JavaScript AJAX call. I recommend finding examples of how this is done through searching "Flask AJAX jQuery" as jQuery will abstract and simplify what you need to do on the client side. Or, if you wish to use WebSockets for lower-latency connection between your web page, that is also possible; search for examples (e.g. like this one).

这篇关于是否可以在Flask服务器端动态更新渲染的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆