Search code examples
python-3.xcachingflaskredisflask-cache

importing variable from main file to class variable


I have two files. One is a main python file. I am using flask where I am initializing a variable called cache using flask cache

from flask import *
from flask_compress import Compress
from flask_cors import CORS
from local_service_config import ServiceConfiguration
from service_handlers.organization_handler import *
import configparser
import argparse
import os
import redis
import ast
from flask_cache import Cache

app = flask.Flask(__name__)
config = None
configured_service_handlers = {}
app.app_config = None
ug = None


@app.route('/organizations', methods=['POST', 'GET'])
@app.route('/organizations/<id>', methods=['DELETE', 'GET', 'PUT'])
def organizations(id=None):
    try:
        pass
    except Exception as e:
        print(e)


def load_configuration():
    global config
    configfile = "jsonapi.cfg"  # same dir as this file

    parser = argparse.ArgumentParser(
    description='Interceptor for UG and backend services.')
    parser.add_argument('--config', required=True, help='name of config file')
    args = parser.parse_args()

    configfile = args.config
    print("Using {} as config file".format(configfile))
    config = configparser.ConfigParser()
    config.read(configfile)
    return config


if __name__ == "__main__":
     config = load_configuration()
     serviceconfig = ServiceConfiguration(config)
     serviceconfig.setup_services()
     ug = serviceconfig.ug
     cache = Cache(app, config={
         'CACHE_TYPE': 'redis',
         'CACHE_KEY_PREFIX': 'fcache',
         'CACHE_REDIS_HOST':'{}'.format(config.get('redis', 'host'),
         'CACHE_REDIS_PORT':'{}'.format(config.get('redis', 'port'),
         'CACHE_REDIS_URL': 'redis://{}:{}'.format(
             config.get('redis', 'host'),
             config.get('redis', 'port')
         )
     }) 

     # configure app
     port = 5065

     if config.has_option('service', 'port'):
         port = config.get('service', 'port')
     host = '0.0.0.0'
     if config.has_option('service', 'host'):
         host = config.get('service', 'host')
     app.config["port"] = port
     app.config["host"] = host
     app.config["APPLICATION_ROOT"] = 'app'
     app.run(port=port, host=host)

And one more handler which has a class

class OrganizationHandler(UsergridHandler):
    def __init__(self, config, test_ug=None):
        super(OrganizationHandler, self).__init__(config, ug=test_ug)

    @cache.memoize(60)
    def get_all_children_for_org(self, parent, all):
        try:
            temp = []
            children = self.ug.collect_entities(
                "/organizations/{}/connecting/parent/organizations".format(parent)
            )
            if not len(children):
                return
            for x in children:
                temp.append(x['uuid'])
            all += temp
            for each in temp:
                self.get_all_children_for_org(each, all)
            return all
        except Exception as e:
            print(e)

I want to import the cache variable defined in main function to be usable as @cache.memoize inside the class. How do I import that variable inside the class?


Solution

  • You can create your Cache instance in a separate module (fcache.py):

    from flask_cache import Cache
    
    cache = Cache()
    

    After that you can configure it in main file:

    from flask import Flask
    
    from fcache import cache
    
    app = Flask(__name__)
    cache.init_app(app, config={'CACHE_TYPE': 'redis'})
    

    Cache instance can be imported in other modules:

    from fcache import cache
    
    @cache.memoize(60)
    def get_value():
        return 'Value'
    

    This approach could be also used with other Flask extensions like Flask-SQLAlchemy.