Example #1
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Apply the SchemeProxyFix middleware
    app.wsgi_app = SchemeProxyFix(app.wsgi_app)

    # Add our cache
    if config_name == "production":  # pragma: no cover
        app.cache = FileSystemCache("recent_calls")
    else:
        app.cache = SimpleCache()

    bootstrap.init_app(app)
    db.init_app(app)

    from .setup import setup as setup_blueprint

    app.register_blueprint(setup_blueprint)

    from .voice import voice as voice_blueprint

    app.register_blueprint(voice_blueprint)

    # Register our custom template filter
    app.jinja_env.filters["national_format"] = convert_to_national_format

    return app
Example #2
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_pyfile(config)
    app.debug = app.config.get("DEBUG", False)

    # Setup semi-permanent cache stored in os temp directory
    try:
        app.cache_file = os.path.join(tempfile.gettempdir(), "spectrometer-cache.p")
        app.cache = pickle.load(open(app.cache_file, "rb"))
    except IOError:
        app.cache = {}

    # Flask profiler is only active when in debug mode
    profiler = Profiler()
    profiler.init_app(app)

    if not app.debug:
        # Setup Logger
        logdir = app.config.get("LOG_DIR", "/var/log/spectrometer")
        logfile = os.path.join(logdir, "spectrometer.log")

        logging.getLogger().setLevel(logging.NOTSET)
        formatter = logging.Formatter("%(asctime)s (%(levelname)8s) %(name)-40s: %(message)s")
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logging.getLogger().addHandler(console_handler)

        try:
            file_handler = RotatingFileHandler(logfile, maxBytes=20000000, backupCount=20)
            file_handler.setFormatter(formatter)
            logging.getLogger().addHandler(file_handler)
            log.info("File logger activated.")
        except IOError:
            log.warn(
                "Unable to activate File logger. Please ensure that the "
                "log directory ({0}) is writable by the spectrometer user.".format(logdir)
            )

    # Prep resource handlers
    app.gerrithandler = GerritHandler(app.config["GERRIT_URL"])
    app.githandlers = {}

    # Stop Flask debug mode from running the scheduler twice
    if not app.debug or os.environ.get("WERKZEUG_RUN_MAIN") == "true":
        run_scheduler(app)

    app.route("/")(views.status)

    app.register_blueprint(gitapi, url_prefix="/git")
    app.register_blueprint(gerritapi, url_prefix="/gerrit")

    return app
Example #3
0
def create_app():
    """
    Create the application and return it to the user
    :return: flask.Flask application
    """

    app = Flask(__name__, static_folder=None)
    app.url_map.strict_slashes = False

    Consul(app)

    load_config(app)

    logging.config.dictConfig(app.config["OBJECTS_LOGGING"])

    app.cache = Cache(app)

    api = Api(app)
    api.add_resource(ObjectSearch, "/", "/<string:objects>", "/<string:objects>/<string:source>")
    api.add_resource(PositionSearch, "/pos/<string:pstring>")
    api.add_resource(QuerySearch, "/query")

    discoverer = Discoverer(app)

    return app
Example #4
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
Example #5
0
def create_app():
    app = Flask(__name__, static_folder=static_folder, template_folder=template_folder)
    app.debug = True

    # Configuration files
    import website.default_config

    app.config.from_object(website.default_config)
    app.config.from_object("website.config")

    # Error handling
    import errors

    errors.init_error_handlers(app)

    # I18n
    import babel

    babel.init_app(app)

    # Caching
    from werkzeug.contrib.cache import SimpleCache

    app.cache = SimpleCache()

    # Template utilities
    app.jinja_env.add_extension("jinja2.ext.do")

    from website.expand import expand

    app.jinja_env.filters["expand"] = expand

    # Blueprints
    from views import frontend_bp
    from views.changelog import changelog_bp
    from views.humans import humans_bp
    from views.plugins import plugins_bp
    from views.docs import docs_bp
    from views.api import api_bp

    app.register_blueprint(frontend_bp)
    app.register_blueprint(changelog_bp, url_prefix="/changelog")
    app.register_blueprint(humans_bp)
    app.register_blueprint(plugins_bp, url_prefix="/plugins")
    app.register_blueprint(docs_bp, url_prefix="/docs")
    app.register_blueprint(api_bp, url_prefix="/api")

    return app
