Exemplo n.º 1
0
def create_app():
    """创建Flask app"""
    app = Flask(__name__)
    cache = Cache(app, config={'CACHE_TYPE': 'simple'})
    cache.init_app(app)
    # Load config
    config = load_config()
    app.config.from_object(config)

    # CSRF protect
    csrf.init_app(app)

    # 注册组件
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_logger(app)
    register_uploadsets(app)

    # before every request
    @app.before_request
    def before_request():
        """Do something before request"""
        # 记录用户的访问时间到redis
        g.user = get_current_user()
        if g.user:
            set_user_active_time(g.user.id)
            g.msg_num = MailBox.query.filter(MailBox.recver_id == g.user.id, MailBox.result == None).count()

    from .utils.devices import Devices

    devices = Devices(app)

    return app
Exemplo n.º 2
0
def create_app():
    global cache
    app = Flask(__name__,
                static_folder="../dist/static",
                template_folder="../dist")
    cache = Cache(config={'CACHE_TYPE': 'simple'})
    cache.init_app(app)
    CORS(app, resources={r"/api/*": {"origins": "*"}})
    return app
Exemplo n.º 3
0
 def assertCacheInitedWithoutError(self, cache_type_value):
     config = {
         'CACHE_TYPE': cache_type_value,
         'CACHE_NO_NULL_WARNING': True,
     }
     cache = Cache()
     try:
         cache.init_app(self.app, config=config)
     except:
         self.fail("Can't set CACHE_TYPE to %s" % cache_type_value)
Exemplo n.º 4
0
 def test_21_redis_url_custom_db(self):
     config = {
         'CACHE_TYPE': 'redis',
         'CACHE_REDIS_URL': 'redis://localhost:6379/2',
     }
     cache = Cache()
     cache.init_app(self.app, config=config)
     rconn = self.app.extensions['cache'][cache] \
                 ._client.connection_pool.get_connection('foo')
     assert rconn.db == 2
Exemplo n.º 5
0
 def test_21_redis_url_custom_db(self):
     config = {
         'CACHE_TYPE': 'redis',
         'CACHE_REDIS_URL': 'redis://localhost:6379/2',
     }
     cache = Cache()
     cache.init_app(self.app, config=config)
     rconn = self.app.extensions['cache'][cache] \
                 ._client.connection_pool.get_connection('foo')
     assert rconn.db == 2
Exemplo n.º 6
0
def create_app():
    
    app = Flask(__name__)
    cache = Cache(app,config={'CACHE_TYPE': 'simple'})
    cache.init_app(app)

    app.debug = True
    app.register_blueprint(api)
    db = CassandraDBConnector()

    return app
Exemplo n.º 7
0
def clear_cache():
    if (not pqr.debug):
        return "You're not supposed to be here o_0"
    global cache
    cache.clear()
    cache = Cache(config={'CACHE_TYPE': 'null'})
    cache.init_app(pqr)
    print cache.config
    print pqr.debug
    flash('Cache cleared')
    return redirect(url_for('molecule', key=MOLECULE_OF_THE_WEEK))
Exemplo n.º 8
0
 def test_20_redis_url_default_db(self):
     config = {
         'CACHE_TYPE': 'redis',
         'CACHE_REDIS_URL': 'redis://localhost:6379',
     }
     cache = Cache()
     cache.init_app(self.app, config=config)
     from werkzeug.contrib.cache import RedisCache
     assert isinstance(self.app.extensions['cache'][cache], RedisCache)
     rconn = self.app.extensions['cache'][cache] \
                 ._client.connection_pool.get_connection('foo')
     assert rconn.db == 0
Exemplo n.º 9
0
 def test_20_redis_url_default_db(self):
     config = {
         'CACHE_TYPE': 'redis',
         'CACHE_REDIS_URL': 'redis://localhost:6379',
     }
     cache = Cache()
     cache.init_app(self.app, config=config)
     from werkzeug.contrib.cache import RedisCache
     assert isinstance(self.app.extensions['cache'][cache], RedisCache)
     rconn = self.app.extensions['cache'][cache] \
                 ._client.connection_pool.get_connection('foo')
     assert rconn.db == 0
Exemplo n.º 10
0
def create_app(name=None):
    app = Flask(name)

    if os.environ.get('PRODUCTION'):
        app.config.from_object(ProductionConfig)
        print "running with ProductionConfig"
    else:
        app.config.from_object(DefaultConfig)
        print "running with DefaultConfig"

    # sentry
    if app.config.get('SENTRY_DSN'):
        sentry = Sentry()
        sentry.init_app(app)
        app.sentry = sentry

    # assets
    assets = Environment(app)
    assets.url = app.static_url_path
    scss_bundle = Bundle('css/*.scss', 'css/*.css',
        filters=['scss', 'cssmin'], depends='css/*.scss', output='css/all.css')
    assets.register('scss_all', scss_bundle)
    js_bundle = Bundle('js/*.js', filters='rjsmin', output='js/all.js')
    assets.register('js_all', js_bundle)
    Compress(app)

    # cache
    if app.config['DEBUG']:
        cache_type = 'null'
    else:
        cache_type = 'simple'

    cache = Cache(config={'CACHE_TYPE': cache_type})
    cache.init_app(app)
    app.cache = cache

    # CDN
    cdn = CDN()
    cdn.init_app(app)

    # workaround flask-assets / flask-cdn integration
    if app.config.get('CDN_HTTPS'):
        cdn_scheme = 'https'
    else:
        cdn_scheme = 'http'
    if app.config.get('FLASK_ASSETS_USE_CDN') and app.config.get('CDN_DOMAIN'):
        app.jinja_env.globals['FLASK_CDN'] = '%s://%s' % (cdn_scheme, app.config['CDN_DOMAIN'])

    return app
Exemplo n.º 11
0
def create_app():
    """创建Flask app"""
    app = Flask(__name__)
    cache = Cache(app,config={'CACHE_TYPE': 'simple'})
    cache.init_app(app)
    # Load config
    config = load_config()
    app.config.from_object(config)

    # CSRF protect
    csrf.init_app(app)

    # if app.debug:
    #     DebugToolbarExtension(app)


    # from .mails import mail
    # mail.init_app(app)

    # 注册组件
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_logger(app)
    register_uploadsets(app)

    # load chinese name dict from dict.txt once
    # from utils.account import CheckName
    #
    # # 加载dict.txt
    # CheckName(app)

    # before every request
    @app.before_request
    def before_request():
        """Do something before request"""
        # 记录用户的访问时间到redis
        g.user = get_current_user()
        if g.user:
            set_user_active_time(g.user.id)

    from .utils.devices import Devices

    devices = Devices(app)

    return app
Exemplo n.º 12
0
def compile_cam_images():
    try:
        with current_app.test_request_context():
            print "[+] Starting cam images cache reset..."
            cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_DB': 0})
            cache.init_app(current_app)

            cam_images = _compile_cam_images()

            if "error" not in cam_images:
                cache.set('cam_images', cam_images, timeout=CACHE_TIMEOUT)
                print "[+] cam images cache reset."
            else:
                print "[-] Error in cache update"
    except Exception as err:
        message = 'compile_cam_images exception: %s' % err.message
        current_app.logger.warning(message)
Exemplo n.º 13
0
def compile_large_format_files():
    try:
        with current_app.test_request_context():
            print "[+] Starting large format file cache reset..."
            cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_DB': 0})
            cache.init_app(current_app)

            data = _compile_large_format_files()

            if "error" not in data:
                cache.set('large_format', data, timeout=CACHE_TIMEOUT)
                print "[+] large format files updated."
            else:
                print "[-] Error in large file format update"
    except Exception as err:
        message = 'compile_large_format_files exception: %s' % err.message
        current_app.logger.warning(message)
