Example #1
1
def get_app():
    app = Flask("flask_seed")
    app.config.from_object("default_settings")
    if os.getenv("FLASK_SEED_SETTINGS", None):
        app.config.from_envvar("FLASK_SEED_SETTINGS")

    app.secret_key = app.config["SECRET_KEY"]

    # app.g  = globals.load()
    app.db = MongoEngine(app)

    app.jinja_env.add_extension("util.Markdown2Extension")
    app.jinja_env.filters["slugify"] = slugify
    app.jinja_env.filters["timesince"] = timesince
    app.jinja_env.filters["timeuntil"] = timeuntil
    app.jinja_env.filters["jsonencode"] = jsonencode
    app.jinja_env.globals["newrelic_head"] = newrelic_head
    app.jinja_env.globals["newrelic_foot"] = newrelic_foot

    if not app.config.get("TEMPLATE_DEBUG", True):
        compiled_templates = os.path.join(os.path.abspath(os.path.dirname(__file__)), "compiled_templates")
        compiled_files = path.path(compiled_templates).files()
        if len(compiled_files) <= 1:
            app.jinja_env.compile_templates(compiled_templates, zip=None, py_compile=True)
        app.jinja_env.loader = ModuleLoader(compiled_templates)

    return app
Example #2
1
def get_app():
    app = Flask("kardboard")
    app.config.from_object("kardboard.default_settings")
    if os.getenv("KARDBOARD_SETTINGS", None):
        app.config.from_envvar("KARDBOARD_SETTINGS")

    app.secret_key = app.config["SECRET_KEY"]

    app.db = PortAwareMongoEngine(app)

    app.jinja_env.add_extension("kardboard.util.Markdown2Extension")
    app.jinja_env.filters["slugify"] = slugify
    app.jinja_env.filters["timesince"] = timesince

    configure_logging(app)

    try:
        from flaskext.exceptional import Exceptional
    except ImportError:
        pass
    exceptional_key = app.config.get("EXCEPTIONAL_API_KEY", "")
    if exceptional_key:
        exceptional = Exceptional(app)
        app._exceptional = exceptional

    return app
def register_server():
    app = Flask(__name__)

    settings_entry = os.environ.get("SKELETONS_SETTINGS_ENTRY", "skeletons")
    server_settings = get_config(settings_entry)
    app.config["server_settings"] = server_settings

    app.config["SESSION_COOKIE_NAME"] = server_settings.cookie_name
    app.secret_key = server_settings.secret_key

    app.register_blueprint(greeting_blueprint, url_prefix="/greeting")

    @app.before_request
    def before_request():
        pass

    @app.teardown_request
    def teardown_request(error=None):
        pass

    @app.after_request
    def after_request(response):
        return response

    @app.errorhandler(404)
    def page_not_found(e):
        return jsonify({"error": "Invalid API path"}), 404

    @app.errorhandler(HTTPError)
    def http_error(e):
        return jsonify({"error": e.msg}), e.status_code

    return app
Example #4
1
File: app.py Project: CMGS/neptulon
def create_app():
    app = Flask(__name__, static_url_path="/neptulon/static")
    app.config.from_object("neptulon.config")
    app.secret_key = app.config["SECRET_KEY"]

    logging.basicConfig(format="%(levelname)s:%(asctime)s:%(message)s", level=logging.INFO)

    db.init_app(app)
    mail.init_app(app)
    oauth.init_app(app)

    for bp in blueprints:
        import_name = "%s.views.%s:bp" % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.user = None
        if "id" in session:
            g.user = User.get(session["id"])
        g.redir = request.args.get("redirect", "")
        g.start = request.args.get("start", type=int, default=0)
        g.limit = request.args.get("limit", type=int, default=20)

    return app
