Esempio n. 1
0
def zuluru_sync():
    with app.app_context():
        ZuluruSync().sync_teams(league_id=662)

    db.session.remove()

    cache = Cache(app, config={'CACHE_TYPE': 'simple'})
    cache.clear()
Esempio n. 2
0
class KotoriServer(Flask):
    def __init__(self, import_name: str):
        super().__init__(import_name)
        self.import_plugins()
        config_path = environ.get("KOTORI_CONFIG")
        if config_path is None:
            raise ValueError("Please set KOTORI_CONFIG")
        config_file = Path(config_path)
        config = ConfigLoader.load(config_file)
        if config is None:
            raise ValueError(f"{config_path} cannot be loaded.")
        self.kotori = Kotori(config)
        self._init_cache(config)
        self._init_path()

    def _init_cache(self, config: Config):
        if config.cache.get("CACHE_TYPE", "null") == "null":
            return
        self.cache = Cache(self, config=config.cache)
        with self.app_context():
            self.cache.clear()
        self.get_image = self.cache.memoize()(self.get_image)

    def _init_path(self):
        self.get_image = self.route("/<path:path>",
                                    methods=["GET"])(self.get_image)
        self.errorhandler(ValueError)(self.on_value_error)
        self.errorhandler(404)(self.no_not_found)

    @staticmethod
    def import_plugins():
        path = environ.get("KOTORI_PLUGINS")
        if path is None:
            return
        plugin_dir = Path(path)
        if not plugin_dir.is_dir():
            return

        sys.path.append(str(plugin_dir.absolute()))
        for _, package_name, _ in pkgutil.iter_modules([plugin_dir]):
            if package_name not in sys.modules:
                importlib.import_module(package_name)

    def get_image(self, path: str):  # pylint: disable=method-hidden
        if path == "favicon.ico":
            abort(404)
        response = self.kotori.get(f"/{path}")
        response.headers["server"] = "Kotori"
        return response

    @staticmethod
    def on_value_error(error: ValueError):
        logger.exception(error, exc_info=False)
        return "", 404

    @staticmethod
    def no_not_found(_: NotFound):
        return "", 404
Esempio n. 3
0
def create_flaskr_app():
    # Sorry
    global _app, _cache, _db_endpoint
    # Verify some of the vital settings are there.
    assert os.environ.get('FLASK_SECRET_KEY') is not None
    assert os.environ.get('FLASK_CACHE_DIR') is not None
    assert os.environ.get('FLASK_DB_ENDPOINT') is not None

    # Load settings
    setting_secret_key = os.environ.get('FLASK_SECRET_KEY')
    cache_dir = os.environ.get('FLASK_CACHE_DIR')
    cache_threshold = int(os.environ.get('FLASK_CACHE_THRESHOLD', 10000))
    _db_endpoint = os.environ.get('FLASK_DB_ENDPOINT')

    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY=setting_secret_key,
        NAV_ITEMS=get_nav_items(),
        CACHE_TYPE="FileSystemCache",  # Flask-Caching related configs
        CACHE_DIR=cache_dir,
        CACHE_THRESHOLD=cache_threshold,
        CACHE_DEFAULT_TIMEOUT=300)

    # Create cache; on load flush it
    _cache = Cache(app)
    _cache.clear()

    # Session data
    @app.before_request
    def init_session():
        session.permanent = True
        app.permanent_session_lifetime = timedelta(days=365)
        g.current_git_commit = git.CURRENT_GIT_COMMIT
        g.current_git_branch = git.CURRENT_GIT_BRANCH

    # Blueprints
    from . import dive
    app.register_blueprint(dive.bp)
    from . import user
    app.register_blueprint(user.bp)
    from . import admin
    app.register_blueprint(admin.bp)

    #
    # Separate Page definitions
    #
    @app.route('/')
    def index():
        return flask.redirect(flask.url_for('dive.show_any'))

    @app.route('/favicon.ico')
    def favicon():
        return flask.redirect(
            url_for('static', filename='images/favicon/favicon.ico'))

    return app