Exemplo n.º 14
0
def compile_assets():
    try:
        print '\n debug - *** tasks - compile_assets()'
        with current_app.test_request_context():
            print "[+] Starting asset cache reset..."
            cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_DB': 0})
            cache.init_app(current_app)
            url = current_app.config['UFRAME_ASSETS_URL'] + '/%s' % ('assets')
            payload = requests.get(url)
            if payload.status_code is 200:

                # Cache assets_list
                data = payload.json()
                assets, asset_rds = _compile_assets(data)
                if "error" not in assets:
                    cache.set('asset_list', assets, timeout=CACHE_TIMEOUT)
                    print "[+] Asset list cache reset"

                    # Cache assets_dict (based on success of _compile_assets returning assets)
                    assets_dict = get_assets_dict_from_list(assets)
                    if not assets_dict:
                        message = 'Warning: get_assets_dict_from_list returned empty assets_dict.'
                        print '\n debug -- message: ', message
                        current_app.logger.info(message)
                    if isinstance(assets_dict, dict):
                        cache.set('assets_dict', assets_dict, timeout=CACHE_TIMEOUT)
                        print "[+] Assets dictionary cache reset"
                    else:
                        print "[-] Error in Assets dictionary cache update"
                else:
                    print "[-] Error in asset_list and asset_dict cache update"

                # Cache assets_rd
                if asset_rds:
                    cache.set('asset_rds', asset_rds, timeout=CACHE_TIMEOUT)
                    print "[+] Asset reference designators cache reset..."
                else:
                    print "[-] Error in asset_rds cache update"

            else:
                print "[-] Error in cache update"
    except Exception as err:
        message = 'compile_assets exception: %s' % err.message
        current_app.logger.warning(message)
        raise Exception(message)
Exemplo n.º 15
0
class CachedStore(SessionStore):

    def __init__(self, app, session_cache_config=None, app_cache_config=None):
        SessionStore.__init__(self)
        # check if app cache config exists, otherwise use the same as cache_config
        if app_cache_config and not session_cache_config:
            self._app_cache_client = Cache(config=app_cache_config)
            self._session_cache_client = Cache(config=app_cache_config)
        elif app_cache_config and session_cache_config:
            self._app_cache_client = Cache(config=app_cache_config)
            self._session_cache_client = Cache(config=session_cache_config)
        elif not app_cache_config and session_cache_config:
            self._app_cache_client = Cache(config=session_cache_config)
            self._session_cache_client = Cache(config=session_cache_config)
        else:
            self._app_cache_client = self._session_cache_client = Cache()
        self._app_cache_client.init_app(app)
        #self._session_cache_client.init_app(app)
        # now set the app config to contain the cache
        app.config['_session_cache'] = self._session_cache_client
        app.config['_app_cache'] = self._app_cache_client

    def save(self, session):
        key = self._get_memcache_key(session.sid)
        data = json.dumps(dict(session))
        print "{0}:{1}".format(key, data)
        self._cache_client.set(key, data)

    def delete(self, session):
        key = self._get_memcache_key(session.sid)
        self._memcache_client.delete(key)

    def get(self, sid):
        key = self._get_memcache_key(sid)
        data = self._memcache_client.get(key)
        if data is not None:
           session = json.loads(data)
        else:
            session = {}
        return self.session_class(session, sid, False)

    def _get_memcache_key(self, sid):
        if isinstance(sid, unicode):
            sid = sid.encode('utf-8')
        return sid
Exemplo n.º 16
0
def compile_glider_tracks():
    try:
        with current_app.test_request_context():
            print "[+] Starting glider tracks cache reset..."
            cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_DB': 0})
            cache.init_app(current_app)

            glider_tracks = _compile_glider_tracks(True)

            if "error" not in glider_tracks:
                cache.set('glider_tracks', glider_tracks, timeout=CACHE_TIMEOUT)
                print "[+] Glider tracks cache reset."
            else:
                print "[-] Error in cache update"

    except Exception as err:
        message = 'compile_glider_tracks exception: %s' % err.message
        current_app.logger.warning(message)
Exemplo n.º 17
0
def run():
    """Runs the flask app using the config.ini found in the working dir."""
    import webcronmon
    import webcronmon.config

    config = webcronmon.active_config = webcronmon.config.load()

    webcronmon.app.debug = config.app.debug
    cache = Cache(config=config.cache.as_dictionary)
    cache.init_app(webcronmon.app)

    import webcronmon.api
    webcronmon.api.list_monitors = cache.cached(
        key_prefix='list_monitors',
        timeout=config.api_cache.list_monitors
    )(webcronmon.api.list_monitors)
    webcronmon.api.list_monitor_states = cache.cached(
        key_prefix='list_monitor_states',
        timeout=config.api_cache.list_monitor_states
    )(webcronmon.api.list_monitor_states)
    webcronmon.api.list_monitor_uptimes = cache.cached(
        key_prefix='list_monitor_uptimes',
        timeout=config.api_cache.list_monitor_uptimes
    )(webcronmon.api.list_monitor_uptimes)

    import webcronmon.views
    for route, shown_groups in config.routes:
        view = partial(
            webcronmon.views.show_monitors,
            config=config,
            shown_groups=shown_groups
        )
        webcronmon.app.add_url_rule(route, route.replace('/', '-'), view)

    # force logging through webcronmon
    webcronmon.app._logger = logging.getLogger('webcronmon')
    webcronmon.app.logger_name = 'webcronmon'

    try:
        webcronmon.app.run(
            host=config.app.host, port=config.app.port, debug=config.app.debug,
        )
    except KeyboardInterrupt:
        pass
Exemplo n.º 18
0
def compile_bad_assets():
    try:
        with current_app.test_request_context():
            print "[+] Starting bad asset cache reset..."
            cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_DB': 0})
            cache.init_app(current_app)
            url = current_app.config['UFRAME_ASSETS_URL'] + '/assets'
            payload = requests.get(url)
            if payload.status_code is 200:
                data = payload.json()
                bad_assets = _compile_bad_assets(data)
                if "error" not in bad_assets:
                    cache.set('bad_asset_list', bad_assets, timeout=CACHE_TIMEOUT)
                    print "[+] Bad asset cache reset"
                else:
                    print "[-] Error in cache update"
    except Exception as err:
        message = 'compile_bad_assets exception: %s' % err.message
        current_app.logger.warning(message)
Exemplo n.º 19
0
def run():
    """Runs the flask app using the config.ini found in the working dir."""
    import webcronmon
    import webcronmon.config

    config = webcronmon.active_config = webcronmon.config.load()

    webcronmon.app.debug = config.app.debug
    cache = Cache(config=config.cache.as_dictionary)
    cache.init_app(webcronmon.app)

    import webcronmon.api
    webcronmon.api.list_monitors = cache.cached(
        key_prefix='list_monitors',
        timeout=config.api_cache.list_monitors)(webcronmon.api.list_monitors)
    webcronmon.api.list_monitor_states = cache.cached(
        key_prefix='list_monitor_states',
        timeout=config.api_cache.list_monitor_states)(
            webcronmon.api.list_monitor_states)
    webcronmon.api.list_monitor_uptimes = cache.cached(
        key_prefix='list_monitor_uptimes',
        timeout=config.api_cache.list_monitor_uptimes)(
            webcronmon.api.list_monitor_uptimes)

    import webcronmon.views
    for route, shown_groups in config.routes:
        view = partial(webcronmon.views.show_monitors,
                       config=config,
                       shown_groups=shown_groups)
        webcronmon.app.add_url_rule(route, route.replace('/', '-'), view)

    # force logging through webcronmon
    webcronmon.app._logger = logging.getLogger('webcronmon')
    webcronmon.app.logger_name = 'webcronmon'

    try:
        webcronmon.app.run(
            host=config.app.host,
            port=config.app.port,
            debug=config.app.debug,
        )
    except KeyboardInterrupt:
        pass
Exemplo n.º 20
0
def compile_vocabulary():
    try:
        with current_app.test_request_context():
            print "[+] Starting vocabulary cache reset..."
            cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_DB': 0})
            cache.init_app(current_app)
            url = current_app.config['UFRAME_VOCAB_URL'] + '/vocab'
            payload = requests.get(url)
            if payload.status_code is 200:
                data = payload.json()
                vocab_dict, vocab_codes = compile_vocab(data)
                if "error" not in vocab_dict:
                    cache.set('vocab_dict', vocab_dict, timeout=CACHE_TIMEOUT)
                    cache.set('vocab_codes', codes, timeout=CACHE_TIMEOUT)
                    print "[+] Vocabulary cache reset"
                else:
                    print "[-] Error in cache update"
    except Exception as err:
        message = 'compile_vocabulary exception: %s' % err.message
        current_app.logger.warning(message)