Example #5
1
def create_app():
    options = {"port": 0, "unitTesting": False}
    WebConfig.config(options)

    b = Borg()
    app = Flask(__name__)
    app.config["DEBUG"] = True
    app.config["SECRET_KEY"] = b.secretKey
    app.config["SECURITY_PASSWORD_HASH"] = b.passwordHash
    app.config["SECURITY_PASSWORD_SALT"] = b.passwordSalt
    app.config["SQLALCHEMY_DATABASE_URI"] = (
        "mysql://" + b.auth_dbUser + ":" + b.auth_dbPasswd + "@" + b.auth_dbHost + "/" + b.auth_dbName
    )
    b.logger.setLevel(b.logLevel)
    b.logger.debug("Error handlers: {0}".format(app.error_handler_spec))
    app.secret_key = os.urandom(24)
    logger = logging.getLogger("werkzeug")
    logger.setLevel(b.logLevel)
    enable_debug = b.logLevel = logging.DEBUG

    cors = CORS(app)
    db.init_app(app)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    from main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    with app.app_context():
        db.create_all()

    return app
Example #6
1
def create_app():
    app = Flask(__name__)
    app.debug = True
    app.secret_key = urandom(24)

    # 注册蓝本
    from .news import news as news_blueprint

    app.register_blueprint(news_blueprint)

    from .query import query as query_blueprint

    app.register_blueprint(query_blueprint)

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .kebiao import kebiao as kebiao_blueprint

    app.register_blueprint(kebiao_blueprint)

    from .repair import repair as repair_blueprint

    app.register_blueprint(repair_blueprint)

    return app
Example #7
1
def get_flask_app(roles=False, views=None, **kwargs):
    db = SQLAlchemy("sqlite:///:memory:")
    views = views or []
    auth = authcode.Auth(SECRET_KEY, db=db, roles=roles, views=views, **kwargs)
    User = auth.User

    db.create_all()
    user = User(login=u"meh", password="foobar")
    db.add(user)
    db.commit()

    app = Flask("test")
    app.secret_key = os.urandom(32)
    app.testing = True
    authcode.setup_for_flask(auth, app)

    @app.route("/login/")
    def login():
        user = User.by_id(1)
        auth.login(user)
        return "login"

    @app.route("/logout/")
    def logout():
        auth.logout()
        return "logout"

    return auth, app, user
Example #8
1
def create_app(database):
    global app

    # create our little application :)
    app = Flask(__name__)
    app.debug = True
    app.config.from_object(__name__)
    app.secret_key = "^]CUCqFL6;wVz-w4%#ZYKTIB]kWT+3rfAq@_}(p;r%Mjq6umt9\>8-.){.u!uA*"

    # db import
    from libs.db import init_connection

    # db setup
    init_connection(database)

    # presenters
    from presenters.listing import listing
    from presenters.doc import doc

    # register modules
    app.register_module(listing)
    app.register_module(doc)

    # template filters
    @app.template_filter("test_format")
    def test_format(input):
        return input[::-1]

    return app
Example #9
1
def _get_flask_app(roles=False, **kwargs):
    db = SQLAlchemy("sqlite:///:memory:")
    auth = authcode.Auth(SECRET_KEY, db=db, roles=roles, password_minlen=3, **kwargs)
    User = auth.User

    db.create_all()
    user = User(login=u"meh", password="foobar")
    db.add(user)

    user2 = User(login=u"foo", password="bar")
    db.add(user2)
    db.commit()

    app = Flask("test")
    app.secret_key = os.urandom(32)
    app.testing = True

    @app.route("/protected/")
    @auth.protected()
    def protected():
        return u"Welcome"

    authcode.setup_for_flask(auth, app)
    auth.session = {}
    return auth, app, user
Example #10
0
def create_application():
    global app, db, UserManager

    if not config.check():
        return None

    if not os.path.exists(config.get("base", "cache_dir")):
        os.makedirs(config.get("base", "cache_dir"))

    import db

    db.init_db()

    app = Flask(__name__)
    app.secret_key = "?9huDM\\H"

    if config.get("base", "log_file"):
        import logging
        from logging.handlers import TimedRotatingFileHandler

        handler = TimedRotatingFileHandler(config.get("base", "log_file"), when="midnight")
        handler.setLevel(logging.WARNING)
        app.logger.addHandler(handler)

    app.teardown_request(teardown)

    import frontend
    import api

    return app
