コード例 #1
0
from flask.ext.cache import Cache
import os
# Setup the Cache
cache = Cache(
    config={
        'CACHE_TYPE':
        'filesystem',
        'CACHE_DIR':
        str(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +
        '/cache'
    })

#make a http last modified wrapper
from flask import make_response
from functools import wraps, update_wrapper
from datetime import datetime, timedelta


def httpdate(dt):
    """Return a string representation of a date according to RFC 1123
    (HTTP/1.1).

    The supplied date must be in UTC.

    """
    weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
    month = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
        "Nov", "Dec"
    ][dt.month - 1]
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
コード例 #2
0
logging.basicConfig(
    format=
    "%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s",
    datefmt="%m/%d/%Y %I:%M:%S %p",
    level=logging.INFO,
)

logging.getLogger("socketio").setLevel(logging.ERROR)
logging.getLogger("engineio").setLevel(logging.ERROR)

app = Flask(__name__)
socketio = SocketIO(app,
                    async_mode="eventlet",
                    engineio_logger=False,
                    message_queue="redis://")
cache = Cache(app, config={"CACHE_TYPE": "simple"})

CACHE_TIMEOUT = 600

requests.packages.urllib3.disable_warnings()

BRANCHES_SETTINGS = {}
APP_SETTINGS = {}


def update_all_rules():
    """Set next active rules for all branches."""
    try:
        for i in range(1, len(RULES_FOR_BRANCHES)):
            set_next_rule_to_redis(i, database.get_next_active_rule(i))
        logging.info("Rules updated")
コード例 #3
0
ファイル: config.py プロジェクト: raintank/graphite-api
def configure(app):
    config_file = os.environ.get('GRAPHITE_API_CONFIG',
                                 '/etc/graphite-api.yaml')
    if os.path.exists(config_file):
        with open(config_file) as f:
            config = yaml.safe_load(f)
            config['path'] = config_file
    else:
        warnings.warn("Unable to find configuration file at {0}, using "
                      "default config.".format(config_file))
        config = {}

    configure_logging(config)

    for key, value in list(default_conf.items()):
        config.setdefault(key, value)

    app.statsd = None
    if 'statsd' in config:
        try:
            from statsd import StatsClient
        except ImportError:
            warnings.warn("'statsd' is provided in the configuration but "
                          "the statsd client is not installed. Please `pip "
                          "install statsd`.")
        else:
            c = config['statsd']
            app.statsd = StatsClient(c['host'], c.get('port', 8125))

    app.cache = None
    if 'cache' in config:
        try:
            from flask.ext.cache import Cache
        except ImportError:
            warnings.warn("'cache' is provided in the configuration but "
                          "Flask-Cache is not installed. Please `pip install "
                          "Flask-Cache`.")
        else:
            cache_conf = {
                'CACHE_DEFAULT_TIMEOUT': 60,
                'CACHE_KEY_PREFIX': 'graphite-api:'
            }
            for key, value in config['cache'].items():
                cache_conf['CACHE_{0}'.format(key.upper())] = value
            app.cache = Cache(app, config=cache_conf)

    loaded_config = {'functions': {}}
    for functions in config['functions']:
        loaded_config['functions'].update(load_by_path(functions))

    if 'carbon' in config:
        if 'hashing_keyfunc' in config['carbon']:
            config['carbon']['hashing_keyfunc'] = load_by_path(
                config['carbon']['hashing_keyfunc'])
        else:
            config['carbon']['hashing_keyfunc'] = lambda x: x
    loaded_config['carbon'] = config.get('carbon', None)

    finders = []
    for finder in config['finders']:
        finders.append(load_by_path(finder)(config))
    loaded_config['store'] = Store(finders)
    app.config['GRAPHITE'] = loaded_config
    app.config['TIME_ZONE'] = config['time_zone']
    logger.info("configured timezone", timezone=app.config['TIME_ZONE'])

    app.config['admin_token'] = config['admin_token']
    app.config['multi_tenant'] = config['multi_tenant']

    if 'sentry_dsn' in config:
        try:
            from raven.contrib.flask import Sentry
        except ImportError:
            warnings.warn("'sentry_dsn' is provided in the configuration but "
                          "the sentry client is not installed. Please `pip "
                          "install raven[flask]`.")
        else:
            Sentry(app, dsn=config['sentry_dsn'])

    app.wsgi_app = TrailingSlash(
        CORS(app.wsgi_app, config.get('allowed_origins')))
    if config.get('render_errors', True):
        app.errorhandler(500)(error_handler)