Exemplo n.º 21
0
def compile_c2_toc():
    try:
        c2_toc = {}
        with current_app.test_request_context():
            print "[+] Starting c2 toc cache reset..."
            cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_DB': 0})
            cache.init_app(current_app)
            try:
                c2_toc = _compile_c2_toc()
            except Exception as err:
                message = 'Error processing compile_c2_toc: ', err.message
                current_app.logger.warning(message)

            if c2_toc is not None:
                cache.set('c2_toc', c2_toc, timeout=CACHE_TIMEOUT)
                print "[+] C2 toc cache reset..."
            else:
                print "[-] Error in cache update"

    except Exception as err:
        message = 'compile_c2_toc exception: ', err.message
        current_app.logger.warning(message)
Exemplo n.º 22
0
def create_app():
    """创建Flask app"""
    app = Flask(__name__)
    cache = Cache(app, config={'CACHE_TYPE': 'simple'})
    cache.init_app(app)
    # Load config
    config = load_config()
    app.config.from_object(config)

    # CSRF protect
    csrf.init_app(app)

    # 注册组件
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_logger(app)
    register_uploadsets(app)

    # before every request
    @app.before_request
    def before_request():
        """Do something before request"""
        # 记录用户的访问时间到redis
        g.user = get_current_user()
        if g.user:
            set_user_active_time(g.user.id)
            g.msg_num = MailBox.query.filter(MailBox.recver_id == g.user.id,
                                             MailBox.result == None).count()

    from .utils.devices import Devices

    devices = Devices(app)

    return app