Example #11
0
def create_app(config_name):
    if config_name != "test":
        print "Application created based on config_name: %s" % (config_name)

    app = Flask(__name__)
    app._static_folder = "static"
    app.debug = True

    app_config = config[config_name]
    app.config.from_object(app_config)
    config[config_name].init_app(app)

    app.secret_key = "tell you"

    db.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    pages.init_app(app)
    from .send_mail import sendmail as send_mail_blueprint

    app.register_blueprint(send_mail_blueprint)

    from .webviews import webviews as webviews

    app.register_blueprint(webviews)
    return app
Example #12
0
def app_init(cfg="../config.py"):
    """ Initialises the flask app. """

    app = Flask(__name__, static_folder=os.path.abspath("static"))
    app.register_blueprint(API, url_prefix="/api")
    app.config.from_pyfile(cfg)
    app.debug = app.config.get("DEBUG")
    app.secret_key = app.config.get("SECRET_KEY")
    oauth = OAuth()

    """GOOGLE_CLIENT_ID = conf.GOOGLE_CLIENT_ID
    GOOGLE_CLIENT_SECRET = conf.GOOGLE_CLIENT_SECRET
    """

    google = oauth.remote_app(
        "google",
        base_url="https://www.google.com/accounts/",
        authorize_url="https://accounts.google.com/o/oauth2/auth",
        request_token_url=None,
        request_token_params={"scope": "https://www.googleapis.com/auth/userinfo.email", "response_type": "code"},
        access_token_url="https://accounts.google.com/o/oauth2/token",
        access_token_method="POST",
        access_token_params={"grant_type": "authorization_code"},
        consumer_key=app.config.get("GOOGLE_CLIENT_ID"),
        consumer_secret=app.config.get("GOOGLE_CLIENT_SECRET"),
    )

    return app, google
Example #13
0
    def setUp(self):
        app = Flask(__name__)
        app.secret_key = "N4buDSXfaHx2oO8g"
        self.app = app
        auth = Auth(app)

        @login_required
        def needs_login():
            return "needs_login"

        app.add_url_rule("/needs_login/", "needs_login", needs_login)

        @permission_required(resource="post", action="view")
        def post_view():
            return "needs_post_view"

        app.add_url_rule("/post_view/", "post_view", post_view)

        @app.route("/login_view/")
        def login_view():
            return "login_view"

        user = AuthUser(username="user")
        user.role = "testuser"
        testuser_role = Role("testuser", [Permission("post", "view")])
        auth.load_role = lambda _: testuser_role
        self.user = user
Example #14
0
 def create_app(self):
     app = Flask(__name__)
     app.config.update({"OAUTH1_PROVIDER_ENFORCE_SSL": False})
     app.debug = True
     app.testing = True
     app.secret_key = "development"
     return app
def create_app(database):
    global app

    # create our little application :)
    app = Flask(__name__)
    app.config.from_object(config)
    app.secret_key = config.SECRET_KEY

    # db import
    from libs.db import init_connection

    # db setup
    init_connection(database)

    # presenters
    from presenters.home import home

    # register modules
    app.register_blueprint(home)

    # template filters
    @app.template_filter("test_format")
    def test_format(input):
        return input[::-1]

    return app
def make_json_app(import_name, **kwargs):
    """
    Creates a JSON-oriented Flask app.

    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):

    { "message": "405: Method Not Allowed" }
    """

    def make_json_error(ex):
        pprint.pprint(ex)
        pprint.pprint(ex.code)
        # response = jsonify(message=str(ex))
        response = json.dumps(ex)
        response.status_code = ex.code if isinstance(ex, HTTPException) else 500
        return response

    app = Flask(import_name, **kwargs)
    # app.debug = True
    app.secret_key = id_generator(24)

    for code in default_exceptions.keys():
        app.error_handler_spec[None][code] = make_json_error

    return app
Example #17
0
def create_app():
    app = Flask(__name__, static_url_path="/argonath/static")
    app.config.from_object("argonath.config")
    app.secret_key = "wolegeca"

    logging.basicConfig(format="%(levelname)s:%(asctime)s:%(message)s", level=logging.INFO)

    for ext in (db, openid2):
        ext.init_app(app)

    for bp in blueprints:
        import_name = "%s.views.%s:bp" % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        user_dict = json.loads(request.cookies.get(app.config["OPENID2_PROFILE_COOKIE_NAME"], "{}"))
        g.user = user_dict and User.get_or_create(user_dict["username"], user_dict["email"]) or None
        g.start = request.args.get("start", type=int, default=0)
        g.limit = request.args.get("limit", type=int, default=20)

    return app