コード例 #4
0
    def test_17_dict_config(self):
        cache = Cache(config={'CACHE_TYPE': 'simple'})
        cache.init_app(self.app)

        assert cache.config['CACHE_TYPE'] == 'simple'
コード例 #5
0
ファイル: host_test.py プロジェクト: himanshpal/discovery
 def setUp(self):
     self.app = Flask(__name__)
     self.app.cache = Cache(self.app, config={'CACHE_TYPE': 'simple'})
     self.app.cache.clear()
     self.app_context = self.app.app_context()
     self.app_context.push()
コード例 #6
0
    def add_resource(cls):
        api.add_resource(cls, '/api/%s' % cls.RESOURCE_NAME, '/api/%s/<id>' % cls.RESOURCE_NAME)


app = Flask(__name__)
app.json_encoder = CustomJSONEncoder

SESSION_TYPE = 'redis'
CACHE_TYPE = 'redis'
SQLALCHEMY_DATABASE_URI = CONF.psql_db_url
app.config.from_object(__name__)

db = SQLAlchemy(app)

Session(app)
cache = Cache(app, config={'CACHE_TYPE': CACHE_TYPE, 'CACHE_REDIS_HOST': CONF.redis_host,
                           'CACHE_REDIS_PORT': CONF.redis_port})

from yeti.api.filter import auth_filter, log_filter, audit_filter, permission_filter

# api = Api(app, decorators=[audit_filter, permission_filter, auth_filter, log_filter])
api = Api(app, decorators=[audit_filter, auth_filter, log_filter])
api.route = types.MethodType(api_route, api)

redis_conn = Redis(CONF.redis_host, CONF.redis_port)


@app.before_request
def before_request():
    db.session()

コード例 #7
0
#!/usr/bin/env python

import json
import urllib2

from flask import Flask
from flask.ext.cache import Cache

from bs4 import BeautifulSoup

APP = Flask(__name__)
CACHE = Cache(APP, config={'CACHE_TYPE': 'simple'})
CACHE_TIMEOUT = 1800  # 30 minutes
URL = 'http://www.urbandictionary.com'


def get_wod(day=0):
    if day > 6:
        raise LookupError(
            'Words of the day older than one week from today are not available.'
        )

    content = urllib2.urlopen(URL).read()
    soup = BeautifulSoup(content)
    words = []

    for div in soup.findAll('a', attrs={'class': 'word'}):
        words.append(div.text.strip())

    meanings = __get_elements_of_class('meaning', soup)
    elements = __get_elements_of_class('example', soup)
コード例 #8
0
ファイル: app.py プロジェクト: 919695/miaopai-thief
if platform.system() == 'Windows':
    debug = False
    path = os.getcwd() + '\\cache\\'
    host = '127.0.0.1'
    port = 808
else:
    debug = True
    host = '0.0.0.0'
    path = 'cache/'
    debug = False
    port = 80
index_path = path + 'index.json'
cache = Cache(app,
              config={
                  'CACHE_TYPE': 'filesystem',
                  'CACHE_THRESHOLD': sys.maxint,
                  'CACHE_DEFAULT_TIMEOUT': 60 * 60 * 24,
                  'CACHE_DIR': path
              })
time_out = 60


@app.route('/')
def index():
    index_doc = {
        'update_time': 0,
        'doc': {},
    }
    # 没有缓存文件
    if os.path.exists(index_path) == False:
        index_doc['doc'] = get_index_doc()