Example #6
0
def create_app():
    conf = Config()
    iggybase = Flask(__name__)
    iggybase.config.from_object(conf)
    iggybase.cache = Cache()

    init_db()

    configure_blueprints(iggybase)
    security, user_datastore = configure_extensions(iggybase, db)
    configure_error_handlers(iggybase)
    configure_hook(iggybase)

    add_base_routes(iggybase, conf, security, user_datastore)

    return iggybase
Example #7
0
def create_app(config_file):
    app = Flask(__name__)

    # configuration settings are loaded from the `config.py` module
    # and (optionally) from a file `XSNIPPET_API_SETTINGS` env var points to
    app.config.from_pyfile(config_file)
    app.config.from_envvar("XSNIPPET_API_SETTINGS", silent=True)

    app.register_blueprint(api)

    # create a database connection (it's thread-safe, so we can keep it global)
    app.db = create_db_connection(app)

    # create a cache connection (it's thread-safe too)
    app.cache = create_cache_connection(app, key_prefix="api_")

    return app
Example #8
0
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object(settings)

    if isinstance(config, dict):
        app.config.update(config)
    elif config:
        app.config.from_pyfile(os.path.realpath(config))

    redis_store.init_app(app)
    cache.init_app(app)
    app.cache = cache
    app.plugin_modules = plugin_modules

    slackbot = SlackBot(app)
    slackbot.set_handler(callback)
    slackbot.filter_outgoing(_filter)

    return app
Example #9
0
def create_app(config_file):
    app = Flask(__name__)

    # configuration settings are loaded from the `config.py` module
    # and (optionally) from a file `XSNIPPET_SETTINGS` env var points to
    app.config.from_pyfile(config_file)
    app.config.from_envvar("XSNIPPET_WEBUI_SETTINGS", silent=True)

    # set jinja2 global vars to be used in all templates
    app.jinja_env.globals.update(
        {"title": app.config["TITLE"], "abs_url_for": abs_url_for, "lang_by_short_name": lang_by_short_name}
    )
    # set assets env
    assets.Environment(app)

    app.register_blueprint(webui)

    # register all needed hooks
    app.before_request(create_http_object)

    # create cache connection (it's thread-safe)
    app.cache = create_cache_connection(app, key_prefix="webui_")

    return app
Example #10
0
def make_app(cache=None, config=None):

    if config is None:
        config = Config()

    app = Flask(__name__)
    app.config.update(config)

    if cache is None:
        cache = Cache(config=config)

    app.cache = cache

    # Get the fallback server from shotgun_api3_registry.
    passthrough_server = app.config.setdefault("PASSTHROUGH_SERVER", get_shotgun_kwargs(config)["base_url"].strip("/"))
    app.config.setdefault("PASSTHROUGH_URL", passthrough_server + "/api3/json")

    # We use one HTTP session for everything.
    app.http_session = requests.Session()

    # Register the logic.
    app.register_blueprint(blueprint)

    return app
Example #11
0
def create_app(configuration_file=None):
    app = Flask(__name__)
    app.plugins = []

    # cannot use namespace here, weak signals will disappear
    app.plugin_signals = {
        "plugin-loaded": Signal(),
        "page-loaded": Signal(),
        "special-loaded": Signal(),
        "page-preprocess": Signal(),
        "page-postmarkdown": Signal(),
        "page-treeprocess": Signal(),
        "page-postprocess": Signal(),
    }

    # load a default config, and from configuration file
    app.config.from_object(defaults)
    if configuration_file:
        app.config.from_pyfile(configuration_file)

    app.db = WikiDb(app.config["REPOSITORY_PATH"])
    app.cache = Cache(app)

    app.register_module(frontend)

    # load plugins
    for plugin_name in app.config["PLUGINS"]:
        import_name = "qwappplugin.%s" % plugin_name

        qwappplugin = __import__("qwappplugin.%s" % plugin_name)
        plugin_module = getattr(qwappplugin, plugin_name)
        app.logger.debug("loading plugin %s" % plugin_module.plugin.version_string)

        plugin_module.plugin.register_app(app)

    return app
