Szymon
Szymon

Reputation: 633

How to create refresh button upon user request for a long-time query?

I've a simple app written in the Flask microframework. The main page as follows:

@app.route("/")
def index():
   # ...
   # connect to the database
   # execute a query
   # retrieve a data
   # ...
   return render_template('index.html', out=data_from_the_database)

Above function produce a web page with data from the Oracle database. The problem is complex, long-time query which execution time taken about ~10-15 minutes on the database and almost 100% CPU time on the server.

I have an idea to resolve this problem:

  1. Every day at 2:00 AM, using cURL tool I want to open the main page, and
  2. Using the pickle module save data to a file, and
  3. Create "REFRESH" button on the page to manually refresh actual data from the database.

My main question is how to achieve the following two assumptions:

  1. When the user call the main page ("/") in the browser he/she get data from the file.
  2. When the user want to fresh data he/she presses the "REFRESH" button and the query is executed again.

Please give me some tips, ideas (or code) how to realize this?

Upvotes: 2

Views: 1319

Answers (1)

codegeek
codegeek

Reputation: 33309

You can just call the "REFRESH" part using POST (via a form). Something like the following:

@app.route("/", methods=['GET','POST'])
def index():

    if request.method == 'POST':
        # pull data from database
        # update the data file. If does not exist, then create it first time

    # Now, retrieve the data from the data file. This will always be called even with GET request

    data = <data from file>     

    # Return the data back to the client.    
    return render_template('index.html', out=data)

In the code above, you will doing 2 extra steps using POST. Step 1 will pull data from database and step 2 will update the data file that you have. If data file does not exist yet, it should be created in that step. Rest will be same.

In your index.html or template, just make sure you have the following form:

<form action= {{url_for('index')}} method='POST'>
<input type='submit' value="REFRESH'>
</form>
.....

Upvotes: 2

Related Questions