66import json
77import redis
88import pandas as pd
9+ import bmemcached
910
1011from flask import Flask
1112from flask import request
3940 sslify = SSLify (app )
4041
4142if app .config ['DEBUG' ]:
42- cache = Cache ( app , config = { 'CACHE_TYPE' : 'null' } )
43+ cache = bmemcached . Client ( servers = [ '127.0.0.1:11211' ] )
4344else :
44- cache = Cache (app , config = {
45- 'CACHE_TYPE' : 'memcached' ,
46- 'CACHE_MEMCACHED_SERVERS' : [ os .environ ['MEMCACHEDCLOUD_SERVERS' ] ],
47- 'CACHE_MEMCACHED_USERNAME' : os .environ ['MEMCACHEDCLOUD_USERNAME' ],
48- 'CACHE_MEMCACHED_PASSWORD' : os .environ ['MEMCACHEDCLOUD_PASSWORD' ]
49- })
50- app .logger .info ("Cache set to memcached:" )
51- app .logger .info (cache )
45+ cache = bmemcached .Client (
46+ servers = os .environ ['MEMCACHEDCLOUD_SERVERS' ].split ("," ),
47+ username = os .environ ['MEMCACHEDCLOUD_USERNAME' ],
48+ password = os .environ ['MEMCACHEDCLOUD_PASSWORD' ]
49+ )
5250
5351redis_conn = redis .StrictRedis .from_url (os .environ ['REDIS_URL' ])
5452
@@ -113,13 +111,19 @@ def mean_returns(asset_ids):
113111
114112 return df .drop (asset_ids_to_eliminate )
115113
116- @cache .memoize ()
117114def build_efficient_frontier_for (asset_ids ):
118- app .logger .info ("[Cache Miss] Building efficient frontier for: %s" % asset_ids )
119- means = mean_returns (asset_ids )
120- covars = covariance_matrix (asset_ids )
121- return efficient_frontier (asset_ids , means , covars )
122-
115+ cache_key = "efficient_frontier/" + "-" .join (asset_ids )
116+ val = cache .get (cache_key )
117+ if val is None :
118+ app .logger .info ("[Cache Miss] Building efficient frontier for: %s" % asset_ids )
119+ means = mean_returns (asset_ids )
120+ covars = covariance_matrix (asset_ids )
121+ frontier = efficient_frontier (asset_ids , means , covars )
122+ cache .set (cache_key , json .dumps (frontier ))
123+ else :
124+ app .logger .info ("[Cache Hit] Retreiving efficient frontier for: %s" % asset_ids )
125+ frontier = json .loads (val )
126+ return frontier
123127
124128##########
125129# ROUTES #
@@ -138,7 +142,7 @@ def health():
138142@app .route ('/clear_cache' , methods = ["GET" ])
139143def clear_cache ():
140144 check_for_authorization ()
141- cache .clear ()
145+ cache .flush_all ()
142146 return jsonify ({"success" : True , "message" : "Cache cleared." })
143147
144148
0 commit comments