Forums

Reloading Flask html template

UPDATED: I'm testing new code so if you access my code or site now it won't show I'm mentioning below. Hopefully will get it work.

Hello,

I know this question been asked many times and I've done research and tried to get it working but still not able to.

I've the Always On Task "Running" the .py and have an html table to display variables on webpage. When I refresh the page using refresh on web browser, it shows the new content.

How can I, if it's possible, see updated content without hitting the refresh button?

I've tried scheduler, app.config["TEMPLATES-AUTO-RELOAD"] and a few other methods from Google and PA forums but none work.

I see PA team always asked before look into the code please feel free to do so.

Here's my page alanluong66.pythonanywhere.com . I've created a random number function for Pre-Close since you might access it when the stock market not opened. When you refresh the page, you will see a random number. How can I get it updated every x seconds without refreshing the page?

All help would be greatly appreciated

TEMPLATES_AUTO_RELOAD does not cause the page to be reloaded, it's about reloading templates that are changed on disk when using the Flask development server.

If you want your page to reload automatically, you can use the meta refresh tag: https://css-tricks.com/snippets/html/meta-refresh/

Thank you very much for your reply Glenn, I finally got it working using jquery setinterval to update value without refreshing the whole page.

But this is only for when I return 1 single variable. When I tried to return a list, the output was [object, Object] instead of real value.

I'm finding a way to convert it into real value and then using jquery to loop through it.

Would be greatly appreciated if you can give me some ideas.

It's hard to help without seeing the code -- you need to pass the data to a template context and parse them in your jquery script. Sometimes you might need to filter the data to be "visible" by JavaScript. The standard way, I suppose, is to provide data as a dictionary and filter them with tojson function in the template. It would look like:

In your Python code:

app.route('/')
def hello():
    data = {'key1': 'value1', 'key2': 123, 'key3': [9,8,7]}
    return render_template('template.html', data=data)

Somewhere in the template:

const contextData = {{data|tojson}}
// do stuff...

Thanks for your help, here's my .py

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


@app.route("/_data", methods=["GET", "POST"])
def get_data():
    gap_list = []
    response = requests.get(
    f'{url_base}{tickers}?apikey={api_key}'
)
response.raise_for_status()
json_data = response.json()
for detail in json_data:
    if detail['dayLow'] > 0: #detail['previousClose']:
        gap_dict = {
            "symbol": detail['symbol'],
            "price": detail['price'],
        }
    gap_list.append(gap_dict.copy())
return flask.json.dumps(gap_list)

And the .html

   <script type="text/javascript">
  const root_url = {{request.root_url|tojson|safe}};
  const intervalID = setInterval(update_values, 1000);

  function update_values() {
    $.getJSON(
      root_url + "_data",
      data => {
      var obj = JSON.stringify(data);
      $("#result").text(obj);
      }
    )
  }

</script>

The output

[{"price":1.3,"symbol":"CWBR"},{"price":3.1,"symbol":"DBGI"},{"price":4.77,"symbol":"DYAI"},{"price":1.12,"symbol":"ENVIW"},{"price":1.33,"symbol":"LITB"},{"price":3.76,"symbol":"ORLA"},{"price":2.59,"symbol":"PBIO"},{"price":2.08,"symbol":"PSTV"},{"price":3.6,"symbol":"PXLW"}]

So now I have the output as expected but it's just a string. How can I loop through it so I can display it as a table? I know it's Javascript question. I've google a lot but still haven't found the answer.

Thank you very much for your help,

I think you shouldn't stringify the data, you want it as a JS object rather than a string. When you have an object you can loop over it and put the values into relevant placeholders in html template table (you could use symbol fields to distinguish between placeholders).