Exemplo n.º 23
0
def compile_assets_rd():
    try:
        asset_rds = {}
        with current_app.test_request_context():
            print "[+] Starting asset reference designators cache reset..."

            cache = Cache(config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_DB': 0})
            cache.init_app(current_app)
            try:
                asset_rds, _ = _compile_asset_rds()
            except Exception as err:
                message = 'Error processing _compile_asset_rds: ', err.message
                current_app.logger.warning(message)

        if asset_rds:
            cache.set('asset_rds', asset_rds, timeout=CACHE_TIMEOUT)
            print "[+] Asset reference designators cache reset..."
        else:
            print "[-] Error in cache update"

    except Exception as err:
        message = 'compile_asset_rds exception: %s' % err.message
        current_app.logger.warning(message)
        raise Exception(message)
Exemplo n.º 24
0
 def test_23_init_app_sets_app_attribute(self):
     cache = Cache()
     cache.init_app(self.app)
     assert cache.app == self.app
Exemplo n.º 25
0
def create_app_ext(flask_config_file=None, flask_config_dict=None,
                   moin_config_class=None, warn_default=True, **kwargs):
    """
    Factory for moin wsgi apps

    :param flask_config_file: a flask config file name (may have a MOINCFG class),
                              if not given, a config pointed to by MOINCFG env var
                              will be loaded (if possible).
    :param flask_config_dict: a dict used to update flask config (applied after
                              flask_config_file was loaded [if given])
    :param moin_config_class: if you give this, it'll be instantiated as app.cfg,
                              otherwise it'll use MOINCFG from flask config. If that
                              also is not there, it'll use the DefaultConfig built
                              into MoinMoin.
    :param warn_default: emit a warning if moin falls back to its builtin default
                         config (maybe user forgot to specify MOINCFG?)
    :param kwargs: if you give additional keyword args, the keys/values will get patched
                   into the moin configuration class (before its instance is created)
    """
    clock = Clock()
    clock.start('create_app total')
    app = Flask('MoinMoin')
    clock.start('create_app load config')
    if flask_config_file:
        app.config.from_pyfile(flask_config_file)
    else:
        if not app.config.from_envvar('MOINCFG', silent=True):
            # no MOINCFG env variable set, try stuff in cwd:
            from os import path
            flask_config_file = path.abspath('wikiconfig_local.py')
            if not path.exists(flask_config_file):
                flask_config_file = path.abspath('wikiconfig.py')
                if not path.exists(flask_config_file):
                    flask_config_file = None
            if flask_config_file:
                app.config.from_pyfile(flask_config_file)
    if flask_config_dict:
        app.config.update(flask_config_dict)
    Config = moin_config_class
    if not Config:
        Config = app.config.get('MOINCFG')
    if not Config:
        if warn_default:
            logging.warning("using builtin default configuration")
        from MoinMoin.config.default import DefaultConfig as Config
    for key, value in kwargs.iteritems():
        setattr(Config, key, value)
    if Config.secrets is None:
        # reuse the secret configured for flask (which is required for sessions)
        Config.secrets = app.config.get('SECRET_KEY')
    app.cfg = Config()
    clock.stop('create_app load config')
    clock.start('create_app register')
    # register converters
    from werkzeug.routing import BaseConverter

    class ItemNameConverter(BaseConverter):
        """Like the default :class:`UnicodeConverter`, but it also matches
        slashes (except at the beginning AND end).
        This is useful for wikis and similar applications::

            Rule('/<itemname:wikipage>')
            Rule('/<itemname:wikipage>/edit')
        """
        regex = '[^/]+?(/[^/]+?)*'
        weight = 200

    app.url_map.converters['itemname'] = ItemNameConverter
    # register modules, before/after request functions
    from MoinMoin.apps.frontend import frontend
    frontend.before_request(before_wiki)
    frontend.teardown_request(teardown_wiki)
    app.register_blueprint(frontend)
    from MoinMoin.apps.admin import admin
    admin.before_request(before_wiki)
    admin.teardown_request(teardown_wiki)
    app.register_blueprint(admin, url_prefix='/+admin')
    from MoinMoin.apps.feed import feed
    feed.before_request(before_wiki)
    feed.teardown_request(teardown_wiki)
    app.register_blueprint(feed, url_prefix='/+feed')
    from MoinMoin.apps.misc import misc
    misc.before_request(before_wiki)
    misc.teardown_request(teardown_wiki)
    app.register_blueprint(misc, url_prefix='/+misc')
    from MoinMoin.apps.serve import serve
    app.register_blueprint(serve, url_prefix='/+serve')
    clock.stop('create_app register')
    clock.start('create_app flask-cache')
    cache = Cache()
    cache.init_app(app)
    app.cache = cache
    clock.stop('create_app flask-cache')
    # init storage
    clock.start('create_app init backends')
    init_backends(app)
    clock.stop('create_app init backends')
    clock.start('create_app flask-babel')
    i18n_init(app)
    clock.stop('create_app flask-babel')
    # configure templates
    clock.start('create_app flask-themes')
    setup_themes(app)
    if app.cfg.template_dirs:
        app.jinja_env.loader = ChoiceLoader([
            FileSystemLoader(app.cfg.template_dirs),
            app.jinja_env.loader,
        ])
    app.register_error_handler(403, themed_error)
    clock.stop('create_app flask-themes')
    clock.stop('create_app total')
    del clock
    return app
Exemplo n.º 26
0
from pqr import pqr, secret_config

from settings import APP_JSON, APP_MOL2, APP_ARTICLES

# Python library imports
import os
import ujson as json
import markdown
import datetime
from Levenshtein import ratio

# Regular expressions for chemical formula parsing
import re

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

redirect_table = {}
amount_mol = None
MOLECULE_OF_THE_WEEK = 'GZCGUPFRVQAUEE-SLPGGIOYSA-N'
WEEKLY_MOL_NAME = None
pqr.debug = True

last_updated_wm = datetime.datetime.strptime('Aug 7 1996', '%b %d %Y').date()

Masses = dict(H=1.01,
              He=4.00,
              Li=6.94,
              Be=9.01,
              B=10.81,
              C=12.01,
Exemplo n.º 27
0
from flask import Flask, url_for, request, send_from_directory, redirect
from flask import render_template
from flask.ext.cache import Cache
from jinja2 import FileSystemLoader



cache = Cache(config={'CACHE_TYPE': 'simple'})

app = Flask(__name__)
cache.init_app(app)


@app.route('/')
@cache.cached()
def main():
    return redirect("http://jemyoung.com/about/")


@app.route('/about/')
def about():
    dev = request.args.get('dev', False)
    return render_template('about.html', dev=dev)


@app.route('/blog/')
def blog():
    return redirect("http://blog.jemyoung.com", code=302)

# @app.route('/robots.txt')
# @cache.cached()
Exemplo n.º 28
0
def init(app):
    global cache
    cache = Cache(app, config={'CACHE_TYPE': 'memcached'})
    cache.init_app(app)
Exemplo n.º 29
0
 def test_19_dict_config_both(self):
     cache = Cache(config={'CACHE_TYPE': 'null'})
     cache.init_app(self.app, config={'CACHE_TYPE': 'simple'})
     from werkzeug.contrib.cache import SimpleCache
     assert isinstance(self.app.extensions['cache'][cache], SimpleCache)
Exemplo n.º 30
0
app.config['CONFIG_FILE'] = os.path.abspath('app/config.yaml')
app.config['PROPAGATE_EXCEPTIONS'] = True
configStr = open(app.config['CONFIG_FILE'], 'r')
app.config['CONFIG'] = yaml.load(configStr)
sqlite_db = os.path.abspath('db/elastatus.db')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////%s' % sqlite_db

# Allow arbitrary python code in Jinja templates
app.jinja_options['extensions'].append('jinja2.ext.do')

db = SQLAlchemy(app)
auth = HTTPBasicAuth()
mail = Mail(app)
cache = Cache()
cache.init_app(app, config={'CACHE_TYPE': 'simple',
                            'CACHE_DEFAULT_TIMEOUT':app.config['CONFIG']['sgaudit']['cache_timeout']
                            })

if app.config['CONFIG']['jobs']['enabled']:
    from jobs import *


from app.models import *

@app.before_first_request
def create_db():
    if not os.path.exists(sqlite_db):
        db.create_all()


from views import elastatus as elastatus
Exemplo n.º 31
0
#coding=utf-8
#!/usr/bin/env python
from flask import Flask
from admin.admin import admin
from blog.blog import blog
from flask.ext.cache import Cache
cache = Cache(config={'CACHE_TYPE': 'simple'})
config = {
    'CACHE_TYPE': 'redis',
    'CACHE_REDIS_HOST': '10.10.10.57',
    'CACHE_REDIS_PORT': 6379,
    'CACHE_REDIS_DB': '',
    'CACHE_REDIS_PASSWORD': ''
}
pyshell = Flask(__name__, template_folder='templates', static_folder='static')

pyshell.config.from_object(config)
cache.init_app(pyshell, )
pyshell.register_blueprint(admin, url_prefix='/admin')
pyshell.register_blueprint(blog, url_prefix='/blog')

if __name__ == '__main__':
    pyshell.run()
    #pyshell.run(host='0.0.0.0', port=5000, debug=True)
Exemplo n.º 32
0
    def test_18_dict_config_initapp(self):
        cache = Cache()
        cache.init_app(self.app, config={'CACHE_TYPE': 'simple'})

        assert cache.config['CACHE_TYPE'] == 'simple'
Exemplo n.º 33
0
class CacheTestCase(unittest.TestCase):
    def setUp(self):
        app = Flask(__name__)

        app.debug = False
        app.config['CACHE_TYPE'] = 'simple'

        self.cache = Cache()
        self.cache.init_app(app)

        self.app = app

    def tearDown(self):
        self.app = None
        self.cache = None
        self.tc = None

    def test_00_set(self):
        self.cache.set('hi', 'hello')

        assert self.cache.get('hi') == 'hello'

    def test_01_add(self):
        self.cache.add('hi', 'hello')

        assert self.cache.get('hi') == 'hello'

        self.cache.add('hi', 'foobar')

        assert self.cache.get('hi') == 'hello'

    def test_02_delete(self):
        self.cache.set('hi', 'hello')

        self.cache.delete('hi')

        assert self.cache.get('hi') is None

    def test_03_cached_view(self):
        @self.app.route('/')
        @self.cache.cached(5)
        def cached_view():
            return str(time.time())

        tc = self.app.test_client()

        rv = tc.get('/')
        the_time = rv.data

        time.sleep(2)

        rv = tc.get('/')

        assert the_time == rv.data

        time.sleep(5)

        rv = tc.get('/')
        assert the_time != rv.data

    def test_04_cached_view_unless(self):
        @self.app.route('/a')
        @self.cache.cached(5, unless=lambda: True)
        def non_cached_view():
            return str(time.time())

        @self.app.route('/b')
        @self.cache.cached(5, unless=lambda: False)
        def cached_view():
            return str(time.time())

        tc = self.app.test_client()

        rv = tc.get('/a')
        the_time = rv.data

        time.sleep(1)

        rv = tc.get('/a')
        assert the_time != rv.data

        rv = tc.get('/b')
        the_time = rv.data

        time.sleep(1)
        rv = tc.get('/b')

        assert the_time == rv.data

    def test_05_cached_function(self):

        with self.app.test_request_context():

            @self.cache.cached(2, key_prefix='MyBits')
            def get_random_bits():
                return [random.randrange(0, 2) for i in range(50)]

            my_list = get_random_bits()
            his_list = get_random_bits()

            assert my_list == his_list

            time.sleep(4)

            his_list = get_random_bits()

            assert my_list != his_list

    def test_06_memoize(self):

        with self.app.test_request_context():

            @self.cache.memoize(5)
            def big_foo(a, b):
                return a + b + random.randrange(0, 100000)

            result = big_foo(5, 2)

            time.sleep(1)

            assert big_foo(5, 2) == result

            result2 = big_foo(5, 3)
            assert result2 != result

            time.sleep(4)

            assert big_foo(5, 2) != result
            assert big_foo(5, 3) == result2

            time.sleep(1)

            assert big_foo(5, 3) != result2

    def test_07_delete_memoize(self):

        with self.app.test_request_context():

            @self.cache.memoize(5)
            def big_foo(a, b):
                return a + b + random.randrange(0, 100000)

            result = big_foo(5, 2)
            result2 = big_foo(5, 3)

            time.sleep(1)

            assert big_foo(5, 2) == result
            assert big_foo(5, 2) == result
            assert big_foo(5, 3) != result
            assert big_foo(5, 3) == result2

            self.cache.delete_memoized(big_foo)

            assert big_foo(5, 2) != result
            assert big_foo(5, 3) != result2

    def test_08_delete_memoize(self):

        with self.app.test_request_context():

            @self.cache.memoize()
            def big_foo(a, b):
                return a + b + random.randrange(0, 100000)

            result_a = big_foo(5, 1)
            result_b = big_foo(5, 2)

            assert big_foo(5, 1) == result_a
            assert big_foo(5, 2) == result_b

            self.cache.delete_memoized(big_foo, 5, 2)

            assert big_foo(5, 1) == result_a
            assert big_foo(5, 2) != result_b

    def test_09_args_memoize(self):

        with self.app.test_request_context():

            @self.cache.memoize()
            def big_foo(a, b):
                return sum(a) + sum(b) + random.randrange(0, 100000)

            result_a = big_foo([5, 3, 2], [1])
            result_b = big_foo([3, 3], [3, 1])

            assert big_foo([5, 3, 2], [1]) == result_a
            assert big_foo([3, 3], [3, 1]) == result_b

            self.cache.delete_memoized(big_foo, [5, 3, 2], [1])

            assert big_foo([5, 3, 2], [1]) != result_a
            assert big_foo([3, 3], [3, 1]) == result_b

    def test_10_kwargs_memoize(self):

        with self.app.test_request_context():

            @self.cache.memoize()
            def big_foo(a, b=None):
                return a + sum(b.values()) + random.randrange(0, 100000)

            result_a = big_foo(1, dict(one=1, two=2))
            result_b = big_foo(5, dict(three=3, four=4))

            assert big_foo(1, dict(one=1, two=2)) == result_a
            assert big_foo(5, dict(three=3, four=4)) == result_b

            self.cache.delete_memoized(big_foo, 1, dict(one=1, two=2))

            assert big_foo(1, dict(one=1, two=2)) != result_a
            assert big_foo(5, dict(three=3, four=4)) == result_b

    def test_11_cache_key_property(self):
        @self.app.route('/')
        @self.cache.cached(5)
        def cached_view():
            return str(time.time())

        assert hasattr(cached_view, "make_cache_key")
        assert callable(cached_view.make_cache_key)

        tc = self.app.test_client()

        rv = tc.get('/')
        the_time = rv.data

        with self.app.test_request_context():
            cache_data = self.cache.get(cached_view.make_cache_key())
            assert the_time == cache_data

    def test_12_make_cache_key_function_property(self):
        @self.app.route('/<foo>/<bar>')
        @self.cache.memoize(5)
        def cached_view(foo, bar):
            return str(time.time())

        assert hasattr(cached_view, "make_cache_key")
        assert callable(cached_view.make_cache_key)

        tc = self.app.test_client()

        rv = tc.get('/a/b')
        the_time = rv.data

        cache_key = cached_view.make_cache_key(cached_view.uncached,
                                               foo=u"a",
                                               bar=u"b")
        cache_data = self.cache.get(cache_key)
        assert the_time == cache_data

        different_key = cached_view.make_cache_key(cached_view.uncached,
                                                   foo=u"b",
                                                   bar=u"a")
        different_data = self.cache.get(different_key)
        assert the_time != different_data

    def test_13_cache_timeout_property(self):
        @self.app.route('/')
        @self.cache.memoize(5)
        def cached_view1():
            return str(time.time())

        @self.app.route('/<foo>/<bar>')
        @self.cache.memoize(10)
        def cached_view2(foo, bar):
            return str(time.time())

        assert hasattr(cached_view1, "cache_timeout")
        assert hasattr(cached_view2, "cache_timeout")
        assert cached_view1.cache_timeout == 5
        assert cached_view2.cache_timeout == 10

        # test that this is a read-write property
        cached_view1.cache_timeout = 2
        cached_view2.cache_timeout = 3

        assert cached_view1.cache_timeout == 2
        assert cached_view2.cache_timeout == 3

        tc = self.app.test_client()

        rv1 = tc.get('/')
        time1 = rv1.data
        time.sleep(1)
        rv2 = tc.get('/a/b')
        time2 = rv2.data

        # VIEW1
        # it's been 1 second, cache is still active
        assert time1 == tc.get('/').data
        time.sleep(2)
        # it's been 3 seconds, cache is not still active
        assert time1 != tc.get('/').data

        # VIEW2
        # it's been 2 seconds, cache is still active
        assert time2 == tc.get('/a/b').data
        time.sleep(2)
        # it's been 4 seconds, cache is not still active
        assert time2 != tc.get('/a/b').data

    def test_14_memoized_multiple_arg_kwarg_calls(self):
        with self.app.test_request_context():

            @self.cache.memoize()
            def big_foo(a, b, c=[1, 1], d=[1, 1]):
                return sum(a) + sum(b) + sum(c) + sum(d) + random.randrange(
                    0, 100000)

            result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])

            assert big_foo([5, 3, 2], [1], d=[3, 3], c=[3, 3]) == result_a
            assert big_foo(b=[1], a=[5, 3, 2], c=[3, 3], d=[3, 3]) == result_a
            assert big_foo([5, 3, 2], [1], [3, 3], [3, 3]) == result_a

    def test_15_memoize_multiple_arg_kwarg_delete(self):
        with self.app.test_request_context():

            @self.cache.memoize()
            def big_foo(a, b, c=[1, 1], d=[1, 1]):
                return sum(a) + sum(b) + sum(c) + sum(d) + random.randrange(
                    0, 100000)

            result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
            self.cache.delete_memoized(big_foo, [5, 3, 2], [1], [3, 3], [3, 3])
            result_b = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5, 3, 2],
                                       b=[1],
                                       c=[3, 3],
                                       d=[3, 3])
            result_b = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5, 3, 2], [1],
                                       c=[3, 3],
                                       d=[3, 3])
            result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5, 3, 2],
                                       b=[1],
                                       c=[3, 3],
                                       d=[3, 3])
            result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5, 3, 2], [1],
                                       c=[3, 3],
                                       d=[3, 3])
            result_b = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5, 3, 2], [1], [3, 3], [3, 3])
            result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
            assert result_a != result_b

    def test_16_memoize_kwargs_to_args(self):
        with self.app.test_request_context():

            def big_foo(a, b, c=None, d=None):
                return sum(a) + sum(b) + random.randrange(0, 100000)

            expected = (1, 2, 'foo', 'bar')

            args, kwargs = self.cache.memoize_kwargs_to_args(
                big_foo, 1, 2, 'foo', 'bar')
            assert (args == expected)
            args, kwargs = self.cache.memoize_kwargs_to_args(big_foo,
                                                             2,
                                                             'foo',
                                                             'bar',
                                                             a=1)
            assert (args == expected)
            args, kwargs = self.cache.memoize_kwargs_to_args(big_foo,
                                                             a=1,
                                                             b=2,
                                                             c='foo',
                                                             d='bar')
            assert (args == expected)
            args, kwargs = self.cache.memoize_kwargs_to_args(big_foo,
                                                             d='bar',
                                                             b=2,
                                                             a=1,
                                                             c='foo')
            assert (args == expected)
            args, kwargs = self.cache.memoize_kwargs_to_args(big_foo,
                                                             1,
                                                             2,
                                                             d='bar',
                                                             c='foo')
            assert (args == expected)

    def test_17_dict_config(self):
        cache = Cache(config={'CACHE_TYPE': 'simple'})
        cache.init_app(self.app)

        assert cache.config['CACHE_TYPE'] == 'simple'

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

        assert cache.config['CACHE_TYPE'] == 'simple'

    def test_19_dict_config_both(self):
        cache = Cache(config={'CACHE_TYPE': 'null'})
        cache.init_app(self.app, config={'CACHE_TYPE': 'simple'})

        assert cache.config['CACHE_TYPE'] == 'simple'