Example #18
0
def get_app():
    # app = Flask(__name__)
    app = Flask("pyfem")
    app.config.from_object(Config)

    # set environment PYFEM_SETTINGS=testing_settings to automatically use a -test version of db
    if os.environ.get("PYFEM_SETTINGS"):
        if os.environ["PYFEM_SETTINGS"] == "testing_settings":
            app.config["MONGODB_SETTINGS"] = dict(db=app.config["MONGO_DBNAME"] + "-test")

    app.secret_key = app.config["SECRET_KEY"]

    app.me = MongoEngine(app)
    app.pymongo = _get_db()

    # app.jinja_env.add_extension('util.Markdown2Extension')
    # app.jinja_env.filters['slugify'] = slugify
    # app.jinja_env.filters['timesince'] = timesince
    # app.jinja_env.filters['timeuntil'] = timeuntil
    # app.jinja_env.filters['jsonencode'] = jsonencode
    # app.jinja_env.globals['newrelic_head'] = newrelic_head
    # app.jinja_env.globals['newrelic_foot'] = newrelic_foot

    # if not app.config.get('TEMPLATE_DEBUG', True):
    #     compiled_templates = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'compiled_templates')
    #     compiled_files = path.path(compiled_templates).files()
    #     if len(compiled_files) <= 1:
    #         app.jinja_env.compile_templates(compiled_templates, zip=None, py_compile=True)
    #     app.jinja_env.loader = ModuleLoader(compiled_templates)

    configure_logging(app)
    return app
Example #19
0
def create_app(init=False):
    app = Flask(__name__, static_url_path="/elegon/static", template_folder="templates")
    app.config.from_object("elegon.config")
    app.secret_key = "c534d51a57638e8a8a51c36d4a4128b89f8beb22"

    for ext in (db, openid2):
        ext.init_app(app)

    for bp in blueprints:
        import_name = "%s.ui.%s:bp" % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs, enumerate):
        app.add_template_global(fl)

    with app.app_context():
        db.create_all()

    @app.before_request
    def init_global_vars():
        user_dict = json.loads(request.cookies.get(app.config["OPENID2_PROFILE_COOKIE_NAME"], "{}"))
        g.user = user_dict and User.get_or_create(user_dict["username"], user_dict["email"]) or None
        g.start = request.args.get("start", type=int, default=0)
        g.limit = request.args.get("limit", type=int, default=20)

    init_logging()

    if init:
        init_scheduler()
        start_scheduler()
        signal.signal(signal.SIGTERM, stop_scheduler)
        signal.signal(signal.SIGHUP, stop_scheduler)

    return app
Example #20
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile(get_config_file(app.root_path))
    Bootstrap(app)
    app.extensions["bootstrap"]["cdns"]["jquery"] = WebCDN("//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/")
    app.secret_key = app.config["SECRET_KEY"]
    return app
def create_app():
    app = Flask(__name__)
    auto = Autodoc(app)
    cal = Calendar()
    event = Event()
    from open_event.views.views import app as routes

    app.register_blueprint(routes)
    migrate = Migrate(app, db)

    db.init_app(app)
    manager = Manager(app)
    manager.add_command("db", MigrateCommand)

    cors = CORS(app)
    app.secret_key = "super secret key"
    app.config.from_object("config.ProductionConfig")
    app.config["UPLOADS_FOLDER"] = os.path.realpath(".") + "/static/"
    app.config["FILE_SYSTEM_STORAGE_FILE_VIEW"] = "static"
    app.config["STATIC_URL"] = "/static/"
    app.config["STATIC_ROOT"] = "staticfiles"
    app.config["STATICFILES_DIRS"] = (os.path.join(BASE_DIR, "static"),)
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.ERROR)

    admin_view = AdminView("Open Event")
    admin_view.init(app)
    admin_view.init_login(app)

    return app, manager, db
