Reputation: 2112
I am trying to get a webpage to update from an API endpoint whenever that endpoint updates. Right now my webpage works if I refresh it but I want it to update automatically.
import json
import requests
from flask import Flask, render_template
app = Flask(__name__)
s = requests.session()
# API Key
s.headers.update({'Authorization': 'apikeygoeshere'})
@app.route("/")
def index():
alarms = s.get('https://site/api/alarms')
alarmData = json.loads(alarms.text)
if next in alarmData:
while alarmData['next']:
nextUrl = alarmData['next']['href']
print(nextUrl)
nextUrlGet = s.get(nextUrl)
nextData = json.loads(nextUrlGet.text)
alarmData = nextData
if not alarmData['next']:
break
else:
print('No Next -> Update Ready')
alarmUpdateUrl = alarmData['updates']['href']
update = s.get(alarmUpdateUrl)
updateData = json.loads(update.text)
if not updateData['updates']:
updateName = "Nothing"
else:
updateName = updateData['updates'][0]['source']['name']
alarmUpdateUrl = updateData['next']['href']
print(alarmUpdateUrl)
s.get(alarmUpdateUrl)
return render_template('index.html', data=updateName, url=alarmUpdateUrl)
if __name__ == '__main__':
app.run(debug=True, threaded=True)
I tried putting the code in a while loop but it didn't seem to restart. Esentially the endpoint may not have an updates url on page one so i have to follow the next link until there is an update href then request that to initiate a long poll.
Upvotes: 0
Views: 1263
Reputation: 1429
When you call an endpoint, Flask figures out which method to run, runs this method, and returns a response, in your case HTML. The connection between client (your browser) and server is then terminated and flask stops doing anything (more or less) until a new request comes in. If you want a website to refresh automatically, you have a few options, but all of them have to be implemented on the client side:
<meta http-equiv="refresh" content="30">
to your html head in index html. This will cause your browser to reload the page every 30 seconds.Upvotes: 0