コード例 #9
0
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
from flask.ext.login import LoginManager
from flask_wtf.csrf import CsrfProtect
from flask.ext.cache import Cache
import memcache
from core.utils.libsmq import *
from mongoengine.queryset import Q
import datetime
from hashlib import md5
import pytz

gm_client = JSONGearmanClient(['localhost:4730'])

app = Flask(__name__)

cache = Cache(app, config={'CACHE_TYPE': 'memcached'})

csrf = CsrfProtect()

app.debug = True
app.config["MONGODB_SETTINGS"] = {'DB': "rubicon"}
app.config["SECRET_KEY"] = "t/eSb1zxF6fK2B/JNc0X2w=="
app.config['UPLOAD_FOLDER'] = '/opt/rubicon/csv_data'
app.config['UPLOAD_DATASETS'] = '/opt/rubicon/datasets'
app.config['ALLOWED_NUMBERS_EXTENSIONS'] = set(['csv'])
app.config['WTF_CSRF_CHECK_DEFAULT'] = False
app.config['MODELS_PATH'] = '/opt/rubicon/models'

db = MongoEngine(app)
app.session_interface = MongoEngineSessionInterface(db)
bcrypt = Bcrypt(app)
コード例 #10
0
# -*- coding: utf-8 -*-
__author__ = 'florije'

from flask import Flask, jsonify, request
from flask.ext.cache import Cache
from flask.ext.sqlalchemy import SQLAlchemy
from celery import Celery
import logging
from logging.handlers import TimedRotatingFileHandler

cache = Cache(
    config={
        'CACHE_TYPE': 'redis',
        'CACHE_KEY_PREFIX': 'fcache',
        'CACHE_REDIS_HOST': 'localhost',
        'CACHE_REDIS_PORT': '6379',
        'CACHE_REDIS_URL': 'redis://localhost:6379'
    })

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'

app.config.update(CELERY_BROKER_URL='redis://localhost:6379',
                  CELERY_RESULT_BACKEND='redis://localhost:6379')

cache.init_app(app)
db = SQLAlchemy(app)

