Python flask_caching.Cache() Examples

The following are 14 code examples of flask_caching.Cache(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_caching , or try the search function .
Example #1
Source File: _test_ext.py    From assembly with MIT License 5 votes vote down vote up
def test_cache():
    assert isinstance(cache, flask_caching.Cache)

# # Mailer
# def test_mailer_none():
#     assert mailer.mail is None
#
# def test_mailer_ses():
#     app = Flask(__name__)
#     app.config.update(**{
#         "MAILER_PROVIDER": "SES",
#         "MAILER_SES_ACCESS_KEY": "",
#         "MAILER_SES_SECRET_KEY": ""
#     })
#     mailer.init_app(app)
#     assert isinstance(mailer.mail, ses_mailer.Mail)
#
# def test_mailer_smtp():
#     app = Flask(__name__)
#     app.config.update(**{
#         "MAILER_PROVIDER": "SMTP",
#         "MAILER_SMTP_URI": "smtp://user:pass@mail.google.com:25",
#         "DEBUG": False,
#         "TESTING": False
#     })
#
#     mailer.init_app(app)
#     assert isinstance(mailer.mail, flask_mail.Mail) 
Example #2
Source File: test_views.py    From Flask-Blogging with MIT License 5 votes vote down vote up
def _create_blogging_engine(self):
        cache = Cache(self.app, config={"CACHE_TYPE": "simple"})
        return BloggingEngine(self.app, self.storage, cache=cache) 
Example #3
Source File: api.py    From grin-pool with Apache License 2.0 5 votes vote down vote up
def verify_password(username_or_token, password=None):
    global database
    #database = lib.get_db()
    LOGGER = lib.get_logger(PROCESS)
    debug and LOGGER.warn("Will Verify User: {}, {}".format(username_or_token, password))
    # First try to verify via token
    user_rec = Users.verify_auth_token(app.config['SECRET_KEY'], username_or_token)
    if user_rec is None:
        # try to authenticate with username/password
        user_rec = Users.get(username_or_token, password)
    if user_rec is None:
        return False
    g.user = user_rec
    # Cache username<->user_id in redis for our stratum server
    redis_key = redis_userid_key + user_rec.username
    r.set(redis_key, user_rec.id)
    redis_key = redis_userid_key + user_rec.username.lower()
    r.set(redis_key, user_rec.id)
    return True

# XXX TODO:
# def change_password(username_or_token, new_password, password=None):
#     xxx TODO


#################
# -- Pool User Accounts 
Example #4
Source File: utils_tests.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def test_setup_cache_null_config(self):
        app = Flask(__name__)
        cache_config = {"CACHE_TYPE": "null"}
        assert isinstance(CacheManager._setup_cache(app, cache_config), Cache) 
Example #5
Source File: utils_tests.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def test_setup_cache_standard_config(self):
        app = Flask(__name__)
        cache_config = {
            "CACHE_TYPE": "redis",
            "CACHE_DEFAULT_TIMEOUT": 60,
            "CACHE_KEY_PREFIX": "superset_results",
            "CACHE_REDIS_URL": "redis://localhost:6379/0",
        }
        assert isinstance(CacheManager._setup_cache(app, cache_config), Cache) is True 
Example #6
Source File: cache_manager.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def _setup_cache(app: Flask, cache_config: CacheConfig) -> Cache:
        """Setup the flask-cache on a flask app"""
        if isinstance(cache_config, dict):
            return Cache(app, config=cache_config)

        # Accepts a custom cache initialization function, returning an object compatible
        # with Flask-Caching API.
        return cache_config(app) 
Example #7
Source File: cache_manager.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def tables_cache(self) -> Cache:
        return self._tables_cache 
Example #8
Source File: cache_manager.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def cache(self) -> Cache:
        return self._cache 
Example #9
Source File: screenshots.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def get(
        self,
        user: "User" = None,
        cache: "Cache" = None,
        thumb_size: Optional[WindowSize] = None,
    ) -> Optional[BytesIO]:
        """
            Get thumbnail screenshot has BytesIO from cache or fetch

        :param user: None to use current user or User Model to login and fetch
        :param cache: The cache to use
        :param thumb_size: Override thumbnail site
        """
        payload: Optional[bytes] = None
        thumb_size = thumb_size or self.thumb_size
        if cache:
            payload = cache.get(self.cache_key)
        if not payload:
            payload = self.compute_and_cache(
                user=user, thumb_size=thumb_size, cache=cache
            )
        else:
            logger.info("Loaded thumbnail from cache: %s", self.cache_key)
        if payload:
            return BytesIO(payload)
        return None 
Example #10
Source File: screenshots.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def get_from_cache(self, cache: "Cache") -> Optional[BytesIO]:
        payload = cache.get(self.cache_key)
        if payload:
            return BytesIO(payload)
        return None 
Example #11
Source File: flask_server.py    From trusat-backend with Apache License 2.0 5 votes vote down vote up
def catalog_cache(response):
    response.headers['Cache-Control'] = 'max-age=300'
    return response 
Example #12
Source File: flask_common.py    From flask-common with Apache License 2.0 5 votes vote down vote up
def init_app(self, app):
        """Initializes the Flask application with Common."""
        if not hasattr(app, 'extensions'):
            app.extensions = {}

        if 'common' in app.extensions:
            raise RuntimeError("Flask-Common extension already initialized")

        app.extensions['common'] = self
        self.app = app

        if 'COMMON_FILESERVER_DISABLED' not in app.config:
            with app.test_request_context():

                # Configure WhiteNoise.
                app.wsgi_app = WhiteNoise(app.wsgi_app, root=url_for('static', filename='')[1:])

        self.cache = Cache(app, config={'CACHE_TYPE': app.config.get("COMMON_CACHE_TYPE", 'simple')})

        @app.before_request
        def before_request_callback():
            request.start_time = maya.now()

        @app.after_request
        def after_request_callback(response):
            if 'COMMON_POWERED_BY_DISABLED' not in current_app.config:
                response.headers['X-Powered-By'] = 'Flask'
            if 'COMMON_PROCESSED_TIME_DISABLED' not in current_app.config:
                response.headers['X-Processed-Time'] = maya.now().epoch - request.start_time.epoch
            return response

        @app.route('/favicon.ico')
        def favicon():
            return redirect(url_for('static', filename='favicon.ico'), code=301) 
Example #13
Source File: api.py    From grin-pool with Apache License 2.0 4 votes vote down vote up
def post(self):
        global database
        LOGGER = lib.get_logger(PROCESS)
        username = None
        password = None
        try:
            debug and print("json request = {}".format(request.form))
            username = request.form.get('username')
            password = request.form.get('password')
            debug and LOGGER.warn("PoolAPI_users POST: user:{} password:{}".format(username, password))
        except AttributeError as e:
            LOGGER.warn("Missing username or password - {}".format(str(e)))
        if username is None or password is None:
            response = jsonify({ 'message': 'Missing arguments: username and pasword required' })
            response.status_code = 400
            return response
        if username == "" or password == "":
            response = jsonify({ 'message': 'Missing arguments: username and pasword required' })
            response.status_code = 400
            return response
        if "." in username:
            response = jsonify({ 'message': 'Invalid Username: May not contain "."' })
            response.status_code = 400
            return response
        # Check if the username is taken
        exists = Users.check_username_exists(username)
        if exists:
            debug and print("Failed to add - conflict with existing user = {}".format(username))
            response = jsonify({ 'message': 'Conflict with existing account' })
            response.status_code = 409
            return response
        # Create the users record
        user_rec = Users.create(username, password)
        if user_rec is None:
            debug and print("Failed to add - unable to create a new user record")
            response = jsonify({ 'message': 'System Error: Failed to create account' })
            response.status_code = 500
            return response
        # initialize a worker_stats record for this user (previous block) so they get instance feedback on the UI
        lb = Blocks.get_latest()
        if lb is not None:
            height = Blocks.get_latest().height
            initial_stat = Worker_stats(datetime.utcnow(), height, user_rec.id)
            database.db.createDataObj(initial_stat)
        # Cache username<->user_id in redis for our stratum server
        redis_key = redis_userid_key + user_rec.username
        r.set(redis_key, user_rec.id)
        debug and print("Added user = {}".format(user_rec))
        response = jsonify({ 'username': user_rec.username, 'id': user_rec.id })
        response.status_code = 201
        return response

    #decorators = [limiter.limit("5/minute"), auth.login_required] 
Example #14
Source File: screenshots.py    From incubator-superset with Apache License 2.0 4 votes vote down vote up
def compute_and_cache(  # pylint: disable=too-many-arguments
        self,
        user: "User" = None,
        thumb_size: Optional[WindowSize] = None,
        cache: "Cache" = None,
        force: bool = True,
    ) -> Optional[bytes]:
        """
        Fetches the screenshot, computes the thumbnail and caches the result

        :param user: If no user is given will use the current context
        :param cache: The cache to keep the thumbnail payload
        :param window_size: The window size from which will process the thumb
        :param thumb_size: The final thumbnail size
        :param force: Will force the computation even if it's already cached
        :return: Image payload
        """
        cache_key = self.cache_key
        if not force and cache and cache.get(cache_key):
            logger.info("Thumb already cached, skipping...")
            return None
        thumb_size = thumb_size or self.thumb_size
        logger.info("Processing url for thumbnail: %s", cache_key)

        payload = None

        # Assuming all sorts of things can go wrong with Selenium
        try:
            payload = self.get_screenshot(user=user)
        except Exception as ex:  # pylint: disable=broad-except
            logger.error("Failed at generating thumbnail %s", ex)

        if payload and self.window_size != thumb_size:
            try:
                payload = self.resize_image(payload, thumb_size=thumb_size)
            except Exception as ex:  # pylint: disable=broad-except
                logger.error("Failed at resizing thumbnail %s", ex)
                payload = None

        if payload and cache:
            logger.info("Caching thumbnail: %s %s", cache_key, str(cache))
            cache.set(cache_key, payload)
        return payload