I am using cache to reduce the resources to query from MySQL database. Currently, I set acche type as 'simple' but I am not sure is it the best way with Pythonanywhere MySQL. Or should use redis or memcached? Not familiar with database though.
Both abc and def will be call at the same time, will it be an issues?
from flask import Flask,jsonify,abort,make_response,request
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cache import Cache
from sqlalchemy import text
from collections import OrderedDict
import time
app = Flask(__name__)
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
username="vinus",
password="liverpoolfc",
hostname="vinus.mysql.pythonanywhere-services.com",
databasename="vinus$default",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
db = SQLAlchemy(app)
# define the cache config keys, remember that it can be done in a settings file
app.config['CACHE_TYPE'] = 'simple'
# register the cache instance and binds it on to your app
app.cache = Cache(app)
@app.route("/")
@app.cache.cached(timeout=300) # cache this view for 5 minutes
def cached_view():
return time.ctime()
@app.route('/abc', methods=['GET'])
@app.cache.cached(timeout=300)
def abc():
try:
#curs.execute("SELECT Trade AS trade,COUNT(*) AS count FROM ABC GROUP BY Trade")
call= db.session.execute("SELECT Market_sentiment,BUY_total,HOLD_total,SELL_total FROM KLSE")
col = ['Market_sentiment','BUY_total','HOLD_total','SELL_total']
d = call.fetchone()
#e = [OrderedDict(zip(col,t)) for t in d]
d1 = [OrderedDict(zip(col,d))]
except Exception:
return 'Error: unable to fetch items'
return jsonify({'Trade': d1})
@app.route('/def', methods=['GET'])
@app.cache.cached(timeout=300)
def abc():
try:
#curs.execute("SELECT Trade AS trade,COUNT(*) AS count FROM DEF GROUP BY Trade")
call= db.session.execute("SELECT Market_sentiment,BUY_total,HOLD_total,SELL_total FROM KLSE")
col = ['Market_sentiment','BUY_total','HOLD_total','SELL_total']
d = call.fetchone()
#e = [OrderedDict(zip(col,t)) for t in d]
d1 = [OrderedDict(zip(col,d))]
except Exception:
return 'Error: unable to fetch items'
return jsonify({'Trade': d1})