Exemple #1
0
    def __init__(self, app, config, *args):

        self.caches = [
            flask_caching.Cache(app,
                                config={
                                    "CACHE_TYPE": 'redis',
                                    "CACHE_REDIS_URL": url
                                }) for url in app.config['redis_urls']
        ]
    def __init__(self, app: Dash) -> None:
        cache_dir = (
            WEBVIZ_INSTANCE_INFO.storage_folder / f"SurfaceServer_filecache_{uuid4()}"
        )
        LOGGER.debug(f"Setting up file cache in: {cache_dir}")
        self._image_cache = flask_caching.Cache(
            config={
                "CACHE_TYPE": "FileSystemCache",
                "CACHE_DIR": cache_dir,
                "CACHE_DEFAULT_TIMEOUT": 0,
            }
        )
        self._image_cache.init_app(app.server)

        self._setup_url_rule(app)
    def __init__(self, app: dash.Dash):
        app.server.logger.info(f"REDIS: {config.redis_host} {config.redis_key}")

        self.cache: flask_caching.Cache = flask_caching.Cache(app.server, config=dict(
            CACHE_TYPE="redis",
            CACHE_REDIS_HOST=config.redis_host,
            CACHE_REDIS_PASSWORD="******",
            CACHE_REDIS_PORT=6380,
            CACHE_REDIS_DB=0,
            CACHE_OPTIONS={"ssl": True}
        ))
        self.r: redis.Redis = self.cache.cache._read_clients  # NoQA
        self.key_prefix = self.cache.cache.key_prefix
        self.environment = "prod" if config.is_production else "dev"
        self.app = app
import flask_caching


CACHE = flask_caching.Cache(config={"CACHE_TYPE": "simple"})
CACHE.TIMEOUT = 3600
import flask_caching
from server import app, cache_config

cache = flask_caching.Cache()


def main():
    cache.init_app(app, config=cache_config)
    with app.app_context():
        cache.clear()


if __name__ == '__main__':
    main()
Exemple #6
0
        'color': '#1f77b4',
        'width': 0
    }),
]

logging.basicConfig(level=logging.INFO,
                    format="%(levelname)s:%(name)s:%(threadName)s:%(message)s")
app = dash.Dash(__name__)
app.css.append_css(
    {'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'})
# app.css.append_css({'external_url': 'https://codepen.io/chriddyp/pen/brPBPO.css'})
# app.css.append_css({'external_url': '/static/stylesheet.css'})

cache = flask_caching.Cache(app.server,
                            config={
                                'CACHE_TYPE': 'filesystem',
                                'CACHE_DIR': 'cache'
                            })


def si_format(num):
    """ Convert num to a string with nice SI prefix formatting"""
    if num == 0: return u"0.0"
    mag = math.floor(math.log10(abs(num)))
    if mag >= -3 and mag <= 3:
        thous = 0
    else:
        thous = int(math.floor(mag / 3))
    letter = u' kMGTPE'[
        thous] if thous > 0 else u' mμnpfa'[-thous] if thous < 0 else u''
    return u"{:,.3f}{}".format(num / (1000.**thous), letter)
Exemple #7
0
def cache(client):
    return fsc.Cache(client)
Exemple #8
0
# from boomtrain.config import load_flask
import main
# import boomtrain.flask.service

# app = boomtrain.flask.service.APIService(__name__)
app = flask.Flask()
# CONFIG = load_flask()
DB_URL = os.env

cache_config = {
    'CACHE_TYPE': 'filesystem',
    'CACHE_DIR': '/var/cache/flask',
    'CACHE_DEFAULT_TIMEOUT': 900,
    'CACHE_THRESHOLD': 999
}
cache = flask_caching.Cache(app, config=cache_config)


def debug_mode():
    """Debug mode callable to disable cache in dev"""
    return app.debug


def full_cache_key():
    """Cache key callable that includes GET parameters."""
    return flask.request.full_path


@app.route('/')
@cache.cached(unless=debug_mode)
def index():
Exemple #9
0
import time
import urllib

import querymanager

import woeplanet.utils.uri as uri

dotenv.load_dotenv(dotenv.find_dotenv())

app = flask.Flask(__name__)
cache = flask_caching.Cache(
    config={
        'CACHE_TYPE': 'filesystem',
        'CACHE_DEFAULT_TIMEOUT': 5,
        'CACHE_IGNORE_ERRORS': False,
        'CACHE_DIR': os.environ.get('WOE_CACHE_DIR'),
        'CACHE_THRESHOLD': 500,
        'CACHE_OPTIONS': {
            'mode': int(os.environ.get('WOE_CACHE_MASK'))
        }
    })
cache.init_app(app)


@app.template_filter()
def commafy(value):
    return '{:,}'.format(value)


@app.template_filter()
def anyfy(value):
Exemple #10
0
 def __init__(self, app, config=None, **kwargs):
     super(FlaskCacheBackend, self).__init__(**kwargs)
     self.cache = flask_caching.Cache(app, config=config)