Exemplo n.º 34
0
    def test_19_dict_config_both(self):
        cache = Cache(config={'CACHE_TYPE': 'null'})
        cache.init_app(self.app, config={'CACHE_TYPE': 'simple'})

        assert cache.config['CACHE_TYPE'] == 'simple'
Exemplo n.º 35
0
import os, json
from urlparse import urlparse, urljoin
from notifications import send_prr_email
from spam import is_spam, is_working_akismet_key
from requests import get
from time import time
from flask.ext.cache import Cache
from recaptcha.client import captcha

# Initialize login
login_manager = LoginManager()
login_manager.init_app(app)

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



# Submitting a new request
def new_request(passed_recaptcha = False, data = None):
	if request.method == 'POST' or data:
		if not passed_recaptcha:
			data = request.form.copy()
		email = data['request_email']
		request_text = data['request_text']
		if request_text == "":
			return render_template('error.html', message = "You cannot submit an empty request.")
		if email == "" and 'ignore_email' not in data and not passed_recaptcha:
			return render_template('missing_email.html', form = data, user_id = get_user_id())
		if is_spam(request_text) and not passed_recaptcha:
Exemplo n.º 36
0
class CacheTestCase(unittest.TestCase):

    def setUp(self):
        app = Flask(__name__)

        app.debug = False
        app.config['CACHE_TYPE'] = 'simple'

        self.cache = Cache()
        self.cache.init_app(app)

        self.app = app

    def tearDown(self):
        self.app = None
        self.cache = None
        self.tc = None

    def test_00_set(self):
        self.cache.set('hi', 'hello')

        assert self.cache.get('hi') == 'hello'

    def test_01_add(self):
        self.cache.add('hi', 'hello')

        assert self.cache.get('hi') == 'hello'

        self.cache.add('hi', 'foobar')

        assert self.cache.get('hi') == 'hello'

    def test_02_delete(self):
        self.cache.set('hi', 'hello')

        self.cache.delete('hi')

        assert self.cache.get('hi') is None

    def test_03_cached_view(self):

        @self.app.route('/')
        @self.cache.cached(5)
        def cached_view():
            return str(time.time())

        tc = self.app.test_client()

        rv = tc.get('/')
        the_time = rv.data

        time.sleep(2)

        rv = tc.get('/')

        assert the_time == rv.data

        time.sleep(5)

        rv = tc.get('/')
        assert the_time != rv.data

    def test_04_cached_view_unless(self):
        @self.app.route('/a')
        @self.cache.cached(5, unless=lambda: True)
        def non_cached_view():
            return str(time.time())

        @self.app.route('/b')
        @self.cache.cached(5, unless=lambda: False)
        def cached_view():
            return str(time.time())

        tc = self.app.test_client()

        rv = tc.get('/a')
        the_time = rv.data

        time.sleep(1)

        rv = tc.get('/a')
        assert the_time != rv.data

        rv = tc.get('/b')
        the_time = rv.data

        time.sleep(1)
        rv = tc.get('/b')

        assert the_time == rv.data

    def test_05_cached_function(self):

        with self.app.test_request_context():
            @self.cache.cached(2, key_prefix='MyBits')
            def get_random_bits():
                return [random.randrange(0, 2) for i in range(50)]

            my_list = get_random_bits()
            his_list = get_random_bits()

            assert my_list == his_list

            time.sleep(4)

            his_list = get_random_bits()

            assert my_list != his_list

    def test_06_memoize(self):

        with self.app.test_request_context():
            @self.cache.memoize(5)
            def big_foo(a, b):
                return a+b+random.randrange(0, 100000)

            result = big_foo(5, 2)

            time.sleep(1)

            assert big_foo(5, 2) == result

            result2 = big_foo(5, 3)
            assert result2 != result

            time.sleep(4)

            assert big_foo(5, 2) != result
            assert big_foo(5, 3) == result2

            time.sleep(1)

            assert big_foo(5, 3) != result2

    def test_07_delete_memoize(self):

        with self.app.test_request_context():
            @self.cache.memoize(5)
            def big_foo(a, b):
                return a+b+random.randrange(0, 100000)

            result = big_foo(5, 2)
            result2 = big_foo(5, 3)

            time.sleep(1)

            assert big_foo(5, 2) == result
            assert big_foo(5, 2) == result
            assert big_foo(5, 3) != result
            assert big_foo(5, 3) == result2

            self.cache.delete_memoized(big_foo)

            assert big_foo(5, 2) != result
            assert big_foo(5, 3) != result2


    def test_08_delete_memoize(self):

        with self.app.test_request_context():
            @self.cache.memoize()
            def big_foo(a, b):
                return a+b+random.randrange(0, 100000)

            result_a = big_foo(5, 1)
            result_b = big_foo(5, 2)

            assert big_foo(5, 1) == result_a
            assert big_foo(5, 2) == result_b

            self.cache.delete_memoized(big_foo, 5, 2)

            assert big_foo(5, 1) == result_a
            assert big_foo(5, 2) != result_b

    def test_09_args_memoize(self):

        with self.app.test_request_context():
            @self.cache.memoize()
            def big_foo(a, b):
                return sum(a)+sum(b)+random.randrange(0, 100000)

            result_a = big_foo([5,3,2], [1])
            result_b = big_foo([3,3], [3,1])

            assert big_foo([5,3,2], [1]) == result_a
            assert big_foo([3,3], [3,1]) == result_b

            self.cache.delete_memoized(big_foo, [5,3,2], [1])

            assert big_foo([5,3,2], [1]) != result_a
            assert big_foo([3,3], [3,1]) == result_b

    def test_10_kwargs_memoize(self):

        with self.app.test_request_context():
            @self.cache.memoize()
            def big_foo(a, b=None):
                return a+sum(b.values())+random.randrange(0, 100000)

            result_a = big_foo(1, dict(one=1,two=2))
            result_b = big_foo(5, dict(three=3,four=4))

            assert big_foo(1, dict(one=1,two=2)) == result_a
            assert big_foo(5, dict(three=3,four=4)) == result_b

            self.cache.delete_memoized(big_foo, 1, dict(one=1,two=2))

            assert big_foo(1, dict(one=1,two=2)) != result_a
            assert big_foo(5, dict(three=3,four=4)) == result_b

    def test_11_cache_key_property(self):
        @self.app.route('/')
        @self.cache.cached(5)
        def cached_view():
            return str(time.time())

        assert hasattr(cached_view, "make_cache_key")
        assert callable(cached_view.make_cache_key)

        tc = self.app.test_client()

        rv = tc.get('/')
        the_time = rv.data

        with self.app.test_request_context():
            cache_data = self.cache.get(cached_view.make_cache_key())
            assert the_time == cache_data

    def test_12_make_cache_key_function_property(self):
        @self.app.route('/<foo>/<bar>')
        @self.cache.memoize(5)
        def cached_view(foo, bar):
            return str(time.time())

        assert hasattr(cached_view, "make_cache_key")
        assert callable(cached_view.make_cache_key)

        tc = self.app.test_client()

        rv = tc.get('/a/b')
        the_time = rv.data

        cache_key = cached_view.make_cache_key(cached_view.uncached, foo=u"a", bar=u"b")
        cache_data = self.cache.get(cache_key)
        assert the_time == cache_data

        different_key = cached_view.make_cache_key(cached_view.uncached, foo=u"b", bar=u"a")
        different_data = self.cache.get(different_key)
        assert the_time != different_data

    def test_13_cache_timeout_property(self):
        @self.app.route('/')
        @self.cache.memoize(5)
        def cached_view1():
            return str(time.time())

        @self.app.route('/<foo>/<bar>')
        @self.cache.memoize(10)
        def cached_view2(foo, bar):
            return str(time.time())

        assert hasattr(cached_view1, "cache_timeout")
        assert hasattr(cached_view2, "cache_timeout")
        assert cached_view1.cache_timeout == 5
        assert cached_view2.cache_timeout == 10

        # test that this is a read-write property
        cached_view1.cache_timeout = 2
        cached_view2.cache_timeout = 3

        assert cached_view1.cache_timeout == 2
        assert cached_view2.cache_timeout == 3

        tc = self.app.test_client()

        rv1 = tc.get('/')
        time1 = rv1.data
        time.sleep(1)
        rv2 = tc.get('/a/b')
        time2 = rv2.data

        # VIEW1
        # it's been 1 second, cache is still active
        assert time1 == tc.get('/').data
        time.sleep(2)
        # it's been 3 seconds, cache is not still active
        assert time1 != tc.get('/').data

        # VIEW2
        # it's been 2 seconds, cache is still active
        assert time2 == tc.get('/a/b').data
        time.sleep(2)
        # it's been 4 seconds, cache is not still active
        assert time2 != tc.get('/a/b').data

    def test_14_memoized_multiple_arg_kwarg_calls(self):
        with self.app.test_request_context():
            @self.cache.memoize()
            def big_foo(a, b,c=[1,1],d=[1,1]):
                return sum(a)+sum(b)+sum(c)+sum(d)+random.randrange(0, 100000)

            result_a = big_foo([5,3,2], [1], c=[3,3], d=[3,3])

            assert big_foo([5,3,2], [1], d=[3,3], c=[3,3]) == result_a
            assert big_foo(b=[1],a=[5,3,2],c=[3,3],d=[3,3]) == result_a
            assert big_foo([5,3,2], [1], [3,3], [3,3]) == result_a

    def test_15_memoize_multiple_arg_kwarg_delete(self):
        with self.app.test_request_context():
            @self.cache.memoize()
            def big_foo(a, b,c=[1,1],d=[1,1]):
                return sum(a)+sum(b)+sum(c)+sum(d)+random.randrange(0, 100000)

            result_a = big_foo([5,3,2], [1], c=[3,3], d=[3,3])
            self.cache.delete_memoized(big_foo, [5,3,2],[1],[3,3],[3,3])
            result_b = big_foo([5,3,2], [1], c=[3,3], d=[3,3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5,3,2],b=[1],c=[3,3],d=[3,3])
            result_b = big_foo([5,3,2], [1], c=[3,3], d=[3,3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5,3,2],[1],c=[3,3],d=[3,3])
            result_a = big_foo([5,3,2], [1], c=[3,3], d=[3,3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5,3,2],b=[1],c=[3,3],d=[3,3])
            result_a = big_foo([5,3,2], [1], c=[3,3], d=[3,3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5,3,2],[1],c=[3,3],d=[3,3])
            result_b = big_foo([5,3,2], [1], c=[3,3], d=[3,3])
            assert result_a != result_b

            self.cache.delete_memoized(big_foo, [5,3,2],[1],[3,3],[3,3])
            result_a = big_foo([5,3,2], [1], c=[3,3], d=[3,3])
            assert result_a != result_b

    def test_16_memoize_kwargs_to_args(self):
        with self.app.test_request_context():
            def big_foo(a, b, c=None, d=None):
                return sum(a)+sum(b)+random.randrange(0, 100000)

            expected = (1,2,'foo','bar')

            args, kwargs = self.cache.memoize_kwargs_to_args(big_foo, 1,2,'foo','bar')
            assert (args == expected)
            args, kwargs = self.cache.memoize_kwargs_to_args(big_foo, 2,'foo','bar',a=1)
            assert (args == expected)
            args, kwargs = self.cache.memoize_kwargs_to_args(big_foo, a=1,b=2,c='foo',d='bar')
            assert (args == expected)
            args, kwargs = self.cache.memoize_kwargs_to_args(big_foo, d='bar',b=2,a=1,c='foo')
            assert (args == expected)
            args, kwargs = self.cache.memoize_kwargs_to_args(big_foo, 1,2,d='bar',c='foo')
            assert (args == expected)

    def test_17_dict_config(self):
        cache = Cache(config={'CACHE_TYPE': 'simple'})
        cache.init_app(self.app)

        assert cache.config['CACHE_TYPE'] == 'simple'

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

        assert cache.config['CACHE_TYPE'] == 'simple'

    def test_19_dict_config_both(self):
        cache = Cache(config={'CACHE_TYPE': 'null'})
        cache.init_app(self.app, config={'CACHE_TYPE': 'simple'})

        assert cache.config['CACHE_TYPE'] == 'simple'
