Python Forum

Full Version: Flask run function in background and auto refresh page
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to get a function to run in the background when accessing my flask application then update the content of the page when the function is completed. Could anyone give me some advice of how i can do this.

Here is an example of what i want to do:
app.py
from flask import Flask, render_template
from time import sleep
from random import random

app = Flask(__name__)

def dummy_function():
    sleep(5)
    return random()

@app.route('/')
def index():
    x = dummy_function() # run this i background and when it is done update the page

    return render_template('index.html', x=x) # I want this to render even if the dummy function isn't done

if __name__ == '__main__':
    app.run(debug=True)
index.html
<html>
    <body>
        <p>x is {{ x }}</p>
    </body>
</html>
One thing to look at would be AJAX, e.g. https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX. I'm sure there are other good sources of information.
Can look at my post here .

Can give a example for me one that is best tool i have seen in years for web-development htmx.
I really simplify stuff like AJAX, CSS Transitions, WebSockets and Server Sent Events,bye doing all this inside the html.
htmx it's a prefect fit for Flask as can keep the simplicity.

Can make a little project also show APScheduler and Bulma.
BackgroundScheduler is good because it run in a thread automatically that will not interfere with long running stuff like web-server or eg GUI.
But can just comment it out here and code will work fine without it.

app.py
from flask import Flask, render_template, jsonify, request
from apscheduler.schedulers.background import BackgroundScheduler
import requests

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

def chuck():
    '''Return a Chuck Norris joke'''
    url = "https://api.chucknorris.io/jokes/random"
    response = requests.get(url)
    chuck_joke = response.json()["value"]
    return chuck_joke

@app.route("/joke")
def joke():
    joke = chuck() 
    return joke

if __name__ == "__main__":
    '''scheduler = BackgroundScheduler()
    scheduler.add_job(chuck, "interval", seconds=15)
    scheduler.start()
    '''
    app.run()
index.html
<!DOCTYPE html>
<html class="has-background-link-light">
<head>
  <title>Random joke</title>
  <script src="https://unpkg.com/[email protected]"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
</head>

<body>
  <section class="section">
    <div class="container">
      <div class="columns is-multiline is-centered">
        <div class="column is-8 has-text-centered">
          <h2 class="mt-2 mb-4 is-size-1 is-size-3-mobile has-text-weight-bold has-text-success-dark">
            Get a random Joke </h2>
          <p class="subtitle has-text-grey mb-5">Wait for a Joke or push button</p>
          <div class="buttons is-centered">
            <a class="button is-warning ml-4" hx-get="/joke" hx-target="#output_api">Get Joke</a>
            <p hidden hx-get="/joke" hx-target="#output_api" hx-trigger="every 15s">Chuck Joke</p>
          </div>
          <p id="output_api" class="subtitle has-text-grey mt-6"></p>
        </div>
      </div>
    </div>
  </section>
</body>
</html>
See no JavaScript,and this code dos AJAX bye push of button and also hx-trigger which dos auto polling(no reload of page) of joke every 15-sek from server.
[Image: s4RbTf.png]