cmrussell
cmrussell

Reputation: 2112

Flask Long Polling API

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

Answers (1)

Gasp0de
Gasp0de

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:

  1. Add <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.
  2. Add some javascript to your index.html which will poll your API endpoint and update your page when new information is available.
  3. Use websockets (this is similar to the pure javascript approach but potentially with less polling).

Upvotes: 0

Related Questions