Exemple #11
0
import flask_caching

cache = flask_caching.Cache(config={
    "CACHE_TYPE": "simple",
    "CACHE_DEFAULT_TIMEOUT": 300
})
cached = cache.cached
delete = cache.delete
delete_memoized = cache.delete_memoized
memoize = cache.memoize
Exemple #12
0
import pymongo
import hdfs
import io

from datetime import datetime

hdfs_url = "http://localhost:50070"
db_url = "mongodb://localhost:27017"
db_name = "db"

hdfs_client = hdfs.InsecureClient(hdfs_url, user='******')
db_client = pymongo.MongoClient(db_url)
db = db_client[db_name]

app = flask.Flask(__name__)
cache = flask_caching.Cache(app, config={'CACHE_TYPE': 'redis'})


@cache.memoize(timeout=60)
def retrieve_user(uid):
    user = db["user"].find_one({"uid": str(uid)})
    if user is not None:
        del user["_id"]
    return user


@cache.memoize(timeout=60)
def retrieve_article(aid):
    article = db["article"].find_one({"aid": str(aid)})
    if article is not None:
        del article["_id"]
Exemple #13
0
#pylint: skip-file
"""dnstwister web app.

This is the pattern from http://flask.pocoo.org/docs/0.11/patterns/packages/
which generates circular imports hence the comment at the top to just ignore
this file.
"""
import flask
import flask_caching
import logging

# Set up app/cache/db/emailer/gateway here
app = flask.Flask(__name__)
cache = flask_caching.Cache(app, config={'CACHE_TYPE': 'simple'})

# Logging
app.logger.setLevel(logging.INFO)

# Blueprints
import api
app.register_blueprint(api.app, url_prefix='/api')

# Import modules using dnstwister.app/cache here.
import tools
import tools.template
import views.www.analyse
import views.www.index
import views.www.search

# Filters
app.jinja_env.filters['domain_renderer'] = tools.template.domain_renderer
Exemple #14
0
import pandas as pd
from dash.dependencies import Input, Output
import flask_caching

# read csv file of hotel booking data
# create dash app
external_stylesheets = [
    "https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css"
]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server

# cache app
cache = flask_caching.Cache(server,
                            config={
                                "CACHE_TYPE": "filesystem",
                                "CACHE_DIR": "cache-directory"
                            })

TIMEOUT = 60


# pull data
@cache.memoize(timeout=TIMEOUT)
def hotel_data():
    return pd.read_csv(
        "https://raw.githubusercontent.com/mfarris/hotel_data/master/hotel_bookings.csv"
    )


# base config
Exemple #15
0
def cache(app):
    return fsc.Cache(app)
Exemple #16
0
import flask
import flask_caching
from google.appengine.api import app_identity
from google.appengine.api import images
from google.appengine.api import wrap_wsgi_app
from google.cloud import storage

IMAGE_EXTENSIONS = ('.jpg', '.gif', '.png')

app = flask.Flask(__name__)
# The wrap_wsgi_app function sets up the request environ and stuff that the
# legacy App Engine APIs expect.
app.wsgi_app = wrap_wsgi_app(app.wsgi_app)
# flask_caching's memcached backend automatically uses the legacy memcache API.
cache = flask_caching.Cache(config={'CACHE_TYPE': 'MemcachedCache'})
cache.init_app(app)


@functools.cache
def get_bucket_name():
    # For a GCP project `foo`, the default bucket is `foo.appspot.com`
    return app_identity.get_default_gcs_bucket_name()


def get_uploaded_file(request, form_field='file'):
    """The uploaded file object and a random destination path in storage."""
    file = request.files[form_field]
    ext = pathlib.Path(file.filename).suffix

    if ext not in IMAGE_EXTENSIONS:
Exemple #17
0
import logging
import repo

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter(
    "%(asctime)s %(name)s %(levelname)s: %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)

app = flask.Flask(__name__)

cache = flask_caching.Cache(app, config={"CACHE_TYPE": "simple"})


@cache.cached(timeout=600, key_prefix="get_git_repos")
def get_git_repos():
    return [repo["node"] for repo in repo.get_git_repos(max_repos=20)]


@app.route("/")
def index():
    try:
        repos = get_git_repos()
    except Exception as e:
        # Yuck.  Ugly hack for error handling.
        logger.warning("Failed to retrieve repos: {e}".format(e=e))
        repos = [{
import datetime
import flask_caching as fcache
import json
import os
import MapSummary

from database import DatabaseConnection
import valve.source.a2s
from valve.source import NoResponseError

app = flask.Flask("open-leaderboard")

if os.path.isfile("config.py"):
    app.config.from_object("config")

cache = fcache.Cache(app, config={'CACHE_TYPE': 'simple'})
cache.init_app(app)

SEGMENT = 100
SERVERS = list()


def prettifyMinMaxY(computedMin, computedMax):
    if computedMax > 0 and computedMin > 0:
        return (0, 4000)
    else:
        return (computedMin - 100, 4000)


@app.route("/players-online")
def playersOnline():