Esempio n. 4
0
class CacheManager(metaclass=Singleton):

    def __init__(self, config=CACHE["config"], timeout=CACHE["timeout"]):
        self.timeout = timeout
        self.caching = Cache(config=config)

    def init(self, app):
        self.caching.init_app(app)

    def clear(self):
        self.caching.clear()
Esempio n. 5
0
File: cache.py Progetto: jrnn/sholdr
def create_cache(app, db):
    cache = Cache(config={
        "CACHE_DEFAULT_TIMEOUT": 900,
        "CACHE_TYPE": "simple"
    })
    cache.init_app(app)

    with app.app_context():
        cache.clear()

    def commit_and_flush_cache():
        cache.clear()
        db.session.commit()

    db.commit_and_flush_cache = commit_and_flush_cache
    return cache
Esempio n. 6
0
def app_setup(config):

    config = os.path.abspath(config)

    with open(config) as f:
        sett = yaml.safe_load(f)

    os.environ['WEBPLOT_PORT'] = str(sett['port'])
    os.environ['WEBPLOT_HOST'] = sett['host']

    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

    cache = Cache(app.server, config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_HOST': sett['redis']['host'],
                                      'CACHE_REDIS_PORT': sett['redis']['port'],
                                      'CACHE_REDIS_PASSWORD': sett['redis']['password'],
                                      'CACHE_THRESHOLD': sett['cache_threshold'],
                                      'CACHE_DEFAULT_TIMEOUT': sett['cache_time_to_live']})
    cache.clear()
    db = DataQuery(sett['db_path'])

    conf = ReadOnlyDict(sett)

    return app, cache, db, conf
Esempio n. 7
0
# Initialize the Flask application
cache = Cache(config={'CACHE_TYPE': 'null'})
app = Flask(__name__)
emotions = [
    "afraid", "angry", "disgusted", "happy", "neutral", "sad", "surprised"
]
# This is the path to the upload directory
app.config['UPLOAD_FOLDER'] = 'uploads/'
# These are the extension that we are accepting to be uploaded
app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'JPG'])

# To initialize cache
cache.init_app(app)
# clear cache
with app.app_context():
    cache.clear()


# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']


# This route will show a form to perform an AJAX request
# jQuery is loaded to execute the request and update the
# value of the operation
@app.route('/')
def index():
    return render_template('index.html')
Esempio n. 8
0
    guide = all_guides[int(sel_cel[0]['row'])]['Guides'] 
    radar_img = 'summary_single_guide_' + guide + '_' + str(mms) + 'mm.png'
    try:
        radar_src = 'data:image/png;base64,{}'.format(base64.b64encode(open('Results/' + job_id + '/' + radar_img, 'rb').read()).decode())
        radar_href = 'assets/Img/' + job_id + '/' + radar_img
    except:
        radar_src = ''
        radar_href = ''
    return barplot_src, barplot_href, radar_src, radar_href


#If the input guides are different len, select the ones with same length as the first
def selectSameLenGuides(list_guides):
    selected_length = len(list_guides.split('\n')[0])
    same_len_guides_list = []
    for guide in list_guides.split('\n'):
        if len(guide) == selected_length:
            same_len_guides_list.append(guide)
    same_len_guides = '\n'.join(same_len_guides_list).strip()
    return same_len_guides

if __name__ == '__main__':
    app.run_server(host = '0.0.0.0', debug=True, port = 80)
    cache.clear()       #delete cache when server is closed

    #BUG quando faccio scores, se ho dei char IUPAC nei targets, nel terminale posso vedere 150% 200% etc perche' il limite massimo e' basato su wc -l dei targets, ma possono aumentare se ho molti
    #Iupac


    #TODO 
    # togliere caricamento del file per evitare confusione,
Esempio n. 9
0
scheduler = BackgroundScheduler()
if not app.debug and not app.testing:
    scheduler.start()


def shutdown_scheduler():
    if scheduler.running:
        scheduler.shutdown()


# Shut down the scheduler when exiting the app
atexit.register(shutdown_scheduler)

if app.debug or app.testing:
    with app.app_context():
        cache.clear()  # Clear cache during development
    app.config['MAIL_SUPPRESS_SEND'] = True  # Suppress emails during development