Example #22
0
    def __init__(self, config_path, reference_version):
        assert os.path.exists(config_path), "%s does not exist" % config_path
        assert reference_version in ["hg38", "b37"], "bad reference_version: %s" % reference_version
        self.config_path = config_path
        self.config = ConfigParser(interpolation=ExtendedInterpolation())
        self.config.read(config_path)
        self.config.add_section("ref")
        for k, v in self.config["ref_%s" % reference_version].iteritems():
            self.config.set("ref", k, v)

        assert len(self.config["ref"].items()) > 1
        # set_env_aws_credentials()

        os.environ["REQUESTS_CA_BUNDLE"] = "/etc/ssl/certs/ca-certificates.crt"
        # export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
        from cosmos.web.gemon.views import bprint as gemon_bprint
        from cosmos.api import Cosmos, default_get_submit_args
        from functools import partial
        from flask import Flask

        flask_app = Flask("genomekey", template_folder=os.path.join(library_path, "web/templates"))

        flask_app.secret_key = "\x16\x89\xf5-\tK`\xf5FY.\xb9\x9c\xb4qX\xfdm\x19\xbd\xdd\xef\xa9\xe2"
        flask_app.register_blueprint(gemon_bprint, url_prefix="/gemon")
        self.flask_app = flask_app

        def get_submit_args(task):
            return default_get_submit_args(task, parallel_env="orte")

        self.cosmos_app = Cosmos(
            self.config["gk"]["database_url"],
            default_drm=self.config["gk"]["default_drm"],
            flask_app=flask_app,
            get_submit_args=partial(default_get_submit_args, parallel_env="orte"),
        )
Example #23
0
def create_application():
    global app

    if not config.check():
        return None

    if not os.path.exists(config.get("webapp", "cache_dir")):
        os.makedirs(config.get("webapp", "cache_dir"))

    app = Flask(__name__)
    app.secret_key = "?9huDM\\H"
    app.config["UPLOAD_FOLDER"] = "/home/davidb/sandbox/supysonic/uploads"

    app.teardown_appcontext(teardown_db)

    if config.get("webapp", "log_file"):
        import logging
        from logging.handlers import TimedRotatingFileHandler

        handler = TimedRotatingFileHandler(config.get("webapp", "log_file"), when="midnight")
        if config.get("webapp", "log_level"):
            mapping = {
                "DEBUG": logging.DEBUG,
                "INFO": logging.INFO,
                "WARNING": logging.WARNING,
                "ERROR": logging.ERROR,
                "CRTICAL": logging.CRITICAL,
            }
            handler.setLevel(mapping.get(config.get("webapp", "log_level").upper(), logging.NOTSET))
        app.logger.addHandler(handler)

    from supysonic import frontend
    from supysonic import api

    return app
Example #24
0
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = "1234"

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)
        self.csrf.exempt_urls(("/foo",))

        @app.route("/foo/baz", methods=["POST"])
        def foobaz():
            return "bar"

        @app.route("/foo/quz", methods=["POST"])
        def fooquz():
            return "bar"

        @app.route("/bar", methods=["POST"])
        def bar():
            return "foo"
def register_server(url_prefix="", settings={}):
    app = Flask(__name__, **settings)
    app.secret_key = SECRET_KEY

    app.register_blueprint(vv_blueprint, url_prefix="{}".format(url_prefix))

    @app.before_request
    def before_request():
        local_engine = create_engine("sqlite:///test_db")
        g.db = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=local_engine))

    @app.teardown_request
    def teardown_request(error=None):
        if hasattr(g, "db"):
            g.db.close()
            g.db.remove()

    @app.after_request
    def after_request(response):
        origin = request.headers.get("Origin", "*")
        response.headers.add("Access-Control-Allow-Origin", origin)
        response.headers.add("Access-Control-Allow-Credentials", "true")

        return response

    @app.route("{}/location".format(url_prefix))
    def location():
        result = {"location": [{"name": "Venice Beach", "lat_lng": {"lat": 33.990, "lng": -118.459}, "id": 1}]}
        return jsonify(result)

    @app.errorhandler(404)
    def page_not_found(e):
        return "Error: Invalid API Path", 404

    return app
