'How to Cache API once per 15 minutes
OK, I've been looking at caching examples and not sure how to put this together for my Flask Python Application
I have an object that handles the API request, this is market_data.py
I have a main.py this contains my flask app|
What I would like to do is the following:
When the home page is loaded it will check if a cache is available of the API call from market_data.py
If the home_page has a cache that is less than 15minutes old I want the flask app to render_template using the cache.
IF the cache is older than 15mins I want the home_page to render_template using a new API request.
MarketData.py handles the API request and sends the data to main.py to be rendered by flask for the index.html
Should I cache in the main.py or in the MarketData.py
I'm having trouble understanding how caching works... thank you in advanced
main.py
from flask import Flask, render_template
from flask_caching import Cache
from flask_bootstrap import Bootstrap
from flask_ckeditor import CKEditor
from datetime import date
from market_data import MarketData
import os
current_year = date.today().year
data = MarketData()
cache = Cache(config={'CACHE_TYPE': 'SimpleCache'})
app = Flask(__name__)
cache.init_app(app)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
ckeditor = CKEditor(app)
Bootstrap(app)
@app.route('/', methods=['GET', 'POST'])
@cache.cached(timeout=50)
def home_page():
data.get_data()
return render_template("index.html",
year=current_year,
count="{:,.0f}".format(data.total_active),
total="{:,.2f}".format(data.total_market_cap),
per_symbool="{:,.2f}".format(cdata.value_per_ticker),
per_all_ticker="{:,.2f}".format(cdata.value_per_all_asset),
new_asset="{:,}".format(data.total_active),
country="{:,.2f}".format(country),
all_value="{:,}".format(data.total_value),
time_stamp = data.time_stamp
)
if __name__ == "__main__":
app.run(debug=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
