Python Forum
Flask run function in background and auto refresh page
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flask run function in background and auto refresh page
#1
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>
Reply
#2
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.
raossabe likes this post
Reply
#3
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]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  IndexError: list index out of range" & "TypeError: The view function f: Flask Web App joelbeater992 5 3,532 Aug-31-2021, 08:08 PM
Last Post: joelbeater992
  Reload flask current page GrahamL 2 5,152 Jan-08-2021, 08:31 AM
Last Post: GrahamL
  API auto-refresh on HTML page using Flask toc 2 11,883 Dec-23-2020, 02:00 PM
Last Post: toc
  how to pass javascript variables to url_for function in a flask template experimental 5 6,432 Oct-29-2020, 03:29 AM
Last Post: universe
  [Flask]After login page is not redirecting me to dashboard shockwave 0 2,717 May-07-2020, 05:22 PM
Last Post: shockwave
  Flask Create global response function to be called from every where in the web app umen 2 2,321 Apr-14-2020, 09:54 PM
Last Post: umen
  Flask - adding new page affects all other pages CMR 15 5,671 Mar-28-2020, 04:13 PM
Last Post: CMR
  use Xpath in Python :: libxml2 for a page-to-page skip-setting apollo 2 3,650 Mar-19-2020, 06:13 PM
Last Post: apollo
  flask-SQLAlchemy query with keyword as function argument pascale 2 3,504 Mar-13-2019, 08:45 PM
Last Post: Ecniv
  How do i scrape website whose page changes using javsacript _dopostback function and Prince_Bhatia 1 7,246 Aug-06-2018, 09:45 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020