mail = Mail(app)


class MailExceptionHandler(SMTPHandler):
    def __init__(self):
        super(MailExceptionHandler, self).__init__(None, None, None, None)

    def emit(self, record):
        # noinspection PyBroadException
        try:
            # Send exception report via email
            with app.app_context(), app.test_request_context():
              from flask_mail import Message
Esempio n. 10
0
import dash
import json
from flask_caching import Cache

app = dash.Dash(__name__, suppress_callback_exceptions=True)
app.title = 'EveryoneCounts'

with open("config.json", "r") as f:
    CONFIG = json.load(f)
CLEAR_CACHE_ON_STARTUP = CONFIG["CLEAR_CACHE_ON_STARTUP"]
SLOW_CACHE_CONFIG = CONFIG["SLOW_CACHE_CONFIG"]
FAST_CACHE_CONFIG = CONFIG["FAST_CACHE_CONFIG"]

slow_cache = Cache(app.server, config=SLOW_CACHE_CONFIG)
fast_cache = Cache(app.server, config=FAST_CACHE_CONFIG)
if CLEAR_CACHE_ON_STARTUP:
    slow_cache.clear()
    fast_cache.clear()
Esempio n. 11
0
def create_rest_api(event_queue):
    from cmdb.interface.config import app_config
    from cmdb.utils.system_config import SystemConfigReader
    system_config_reader = SystemConfigReader()

    try:
        cache_config = {
            'DEBUG':
            True,
            'CACHE_TYPE':
            system_config_reader.get_value('name', 'Cache'),
            'CACHE_REDIS_HOST':
            system_config_reader.get_value('host', 'Cache'),
            'CACHE_REDIS_PORT':
            system_config_reader.get_value('port', 'Cache'),
            'CACHE_REDIS_PASSWORD':
            system_config_reader.get_value('password', 'Cache'),
        }
    except (ImportError, CMDBError) as e:
        LOGGER.debug(e.message)
        cache_config = {'CACHE_TYPE': 'simple'}
    from flask_caching import Cache

    cache = Cache(config=cache_config)

    # Create manager
    from cmdb.data_storage.database_manager import DatabaseManagerMongo
    app_database = DatabaseManagerMongo(
        **system_config_reader.get_all_values_from_section('Database'))
    object_manager = CmdbObjectManager(database_manager=app_database,
                                       event_queue=event_queue)

    log_manager = CmdbLogManager(database_manager=app_database)

    security_manager = SecurityManager(database_manager=app_database)

    user_manager = UserManager(database_manager=app_database)

    exportd_job_manager = ExportdJobManagement(database_manager=app_database,
                                               event_queue=event_queue)

    exportd_log_manager = ExportdLogManager(database_manager=app_database)

    media_file_manager = MediaFileManagement(database_manager=app_database)

    docapi_tpl_manager = DocapiTemplateManager(database_manager=app_database)

    # Create APP
    from cmdb.interface.cmdb_app import BaseCmdbApp

    app = BaseCmdbApp(__name__,
                      database_manager=app_database,
                      docapi_tpl_manager=docapi_tpl_manager,
                      media_file_manager=media_file_manager,
                      exportd_manager=exportd_job_manager,
                      exportd_log_manager=exportd_log_manager,
                      object_manager=object_manager,
                      log_manager=log_manager,
                      user_manager=user_manager,
                      security_manager=security_manager)

    # Import App Extensions
    from flask_cors import CORS
    CORS(app)
    import cmdb
    cache.init_app(app)
    cache.clear()
    app.cache = cache

    if cmdb.__MODE__ == 'DEBUG':
        app.config.from_object(app_config['rest_development'])
        LOGGER.info('RestAPI starting with config mode {}'.format(
            app.config.get("ENV")))
    elif cmdb.__MODE__ == 'TESTING':
        app.config.from_object(app_config['testing'])
    else:
        app.config.from_object(app_config['rest'])
        LOGGER.info('RestAPI starting with config mode {}'.format(
            app.config.get("ENV")))

    with app.app_context():
        register_converters(app)
        register_error_pages(app)
        register_blueprints(app)

    return app