Exemplo n.º 37
0
from urlparse import urlparse, urljoin
from notifications import send_prr_email
from spam import is_spam, is_working_akismet_key
from requests import get
from time import time
from flask.ext.cache import Cache
from recaptcha.client import captcha
from timeout import timeout

# Initialize login
login_manager = LoginManager()
login_manager.init_app(app)

# Initialize cache
cache = Cache()
cache.init_app(app, config={"CACHE_TYPE": "simple"})


# Submitting a new request
def new_request(passed_recaptcha=False, data=None):
    if data or request.method == "POST":
        if not data and not passed_recaptcha:
            data = request.form.copy()
        email = data["request_email"]
        request_text = data["request_text"]
        if request_text == "":
            return render_template("error.html", message="You cannot submit an empty request.")
        if email == "" and "ignore_email" not in data and not passed_recaptcha:
            return render_template("missing_email.html", form=data, user_id=get_user_id())
        if (app.config["ENVIRONMENT"] == "PRODUCTION") and is_spam(request_text) and not passed_recaptcha:
            return render_template(
Exemplo n.º 38
0
    def test_19_dict_config_both(self):
        cache = Cache(config={'CACHE_TYPE': 'null'})
        cache.init_app(self.app, config={'CACHE_TYPE': 'simple'})

        assert cache.config['CACHE_TYPE'] == 'simple'
Exemplo n.º 39
0
    'Access-Control-Allow-Origin': '*'
}

