2

我有两个文件。一个是主要的python文件。我正在使用烧瓶,我正在使用烧瓶缓存初始化一个名为缓存的变量

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在类中使用。如何在类中导入该变量?

4

1 回答 1

2

Cache您可以在单独的模块 (fcache.py)中创建您的实例:

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 扩展一起使用。

于 2017-10-11T10:26:00.510 回答