Example #12
0
import memcache
from flask_memcache_session import Session
from werkzeug.contrib.fixers import ProxyFix

# git clone https://github.com/dart-lang/py-gfm.git
# cd py-gfm
# python setup.py install
from markdown import markdown

import json, os, hashlib, tempfile, subprocess

config = {}

app = Flask(__name__, static_url_path="")
app.cache = memcache.Client(["unix:/tmp/memcached.sock"], debug=0)
app.session_interface = Session()
app.session_cookie_name = "isucon_session"
app.wsgi_app = ProxyFix(app.wsgi_app)

# log
import logging

logging.basicConfig(filename="log.txt")
# logging.basicConfig(filename='log.txt', level=logging.DEBUG)


def load_config():
    global config
    print("Loading configuration")
    env = os.environ.get("ISUCON_ENV") or "local"
import json
import datetime

from flask import Flask, render_template, jsonify
from flask_cache import Cache

import requests
import xmltodict


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


@app.route("/")
@app.route("/<game>")
def home(game="HGIL15"):
    return render_template("template.html", game=game)


@app.route("/api/<game>")
@app.cache.cached(timeout=120)
def api(game):
    stands = {
        "east": {"main": ["ES-EA", "ES-EB", "ES-EC", "ES-ED", "ES-EE"]},
        "south": {
            "upper": ["SU-SUF", "SU-SUG", "SU-SUHB", "SU-SUHY", "SU-SUI", "SU-SUJ"],
            "lower": ["SL-SLK", "SL-SLL", "SL-SLMB", "SL-SLMY", "SL-SLN", "SL-SLO"],
        },
        "west": {
            "family": ["WS-WP", "WS-WQ", "WS-WR"],
Example #14
0
# import the flask extension
from flask.ext.cache import Cache
import json

# from data import extract_data
# from data.extract_data import *

import config

app = Flask(__name__)

# define the cache config keys, remember that it can be done in a settings file
app.config["CACHE_TYPE"] = "simple"

# register the cache instance and binds it on to your app
app.cache = Cache(app)


@app.route("/numberofhits")
@app.cache.cached(timeout=100)  # cache this view for 5 minutes
def numberofhits():
    # json_data = open("data-2014.json")
    # data = json.load(json_data)
    # json_string = json.dumps(data)
    json_string = config.grand_total()
    response = make_response(json_string)
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Credentials"] = "true"
    return response
    # return jsonify(data=json_string)
Example #15
0
Module:             %(module)s
Function:           %(funcName)s
Time:               %(asctime)s

Message:

%(message)s
"""
        )
    )
    app.logger.addHandler(mail_handler)

if "REDISTOGO_URL" in os.environ:
    redis_client = redis.from_url(os.environ["REDISTOGO_URL"])
    app.cache = RedisCache(redis_client)
else:
    app.cache = SimpleCache()

app.config["S3_BUCKET_NAME"] = "radlibs-assets"
app.config["S3_USE_CACHE_CONTROL"] = False
app.config["S3_CDN_DOMAIN"] = "d2hwb9ozcl9dk9.cloudfront.net"
app.config["FLASK_ASSETS_USE_S3"] = True
app.config["USE_S3_DEBUG"] = True
if os.getenv("ASSETS_DEBUG"):
    app.config["ASSETS_DEBUG"] = True
    app.config["FLASK_ASSETS_USE_S3"] = False
FlaskS3(app)
assets = Environment(app)
js = Bundle(
    "js/jquery.min.js",
    "js/bootstrap.min.js",
Example #16
0
def create_retries_app(cache):
    retries_app = Flask(__name__)
    retries_app.PORT = 12
    retries_app.cache = cache

    # we want the retries app to listen on all methods
    retries_app.url_map.add(Rule("/", endpoint="index"))

    @retries_app.endpoint("index")
    def check_retries():
        json_hdr = {"Content-Type": "application/json"}
        key = request.args.get("key", "default")
        tries = request.args.get("tries", 3)
        try:
            tries = int(tries)
        except Exception:
            return Response(
                status=400,
                headers=json_hdr,
                response=json.dumps({"error": "Please pass an integer number of tries", "key": key, "success": False}),
            )

        if key in retries_app.cache:
            retries_app.cache[key] -= 1
        else:
            retries_app.cache[key] = int(tries) - 1

        if retries_app.cache[key] <= 0:
            data = {"key": key, "tries_remaining": retries_app.cache[key], "success": True}
            return Response(response=json.dumps(data), status=200, headers=json_hdr)
        else:
            msg = "The server had an error. Try again {retry_times} more {time_p}"
            time_p = "time" if retries_app.cache[key] == 1 else "times"
            content = {
                "error": msg.format(retry_times=retries_app.cache[key], time_p=time_p),
                "tries_remaining": retries_app.cache[key],
                "key": key,
                "success": False,
            }
            return Response(response=json.dumps(content), status=500, headers=json_hdr)

    @retries_app.route("/counters", methods=["POST"])
    def reset():
        key = request.values.get("key", "default")
        tries = request.values.get("tries", 3)
        try:
            tries = int(tries)
        except Exception:
            return Response(
                status=400,
                headers=json_hdr,
                response=json.dumps({"error": "Please pass an integer number of tries", "key": key, "success": False}),
            )

        retries_app.cache[key] = tries

        content = {"key": key, "tries_remaining": tries, "success": True}
        return Response(response=json.dumps(content), status=200, headers={"Content-Type": "application/json"})

    @retries_app.route("/counters", methods=["GET"])
    def counter():
        content = {"counters": retries_app.cache, "success": True}
        return Response(response=json.dumps(content), status=200, headers={"Content-Type": "application/json"})

    @retries_app.after_request
    def retries_header(resp):
        _log_flask(resp.status_code)
        resp.headers["Server"] = "hamms"
        return resp

    return retries_app
Example #17
0
from flask import render_template
from flask import request
from flask.ext.mobility import Mobility
from werkzeug.contrib.cache import FileSystemCache
from werkzeug.contrib.fixers import ProxyFix

from discograph import api
from discograph import ui
from discograph import exceptions


app = Flask(__name__)
app.config.from_object("discograph.config.DevelopmentConfiguration")
app.cache = FileSystemCache(
    app.config["FILE_CACHE_PATH"],
    default_timeout=app.config["FILE_CACHE_TIMEOUT"],
    threshold=app.config["FILE_CACHE_THRESHOLD"],
)
if not os.path.exists(app.config["FILE_CACHE_PATH"]):
    os.makedirs(app.config["FILE_CACHE_PATH"])
app.register_blueprint(api.blueprint, url_prefix="/api")
app.register_blueprint(ui.blueprint)
app.wsgi_app = ProxyFix(app.wsgi_app)
Mobility(app)


@app.after_request
def inject_rate_limit_headers(response):
    try:
        requests, remaining, reset = map(int, g.view_limits)
    except (AttributeError, ValueError):
Example #18
0
assets = Environment(app)
# Ensure output directory exists
assets_output_dir = os.path.join(FLASK_APP_DIR, "static", "gen")
if not os.path.exists(assets_output_dir):
    os.mkdir(assets_output_dir)

# Email
from flask.ext.mail import Mail

mail = Mail(app)

# Memcache
from werkzeug.contrib.cache import MemcachedCache

app.cache = MemcachedCache(app.config["MEMCACHED_SERVERS"])


def cache_fetch(key, value_function, timeout=None):
    """Mimicking Rails.cache.fetch"""
    global app
    self = app.cache
    data = self.get(key)
    if data is None:
        data = value_function()
        self.set(key, data, timeout)
    return data


app.cache.fetch = cache_fetch
Example #19
0
from BeautifulSoup import BeautifulSoup
import random
from flask import request
from flask.ext.cache import Cache

from save_historians import *
import time
import random

app = Flask(__name__)
app.config["CACHE_TYPE"] = "simple"
app.cache = Cache(
    app,
    config={
        "CACHE_TYPE": "filesystem",
        "CACHE_DIR": "cache-dir",
        "CACHE_DEFAULT_TIMEOUT": 922337203685477580,
        "CACHE_THRESHOLD": 922337203685477580,
    },
)


@app.route("/")
def main():
    return "nginx is running"


@app.route("/historyofgreats")
def historyofgreats():
    cached = app.cache.get("main")
    if cached:
Example #20
0
app = Flask(__name__)
app.config.from_object("config")
app.register_blueprint(admin, url_prefix="/admin")
app.register_blueprint(myhome, url_prefix="/myhome")
app.register_blueprint(product_blueprint)

# 使用redis,memcache
redis = Redis(host=app.config["REDIS_HOST"], port=app.config["REDIS_PORT"])

# 记录日志
handler = RotatingFileHandler("app.log", maxBytes=10000, backupCount=1)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]"))
handler.setLevel(logging.WARNING)
app.logger.addHandler(handler)
app.cache = MemcachedCache([app.config["MEMCACHE_HOST"], app.config["MEMCACHE_PORT"]])


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/about")
def about():
    if app.cache.get("about") is None:
        app.cache.set("about", app.config["ABOUTME"])

    about = app.cache.get("about")
    return render_template("about.html", about=unicode(about, "utf-8"))
Example #21
0
from openid.store.memstore import MemoryStore
from sqlalchemy import create_engine
from werkzeug.contrib.fixers import ProxyFix


logging.basicConfig(level=logging.INFO)


app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
use_openid = False
if 'MEMCACHEDCLOUD_SERVERS' in os.environ and 'OPENID_AUTH_IDENTITY' in os.environ:
    use_openid = True
    app.cache = bmemcached.Client(
        os.environ['MEMCACHEDCLOUD_SERVERS'].split(','),
        os.environ.get('MEMCACHEDCLOUD_USERNAME'),
        os.environ.get('MEMCACHEDCLOUD_PASSWORD')
    )
    app.session_interface = memcache_session.Session()
    openid_store = MemoryStore()
    openid_identity = os.environ["OPENID_AUTH_IDENTITY"]


TOKEN = os.environ.get('AUTH_TOKEN')
if not is_database_bound():
    # Don't mess with the database connection if someone else set it up already
    Session.configure(bind=create_engine(os.environ['DATABASE_URL']))


def check_auth_token(fn):
    @wraps(fn)
Example #22
0
from flask import Flask, render_template, session, url_for, redirect, request, flash, make_response
import config
import oauth2 as oauth
import redis
import urlparse
from urllib import urlencode
import redis
import json

app = Flask(__name__)
app.secret_key = config.consumer_key
app.consumer = oauth.Consumer(key=config.consumer_key, secret=config.consumer_secret)
app.cache = redis.StrictRedis(host="localhost", port=6379, db=0)

site_url = "http://127.0.0.1:5000/"


def verify_response(resp):
    if resp["status"] != "200":
        session.pop("request_token", None)
        flash("Bad response from Twitter: {0}".format(resp))
        return redirect(url_for("index"))
    else:
        return None


@app.route("/", methods=["GET"])
def index():
    if "request_token" in session:
        auth_token = oauth.Token(
            session["request_token"]["oauth_token"], session["request_token"]["oauth_token_secret"]
Example #23
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
Example #24
0
    render_template,
    _app_ctx_stack,
    Response,
    after_this_request,
)

import memcache
from flask_memcache_session import Session
from werkzeug.contrib.fixers import ProxyFix

import json, os, hashlib, tempfile, subprocess

config = {}

app = Flask(__name__, static_url_path="")
app.cache = memcache.Client(["localhost:11211"], debug=0)
app.session_interface = Session()
app.session_cookie_name = "isucon_session_python"
app.wsgi_app = ProxyFix(app.wsgi_app)


def load_config():
    global config
    print("Loading configuration")
    env = os.environ.get("ISUCON_ENV") or "local"
    with open("../config/" + env + ".json") as fp:
        config = json.load(fp)


def connect_db():
    global config