[英]importing variable from main file to class variable
I have two files.我有两个文件。 One is a main python file.一个是主要的python文件。 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.我想导入 main 函数中定义的缓存变量,以便在类中用作@cache.memoize
。 How do I import that variable inside the class?如何在类中导入该变量?
You can create your Cache
instance in a separate module (fcache.py):您可以在单独的模块 (fcache.py) 中创建您的Cache
实例:
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: Cache
实例可以在其他模块中导入:
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.这种方法也可以与 Flask-SQLAlchemy 等其他 Flask 扩展一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.