Is it possible to dynamically update a rendered template in Flask, server-side?

后端 未结 1 1689
悲&欢浪女
悲&欢浪女 2020-12-29 06:54

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

For example:

def get_data():
    response = r         


        
相关标签:
1条回答
  • 2020-12-29 07:12

    You're discussing what are perhaps two different issues.

    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.

    2. 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).

    0 讨论(0)
提交回复
热议问题