# Make and configure the Flask app
app = Flask(__name__)
if debug_app:
    app.debug = True

# Set up cache
cache_config = {
    'CACHE_TYPE': 'filesystem',
    'CACHE_THRESHOLD': 1000,
    'CACHE_DIR': 'cache'
}
cache = Cache(config=cache_config)
cache.init_app(app, config=cache_config)


# Just a default route
@app.route('/')
@cache.cached(timeout=500)
def index():
    return 'This is a whitelisted JSON to JSONP proxy.'


# Proxy route
@app.route('/proxy')
def handle_proxy():
    request_url = request.args.get('url', '')
    callback = request.args.get('callback', '')
    request_parsed = urlparse.urlparse(request_url)
Exemplo n.º 40
0
from requests import get
from time import time
from flask.ext.cache import Cache
from recaptcha.client import captcha
from timeout import timeout
from flask import jsonify, request, Response
import anyjson
import helpers

# Initialize login
login_manager = LoginManager()
login_manager.init_app(app)

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

# Set flags:

check_for_spam = False
if app.config['ENVIRONMENT'] == 'PRODUCTION':
	check_for_spam = True

# Submitting a new request
def new_request(passed_recaptcha = False, data = None):
	user_id = get_user_id()
	if data or request.method == 'POST':
		if not data and not passed_recaptcha:
			data = request.form.copy()
		email = data['request_email']
		request_text = data['request_text']
Exemplo n.º 41
0
def create_app_ext(flask_config_file=None,
                   flask_config_dict=None,
                   moin_config_class=None,
                   warn_default=True,
                   **kwargs):
    """
    Factory for moin wsgi apps

    :param flask_config_file: a flask config file name (may have a MOINCFG class),
                              if not given, a config pointed to by MOINCFG env var
                              will be loaded (if possible).
    :param flask_config_dict: a dict used to update flask config (applied after
                              flask_config_file was loaded [if given])
    :param moin_config_class: if you give this, it'll be instantiated as app.cfg,
                              otherwise it'll use MOINCFG from flask config. If that
                              also is not there, it'll use the DefaultConfig built
                              into MoinMoin.
    :param warn_default: emit a warning if moin falls back to its builtin default
                         config (maybe user forgot to specify MOINCFG?)
    :param kwargs: if you give additional keyword args, the keys/values will get patched
                   into the moin configuration class (before its instance is created)
    """
    clock = Clock()
    clock.start('create_app total')
    app = Flask('MoinMoin')
    clock.start('create_app load config')
    if flask_config_file:
        app.config.from_pyfile(flask_config_file)
    else:
        if not app.config.from_envvar('MOINCFG', silent=True):
            # no MOINCFG env variable set, try stuff in cwd:
            from os import path
            flask_config_file = path.abspath('wikiconfig_local.py')
            if not path.exists(flask_config_file):
                flask_config_file = path.abspath('wikiconfig.py')
                if not path.exists(flask_config_file):
                    flask_config_file = None
            if flask_config_file:
                app.config.from_pyfile(flask_config_file)
    if flask_config_dict:
        app.config.update(flask_config_dict)
    Config = moin_config_class
    if not Config:
        Config = app.config.get('MOINCFG')
    if not Config:
        if warn_default:
            logging.warning("using builtin default configuration")
        from MoinMoin.config.default import DefaultConfig as Config
    for key, value in kwargs.iteritems():
        setattr(Config, key, value)
    if Config.secrets is None:
        # reuse the secret configured for flask (which is required for sessions)
        Config.secrets = app.config.get('SECRET_KEY')
    app.cfg = Config()
    clock.stop('create_app load config')
    clock.start('create_app register')
    # register converters
    from werkzeug.routing import BaseConverter

    class ItemNameConverter(BaseConverter):
        """Like the default :class:`UnicodeConverter`, but it also matches
        slashes (except at the beginning AND end).
        This is useful for wikis and similar applications::

            Rule('/<itemname:wikipage>')
            Rule('/<itemname:wikipage>/edit')
        """
        regex = '[^/]+?(/[^/]+?)*'
        weight = 200

    app.url_map.converters['itemname'] = ItemNameConverter
    # register modules, before/after request functions
    from MoinMoin.apps.frontend import frontend
    frontend.before_request(before_wiki)
    frontend.teardown_request(teardown_wiki)
    app.register_blueprint(frontend)
    from MoinMoin.apps.admin import admin
    admin.before_request(before_wiki)
    admin.teardown_request(teardown_wiki)
    app.register_blueprint(admin, url_prefix='/+admin')
    from MoinMoin.apps.feed import feed
    feed.before_request(before_wiki)
    feed.teardown_request(teardown_wiki)
    app.register_blueprint(feed, url_prefix='/+feed')
    from MoinMoin.apps.misc import misc
    misc.before_request(before_wiki)
    misc.teardown_request(teardown_wiki)
    app.register_blueprint(misc, url_prefix='/+misc')
    from MoinMoin.apps.serve import serve
    app.register_blueprint(serve, url_prefix='/+serve')
    clock.stop('create_app register')
    clock.start('create_app flask-cache')
    cache = Cache()
    cache.init_app(app)
    app.cache = cache
    clock.stop('create_app flask-cache')
    # init storage
    clock.start('create_app init backends')
    init_backends(app)
    clock.stop('create_app init backends')
    clock.start('create_app flask-babel')
    i18n_init(app)
    clock.stop('create_app flask-babel')
    # configure templates
    clock.start('create_app flask-themes')
    setup_themes(app)
    if app.cfg.template_dirs:
        app.jinja_env.loader = ChoiceLoader([
            FileSystemLoader(app.cfg.template_dirs),
            app.jinja_env.loader,
        ])
    app.register_error_handler(403, themed_error)
    clock.stop('create_app flask-themes')
    clock.stop('create_app total')
    del clock
    return app