Example #26
0
File: app.py Project: CMGS/argonath
def create_app():
    app = Flask(__name__, static_url_path="/argonath/static")
    app.config.from_object("argonath.config")
    app.config.setdefault("SQLALCHEMY_TRACK_MODIFICATIONS", True)
    app.secret_key = "wolegeca"

    logging.basicConfig(format="%(levelname)s:%(asctime)s:%(message)s", level=logging.INFO)

    for ext in (db,):
        ext.init_app(app)

    for bp in blueprints:
        import_name = "%s.views.%s:bp" % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs):
        app.add_template_global(fl)

    @app.before_request
    def init_global_vars():
        g.user = "id" in session and User.get(session["id"]) or None
        g.start = request.args.get("start", type=int, default=0)
        g.limit = request.args.get("limit", type=int, default=20)

    return app
Example #27
0
def setup():
    app = Flask(__name__)
    app.config["CSRF_ENABLED"] = False
    app.secret_key = "1"
    admin = Admin(app)

    return app, admin
Example #28
0
def create_app(root: str, config: str) -> Flask:
    """Create a new Flask application with the provided configuration.

    :param root: The application root module name.
    :param config: The application configuration mode.
    """
    app = Flask(__name__)
    app.config.from_object(CONFIG_PATH_FORMAT % (root, config))

    if app.config["INIT"]["debug"]:
        print(LOG_MODE_DEBUG)
    else:
        print(LOG_MODE_PRODUCTION)

    if app.config["GOOGLECLIENTID"]:
        print(LOG_ID_FORMAT % app.config["GOOGLECLIENTID"])
    else:
        print(LOG_ID_NOT_FOUND)

    # Async socket initialization
    eventlet.monkey_patch()
    socketio.init_app(app)

    # Configuration for mySQL database
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["SQLALCHEMY_DATABASE_URI"] = app.config["DATABASE_URL"].replace("mysql", "mysql+pymysql", 1)
    db.init_app(app)

    # Configuration for login sessions
    app.secret_key = app.config["SECRET_KEY"]
    login_manager.init_app(app)

    # Flask Debug Toolbar
    toolbar.init_app(app)

    # Database migration management
    migrate.init_app(app, db)
    migration_manager(app)

    from .public.views import public
    from .queue.views import queue
    from .admin.views import admin
    from .dashboard.views import dashboard

    BLUEPRINTS = [public, queue, admin, dashboard]

    for blueprint in BLUEPRINTS:
        print(' * Registering blueprint "%s"' % blueprint.name)
        app.register_blueprint(blueprint)

    # subdomain routes with special urls
    app.register_blueprint(admin, url_prefix="/subdomain/<string:queue_url>/admin")
    app.register_blueprint(queue, url_prefix="/subdomain/<string:queue_url>")

    # register error handlers
    app.register_error_handler(401, standard_error)
    app.register_error_handler(404, error_not_found)
    app.register_error_handler(500, error_server)

    return app
Example #29
0
def init_flask():
    # Initialize app!
    app = Flask(__name__)
    # Needed for Flask-admin.
    app.secret_key = "secret"
    init_logging(app)
    init_cfg(app)

    # Add 404 error handler.
    @app.errorhandler(404)
    def not_found(error):
        return render_template("404.html"), 404

    # Initialize blueprints.
    from flask_website.views import general, store, store_api

    app.register_blueprint(general.mod)
    app.register_blueprint(store.mod)
    app.register_blueprint(store_api.mod)

    db = database.Database()
    db.init_db(app)

    init_admin(app, db)
    # init_test_db(db)

    # Utility functions for Jinja2.
    app.jinja_env.globals.update(jsonBoolean=lambda b: str(b).lower())

    return app
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.secret_key = "1234"
        app.config["SEASURF_INCLUDE_OR_EXEMPT_VIEWS"] = "include"

        self.app = app

        csrf = SeaSurf()
        csrf._csrf_disable = False
        self.csrf = csrf

        # Initialize CSRF protection.
        self.csrf.init_app(app)

        @csrf.include
        @app.route("/foo", methods=["POST"])
        @app.route("/foo/<term>", methods=["POST"])
        def foo(term=None):
            return "bar"

        @app.route("/bar", methods=["POST"])
        @app.route("/bar/<term>", methods=["POST"])
        def bar(term=None):
            return "foo"