我有两个文件。一个是主python文件。我正在使用flask,我正在使用flask cache
初始化一个名为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)
还有一个具有类
的处理程序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)
我想导入main函数中定义的缓存变量,以便在类中用作@cache.memoize
。如何在类中导入该变量?
答案 0 :(得分:2)
您可以在单独的模块(fcache.py)中创建Cache
实例:
from flask_cache import Cache
cache = Cache()
之后,您可以在主文件中配置它:
from flask import Flask
from fcache import cache
app = Flask(__name__)
cache.init_app(app, config={'CACHE_TYPE': 'redis'})
Cache
实例可以在其他模块中导入:
from fcache import cache
@cache.memoize(60)
def get_value():
return 'Value'
此方法也可以与Flask-SQLAlchemy等其他Flask扩展一起使用。