handler = TimedRotatingFileHandler(filename='{0}'.format('logs.log'),
                                   when='D',
                                   interval=1,
コード例 #11
0
ファイル: __init__.py プロジェクト: niko64fx/navitia
    handler = logging.StreamHandler(stream=sys.stdout)
    app.logger.addHandler(handler)
    app.logger.setLevel('INFO')

app.wsgi_app = ReverseProxied(app.wsgi_app)
got_request_exception.connect(log_exception, app)

#we want the old behavior for reqparse
compat.patch_reqparse()

rest_api = Api(app, catch_all_404s=True, serve_challenge_on_401=True)

from navitiacommon.models import db

db.init_app(app)
cache = Cache(app, config=app.config['CACHE_CONFIGURATION'])

if app.config['AUTOCOMPLETE'] is not None:
    global_autocomplete = utils.create_object(
        app.config['AUTOCOMPLETE']['class_path'],
        **app.config['AUTOCOMPLETE']['kwargs'])
else:
    global_autocomplete = None

from jormungandr.instance_manager import InstanceManager

i_manager = InstanceManager(
    instances_dir=app.config.get('INSTANCES_DIR', None),
    start_ping=app.config.get('START_MONITORING_THREAD', True))
i_manager.initialisation()
コード例 #12
0
from flask.ext.assets import Environment, Bundle
assets = Environment(app)
assets.load_path.append(os.path.join(oec_dir, "assets/js/"))
js = Bundle("warning.js",
            "visualization.js",
            "configs/*.js",
            "helpers/*.js",
            output="js/visualization.js")
assets.register("js", js)

# DB connection object
db = SQLAlchemy(app)

# set up cache for views
view_cache = Cache(app)

# Global Latest Year Variables
available_years = {"sitc": range(1962, 2014), "hs92": range(1995, 2014), \
                    "hs96": range(1998, 2014), "hs02": range(2003, 2014), \
                    "hs07": range(2008, 2013), "country": range(1962, 2014)}

# Global for excluded countries
excluded_countries = ["ocglp", "xxwld", "asymd", "eumco", "saguf", "euksv", \
    "nabes", "nacuw", "navir", "eusjm", "namaf", "naant", "afreu", "afssd", \
    "afmyt", "eufro", "eubel", "eulux", "afswz", "afbwa", "aflso", "afnam", \
    "napri", "namtq", "euimn", "eulie", "euddr", "eufdr", "nablm", "eusun", \
    "euscg", "euyug"]
random_countries = ["afago","afdza","afegy","afmar","afnga","afzaf","asare", \
    "asaze","asbgd","aschn","ashkg","asidn","asind","asirn","asirq","asisr", \
    "asjpn","askaz","askor","askwt","asmys","asomn","aspak","asphl","asqat", \
コード例 #13
0
from flask.ext.cache import Cache
from flask.ext.mail import Mail
from flask_assets import Environment
from webassets.loaders import PythonLoader as PythonAssetsLoader

app = Flask(__name__)

# ENV configuration
env = os.environ.get('WHATSTODAY_ENV', 'dev')
app.config.from_object('app.settings.%sConfig' % env.capitalize())
app.config['ENV'] = env

# Memcached
if env == 'dev':
    # Use Simple Cache
    cache = Cache(app, config={'CACHE_TYPE': 'simple'})
else:
    import pylibmc

    def pylibmc_cache(app, config, args, kwargs):
        return pylibmc.Client(servers=app.config['CACHE_MEMCACHED_SERVERS'],
                              binary=True)

    cache = Cache(app, config={'CACHE_TYPE': pylibmc_cache})

cache.init_app(app)

# DB
db = SQLAlchemy(app)

# Login manager
コード例 #14
0
__author__ = 'ufarooqi'

from flask.ext.cache import Cache

from candidate_pool_service.common.utils.models_utils import init_talent_app
from candidate_pool_service.common.routes import CandidatePoolApi
from candidate_pool_service.common.talent_config_manager import TalentConfigKeys
from candidate_pool_service.common.talent_celery import init_celery_app
from candidate_pool_service.common.models.db import db

app, logger = init_talent_app(__name__)

try:
    # Instantiate Flask-Cache object
    cache = Cache(app, config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': app.config['REDIS_URL']})

    # Instantiate Celery
    celery_app = init_celery_app(app, 'celery_stats_scheduler')

    from api.talent_pools import talent_pool_blueprint
    from api.talent_pipelines import talent_pipeline_blueprint
    from api.smartlists import smartlist_blueprint

    app.register_blueprint(talent_pipeline_blueprint, url_prefix=CandidatePoolApi.URL_PREFIX)
    app.register_blueprint(talent_pool_blueprint, url_prefix=CandidatePoolApi.URL_PREFIX)
    app.register_blueprint(smartlist_blueprint, url_prefix=CandidatePoolApi.URL_PREFIX)

    db.create_all()
    db.session.commit()

    logger.info("Starting candidate_pool_service in %s environment", app.config[TalentConfigKeys.ENV_KEY])
コード例 #15
0
# Application setup


class MyFlask(Flask):
    jinja_options = dict(Flask.jinja_options)
    jinja_options.setdefault(
        'extensions', []).append('i2p2www.extensions.HighlightExtension')


app = application = MyFlask('i2p2www',
                            template_folder=TEMPLATE_DIR,
                            static_url_path='/_static',
                            static_folder=STATIC_DIR)
app.debug = bool(os.environ.get('APP_DEBUG', 'False'))
babel = Babel(app, default_domain=DEFAULT_GETTEXT_DOMAIN)
cache = Cache(app, config=CACHE_CONFIG)

#################
# Babel selectors


@babel.localeselector
def get_locale():
    # If viewing specs, require English
    if request.path.startswith('/spec'):
        return 'en'
    # If the language is already set from the url, use that
    if hasattr(g, 'lang'):
        return g.lang
    # otherwise try to guess the language from the user accept
    # header the browser transmits. The best match wins.
コード例 #16
0
from itertools import groupby
from cStringIO import StringIO
import csv
from shapely.wkb import loads
from shapely.geometry import box, asShape
from collections import OrderedDict
from urlparse import urlparse
from hashlib import md5

from plenario.models import MasterTable, MetaTable
from plenario.database import session, app_engine as engine, Base
from plenario.utils.helpers import get_socrata_data_info, slugify, increment_datetime_aggregate
from plenario.tasks import add_dataset
from plenario.settings import CACHE_CONFIG

cache = Cache(config=CACHE_CONFIG)

API_VERSION = '/v1'
RESPONSE_LIMIT = 1000
CACHE_TIMEOUT = 60 * 60 * 6
VALID_DATA_TYPE = ['csv', 'json']
VALID_AGG = ['day', 'week', 'month', 'quarter', 'year']
WEATHER_COL_LOOKUP = {
    'daily': {
        'temp_lo': 'temp_min',
        'temp_hi': 'temp_max',
        'temp_avg': 'temp_avg',
        'precip_amount': 'precip_total',
    },
    'hourly': {
        'temp_lo': 'drybulb_fahrenheit',
コード例 #17
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cache import Cache
import xml.etree.ElementTree as ET
import json
app = Flask(__name__)
db = SQLAlchemy(app)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})


def dump_table_xml(elements, table, parent_node, collection_name,
                   element_name):
    collection = ET.SubElement(parent_node, collection_name)
    for element in elements:
        element_node = ET.SubElement(collection, element_name)
        element_dict = dict(
            (col, getattr(element, col)) for col in table.columns.keys())
        for key, value in element_dict.iteritems():
            ET.SubElement(element_node, str(key)).text = unicode(value)
    return collection


"""
    @elements is a result set from sqlalchemy
    @table is the table name used for the result set
    returns a list of dicts
"""


def dump_table(elements, table):
    all = [
コード例 #18
0
#! /usr/bin/env python
# -*- encoding: utf-8 -*-

# Standard Lib
from datetime import timedelta

# Extra Lib
from flask import Flask
from flask.ext.babel import Babel
from flask.ext.cache import Cache

# Custom Tools
from tools.config import conf

# Create Aplication
app = Flask(__name__)
app.secret_key = conf.get('flask', 'secret_key')
app.debug = conf.get('flask', 'debug') == 'True'
app.config['BABEL_DEFAULT_LOCALE'] = conf.get('localization', 'locale')
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(
    minutes=int(conf.get('auth', 'session_minute')))

# Manage translation for the new application
babel = Babel(app)

# Manage Cache for the new application
cache = Cache(app, config={'CACHE_TYPE': conf.get('cache', 'method')})

# Clear Cache
cache.clear()
コード例 #19
0
import os
import sys
from flask import Flask, redirect, send_from_directory, render_template
from flask.ext.cache import Cache
import logics

SERVER_PATH = os.path.abspath(os.path.dirname(sys.argv[0]))
STATIC_DIR = os.path.join(SERVER_PATH, "static")
TEMPLATE_DIR = os.path.join(SERVER_PATH, "template")

app = Flask(
    "modelce", static_url_path=STATIC_DIR, template_folder=TEMPLATE_DIR)
cache = Cache(
    app, config={'CACHE_TYPE': 'filesystem',
                 'CACHE_DIR': './_cache'})

baseline_commit_url = "https://github.com/Superjomn/paddle-modelci-baseline/commit"
paddle_commit_url = "https://github.com/PaddlePaddle/Paddle/commit"


@app.route('/')
@cache.cached(timeout=10)
def index():
    return render_template(
        'dashboard.html',
        current_module='dashboard',
        paddle_commit_url=paddle_commit_url,
        source_code_updated=logics.source_code_updated(),
        baseline_commit_url=baseline_commit_url,
        last_success_commit=logics.last_success_commit(),
        last_fail_commit=logics.last_fail_commit(),
コード例 #20
0
  __name__,
  instance_relative_config = True
)

# Which config to use
mode = os.environ.get("PORTALAPI_MODE")
if mode is None:
  raise Exception, "No API mode designated. Set the PORTALAPI_MODE environment variable to 'dev' or 'prod'"
elif mode == "dev":
  print "Starting with development config..."
  app.config.from_object("portalapi.flask_cfg.DevConfig")
elif mode == "prod":
  print "Starting with production config..."
  app.config.from_object("portalapi.flask_cfg.ProdConfig")
elif mode == "quick":
  print "Starting with quick config..."
  app.config.from_object("portalapi.flask_cfg.QuickConfig")
else:
  raise Exception, "Unrecognized value for PORTALAPI_MODE: " + mode

# Enable cross-domain headers on all routes
CORS(app)

# Enable caching
cache = Cache(
  app,
  config = app.config["CACHE_CONFIG"]
)

from portalapi.controllers import routes
コード例 #21
0
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=587,
    MAIL_USE_TLS=True,
    MAIL_USE_SSL=False,
    MAIL_USERNAME='******',
    MAIL_PASSWORD='******')

flask_mail = Mail(app)

db = MongoEngine(app)

login_manager = LoginManager()
login_manager.init_app(app)

flask_bcrypt = Bcrypt(app)


def register_blueprints(app):
    # Prevents circular import (May be not helpful)#
    from IdeaExplorer.views import posts
    app.register_blueprint(posts)


register_blueprints(app)
cache = Cache(app)

from IdeaExplorer import restserver

if __name__ == '__main__':
    app.run()
コード例 #22
0
ファイル: __init__.py プロジェクト: weichen55/caravel
from flask.ext.migrate import Migrate
from flask.ext.cache import Cache


APP_DIR = os.path.dirname(__file__)
CONFIG_MODULE = os.environ.get('CARAVEL_CONFIG', 'caravel.config')

# Logging configuration
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
logging.getLogger().setLevel(logging.DEBUG)

app = Flask(__name__)
app.config.from_object(CONFIG_MODULE)
db = SQLA(app)

cache = Cache(app, config=app.config.get('CACHE_CONFIG'))

migrate = Migrate(app, db, directory=APP_DIR + "/migrations")


class MyIndexView(IndexView):
    @expose('/')
    def index(self):
        return redirect('/caravel/welcome')

appbuilder = AppBuilder(
    app, db.session,
    base_template='caravel/base.html',
    indexview=MyIndexView,
    security_manager_class=app.config.get("CUSTOM_SECURITY_MANAGER"))
コード例 #23
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)
コード例 #24
0
ファイル: app.py プロジェクト: yask123/moin-2.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
コード例 #25
0
# -*- coding: utf-8 -*-
"""Extensions module. Each extension is initialized in the app factory located
in app.py
"""
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask.ext.migrate import Migrate
migrate = Migrate()

from flask.ext.bcrypt import Bcrypt
bcrypt = Bcrypt()

# from flask.ext.admin import Admin
# admin = Admin()

from flask.ext.cache import Cache
cache = Cache()

from flask.ext.debugtoolbar import DebugToolbarExtension
debug_toolbar = DebugToolbarExtension()



コード例 #26
0
ファイル: __init__.py プロジェクト: IuryAlves/code-challenge
# coding: utf-8

from __future__ import (print_function, unicode_literals, absolute_import)

from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.cors import CORS
from flask.ext.cache import Cache

app = Flask(__name__)
app.config.from_object('app.settings')

enable_cors = app.config.get("ENABLE_CORS", False)
if enable_cors:
    CORS(app, resources={
        r"/properties/*": {
            "origins": "*"
        },
    })

db = MongoEngine(app)
cache = Cache(config={"CACHE": app.config.get("CACHE_TYPE")})
cache.init_app(app)

from app.resources import properties

app.register_blueprint(properties.blueprint)
コード例 #27
0
ファイル: moviesneaker.py プロジェクト: anateus/MovieSneaker
else:  # we're debugging
    DEBUG = True
    env = None

if env:
    redis = redis_from_url(env["DOTCLOUD_DATA_REDIS_URL"])
else:  # we're debugging
    redis = Redis()

showtime_parse_queue = Queue('showtime_parse', redis)

rp = redis.connection_pool.connection_kwargs
cache = Cache(app,
              config={
                  'CACHE_TYPE': 'redis',
                  'CACHE_REDIS_HOST': rp.get('host'),
                  'CACHE_REDIS_POST': rp.get('port'),
                  'CACHE_REDIS_PASSWORD': rp.get('password')
              })
### Various utilities I'll break out later


class SchemaEncoder(json.JSONEncoder):
    """
    Encodes JSON from SQLAlchemy schemas that have .__json__() as well as datetimes
    """
    def default(self, obj):
        if isinstance(obj, db.Model):
            return obj.__json__()
        if isinstance(obj, datetime):
            return obj.isoformat()
コード例 #28
0
    ('CACHE_THRESHOLD', int),
    ('CACHE_KEY_PREFIX', text_type),
    ('CACHE_OBJECT_MAX_SIZE', int),
]
defaults = {
    'CACHE_KEY_PREFIX': 'apiproxy:',
    'CACHE_OBJECT_MAX_SIZE': (1000**2) * 5
}
if CACHE_TYPE.endswith("memcached"):
    defaults.update({
        'CACHE_MEMCACHED_SERVERS': ['127.0.0.1:11211'],
        'CACHE_OBJECT_MAX_SIZE': (1000**2) * 1
    })

config = defaults.copy()
for key, trans in env_keys:
    envvar = ENV.get('EVE_API_%s' % key, None)
    if not envvar:
        continue
    try:
        envvar = trans(envvar)
    except:
        sys.stderr.write(
            "The environment variable 'EVE_API_%s' is malformed: %r'" %
            (key, envvar))
        continue
    config[key] = envvar

CACHE_OBJECT_MAX_SIZE = config.pop('CACHE_OBJECT_MAX_SIZE')
cache = Cache(app, config=config)
コード例 #29
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')
    wfilehandler = logging.FileHandler('werkzeug.log')
    wfilehandler.setLevel(logging.DEBUG)
    wlog = logging.getLogger('werkzeug')
    wlog.setLevel(logging.DEBUG)
    wlog.addHandler(wfilehandler)
    filehandler = logging.FileHandler('flask.log')
    filehandler.setLevel(logging.DEBUG)
    app.logger.setLevel(logging.DEBUG)
    app.logger.addHandler(filehandler)
    return app


app = create_app()
cache = Cache(app,
              config={
                  'CACHE_TYPE': 'redis',
                  'CACHE_DEFAULT_TIMEOUT': 1000000000
              })

from app import views, models
from database import db


@app.teardown_appcontext
def shutdown_session(exception=None):
    db.remove()
コード例 #30
0
from flaskext.gravatar import Gravatar
gravatar = Gravatar(size=35,
                    rating='g',
                    default='mm',
                    force_default=False,
                    force_lower=False)

from flask.ext.misaka import Misaka
md = Misaka(fenced_code=True,
            superscript=True,
            strikethrough=True,
            hard_wrap=True,
            autolink=True)

from flask.ext.cache import Cache
cache = Cache()  # cache cache :)


def github_oauth(app):
    from rauth.service import OAuth2Service

    github = OAuth2Service(
        name='github',
        base_url='https://api.github.com/',
        authorize_url='https://github.com/login/oauth/authorize',
        access_token_url='https://github.com/login/oauth/access_token',
        client_id=app.config['GITHUB_CONSUMER_KEY'],
        client_secret=app.config['GITHUB_CONSUMER_SECRET'],
    )
    return github