Exemplo n.º 42
0
    def test_17_dict_config(self):
        cache = Cache(config={'CACHE_TYPE': 'simple'})
        cache.init_app(self.app)

        assert cache.config['CACHE_TYPE'] == 'simple'
Exemplo n.º 43
0
app = Flask(__name__)
app.secret_key = 'SUPERSECRET'  # you should change this to something equally random
app.config['CONFIG_FILE'] = os.path.abspath('app/config.yaml')
configStr = open(app.config['CONFIG_FILE'], 'r')
app.config['CONFIG'] = yaml.load(configStr)
sqlite_db = os.path.abspath('db/elastatus.db')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////%s' % sqlite_db

db = SQLAlchemy(app)
auth = HTTPBasicAuth()
mail = Mail(app)
cache = Cache()
cache.init_app(app,
               config={
                   'CACHE_TYPE':
                   'simple',
                   'CACHE_DEFAULT_TIMEOUT':
                   app.config['CONFIG']['sgaudit']['cache_timeout']
               })

if app.config['CONFIG']['jobs']['enabled']:
    from jobs import *

from app.models import *


@app.before_first_request
def create_db():
    if not os.path.exists(sqlite_db):
        db.create_all()
Exemplo n.º 44
0
 def test_23_init_app_sets_app_attribute(self):
     cache = Cache()
     cache.init_app(self.app)
     assert cache.app == self.app
Exemplo n.º 45
0
import models
from wtforms.ext.appengine.ndb import model_form

from xml.dom.minidom import parse
import urllib2
import base64
import datetime
import locale
locale.setlocale(locale.LC_ALL, "")
import unicodedata

# caching
from flask.ext.cache import Cache
cache = Cache(with_jinja2_ext=False)
from application import app
cache.init_app(app, config={'CACHE_TYPE': 'gaememcached'})

syskey = app.config['SYSKEY']


def strip_accents(s):
    return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))


def authorize_user(user):
    if not user:
        return False
    if users.is_current_user_admin():
        return True
    else:
        return False
Exemplo n.º 46
0
class Application(Flask):
    def __init__(self,
                 app_config,
                 import_name,
                 static_path=None,
                 static_url_path=None,
                 static_folder='static',
                 template_folder='templates',
                 instance_path=None,
                 instance_relative_config=False):

        from flask.ext.cache import Cache
        from ambry.library import Library
        from ambry.run import get_runconfig

        self._initialized = False
        self.csrf = CsrfProtect()
        self.login_manager = LoginManager()

        super(Application,
              self).__init__(import_name, static_path, static_url_path,
                             static_folder, template_folder, instance_path,
                             instance_relative_config)

        self.config.update(app_config)

        l = Library(get_runconfig(), read_only=True, echo=False)

        self.cache = Cache(config={
            'CACHE_TYPE': 'filesystem',
            'CACHE_DIR': l.filesystem.cache('ui')
        })
        self.cache.init_app(self)

    def __call__(self, environ, start_response):

        if not self._initialized:
            from ambry.library import Library
            from ambry.run import get_runconfig

            rc = get_runconfig()
            l = Library(rc, read_only=True, echo=False)

            secret_key = None

            if os.getenv('AMBRY_UI_SECRET'):
                app.logger.info("Using secret_key from env")
                secret_key = os.getenv('AMBRY_UI_SECRET')

            if not secret_key and l.ui_config.secret:
                app.logger.info("Using secret_key from library")
                secret_key = l.ui_config.secret

            if not secret_key:
                from uuid import uuid4
                app.logger.warn(
                    "SECRET_KEY was not set. Setting to a random value")
                secret_key = str(
                    uuid4())  # Must be the same for all worker processes.

            if not self.config['WTF_CSRF_SECRET_KEY']:
                self.config['WTF_CSRF_SECRET_KEY'] = secret_key

            self.config['SECRET_KEY'] = secret_key

            title = os.getenv('AMBRY_UI_TITLE', "Ambry Data Library"),

            if l.ui_config.website_title:
                title = l.ui_config.website_title

            self.config['website_title'] = title

            self.secret_key = secret_key

            self.csrf.init_app(self)

            self.session_interface = ItsdangerousSessionInterface()

            self.login_manager.init_app(app)
            Bootstrap(app)

            self._initialized = True

        return super(Application, self).__call__(environ, start_response)
Exemplo n.º 47
0
    def test_17_dict_config(self):
        cache = Cache(config={'CACHE_TYPE': 'simple'})
        cache.init_app(self.app)

        assert cache.config['CACHE_TYPE'] == 'simple'
Exemplo n.º 48
0
from sqlalchemy import distinct
import graphsub
import threading
from datetime import datetime
import rdsapi
import searchRDSinstance
import requests
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.cache import Cache

cache = Cache()
app = Flask(__name__)
manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
cache.init_app(app)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))


@app.after_request
def add_header(response):
    response.headers['Cache-Control'] = 'max-age=30'
    return response


@app.route("/check", methods=["GET", "POST"])
def check():
    ##################ESC DB Insert########################
    r = request.args.get('check')
    if r == 'ecs':
Exemplo n.º 49
0
 def test_19_dict_config_both(self):
     cache = Cache(config={'CACHE_TYPE': 'null'})
     cache.init_app(self.app, config={'CACHE_TYPE': 'simple'})
     from werkzeug.contrib.cache import SimpleCache
     assert isinstance(self.app.extensions['cache'][cache], SimpleCache)
Exemplo n.º 50
0
    def test_18_dict_config_initapp(self):
        cache = Cache()
        cache.init_app(self.app, config={'CACHE_TYPE': 'simple'})

        assert cache.config['CACHE_TYPE'] == 'simple'
Exemplo n.º 51
0
}

# Make and configure the Flask app
app = Flask(__name__)
if debug_app:
  app.debug = True


# Set up cache
cache_config = {
  'CACHE_TYPE': 'filesystem',
  'CACHE_THRESHOLD': 1000,
  'CACHE_DIR': 'cache'
}
cache = Cache(config = cache_config)
cache.init_app(app, config = cache_config)



# Just a default route
@app.route('/')
@cache.cached(timeout = 500)
def index():
  return 'This is a whitelisted JSON to JSONP proxy.'


# Proxy route
@app.route('/proxy')
def handle_proxy():
  request_url = request.args.get('url', '')
  callback = request.args.get('callback', '')