Beispiel #1
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
Beispiel #2
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'
Beispiel #3
0
def create_app():
  app = Flask(__name__)
  app.secret_key = 'not a secret key'

  # FIXME duplicated in database.py
  if is_production():
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:jackathon@localhost/watchtower'
  elif is_scan():
    #app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:jackathon@75.101.157.206/watchtower'
    # TODO assumes static private ip
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:jackathon@10.73.181.115/watchtower'
  else:
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////var/watchtower/watchtower.db'
  db.init_app(app)
  # admin setup
  admin = Admin(app)
  admin.add_view(ModelView(Page, db.session))
  class MyModelView(ModelView):
    def __init__(self, model, session, name=None, category=None, endpoint=None, url=None, **kwargs):
      for k, v in kwargs.iteritems():
          setattr(self, k, v)

      super(MyModelView, self).__init__(model, session, name=name, category=category, endpoint=endpoint, url=url)

    def is_accessible(self):
      # Logic
      return True
  #admin.add_view(MyModelView(Version, db.session, column_list=['id', 'foreign_key']))
  admin.add_view(ModelView(Version, db.session,))
  admin.add_view(ModelView(Element, db.session,))
  admin.add_view(ModelView(User, db.session,))
  return app
Beispiel #4
0
def setup():
    app = Flask(__name__)
    app.config['CSRF_ENABLED'] = False
    app.secret_key = '1'
    admin = Admin(app)

    return app, admin
Beispiel #5
0
def create_app():
    app = Flask(__name__)
    # Set crucial variables
    app.secret_key = os.environ['SECRET_KEY']
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']

    # Set non crucial variables
    app.config['MAILGUN_API_URL'] = os.environ.get('MAILGUN_API_URL', '')
    app.config['MAILGUN_API_KEY'] = os.environ.get('MAILGUN_API_KEY', '')
    app.config['MAILGUN_TEST_OPTION'] = True if os.environ.get('MAILGUN_TEST_OPTION', 'True') == 'True' else False
    app.config['NOTIFICATION_EMAIL'] = os.environ.get('MAILGUN_SMTP_LOGIN', '')
    app.config['REDDIT_PASSWORD'] = os.environ.get('WPC_REDDIT_PASSWORD', '')
    app.config['REDDIT_USERNAME'] = os.environ.get('WPC_REDDIT_USERNAME', '')
    app.config['YOUTUBE_KEY'] = os.environ.get('WPC_YOUTUBE_KEY', '')
    app.config['GA_TRACKING_CODE'] = os.environ.get('GA_TRACKING_CODE', '')
    app.config['REDDIT_API_ID'] = os.environ.get('WPC_APP_ID', '')
    app.config['REDDIT_API_SECRET'] = os.environ.get('WPC_APP_SECRET', '')
    app.config['RTMP_LOGIN'] = os.environ.get('RTMP_LOGIN', '')
    app.config['RTMP_PASSWORD'] = os.environ.get('RTMP_PASSWORD', '')
    app.config['RTMP_SERVER'] = os.environ.get('RTMP_SERVER', '127.0.0.1')
    app.config['SERVER_NAME'] = os.environ.get('SERVER_NAME', '')

    app.config['REDDIT_WEB_APP_USER_AGENT'] = "/r/WatchPeopleCode web app(main contact: /u/godlikesme)"
    app.config['REDDIT_BOT_USER_AGENT'] = "/r/WatchPeopleCode flairs&streams bot (main contact: /u/godlikesme)"

    Bootstrap(app)
    loggers_and_levels = [(app.logger, logging.INFO),
                          (logging.getLogger('sqlalchemy'), logging.WARNING),
                          (logging.getLogger('apscheduler.scheduler'), logging.INFO)]
    setup_logging(loggers_and_levels, logentries_id=os.environ.get('LOGENTRIES_ID', None))

    app.logger.info("App created!")

    return app
Beispiel #6
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.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
Beispiel #7
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
def create_app():
    app = Flask(__name__)
    auto=Autodoc(app)
    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
Beispiel #9
0
Datei: main.py Projekt: vddd/rn
def create_app():
    app = Flask(__name__)

    load_config(app)

    app.debug = app.config['DEBUG']
    app.secret_key = app.config['SECRET_KEY']

    # init flask extensions
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    app.context_processor(inject_roles)

    # init my modules
    upload.init_app(app)
    filters.init_app(app)
    views.init_app(app)

    # register routes
    app.register_blueprint(views.bp_basic)
    app.register_blueprint(views.bp_responsable)
    app.register_blueprint(views.bp_activite)
    app.register_blueprint(views.bp_brn)

    return app
Beispiel #10
0
def create_app(configfile=None):
    # We are using the "Application Factory"-pattern here, which is described
    # in detail inside the Flask docs:
    # http://flask.pocoo.org/docs/patterns/appfactories/

    app = Flask(__name__)
    app.secret_key = "realsecretkey"
    
    # We use Flask-Appconfig here, but this is not a requirement
    AppConfig(app)

    # Install our Bootstrap extension
    Bootstrap(app)

    # Our application uses blueprints as well; these go well with the
    # application factory. We already imported the blueprint, now we just need
    # to register it:
    app.register_blueprint(frontend)

    # Because we're security-conscious developers, we also hard-code disabling
    # the CDN support (this might become a default in later versions):
    app.config['BOOTSTRAP_SERVE_LOCAL'] = True

    # We initialize the navigation as well
    nav.init_app(app)

    return app
Beispiel #11
0
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
Beispiel #12
0
def create_app(config_filename='config.default.DevelopmentConfig'):
    app = Flask(__name__)
    app.config.from_object(config_filename)

    app.secret_key = app.config['SECRET_KEY']
    app.permanent_session_lifetime = timedelta(minutes=app.config['SESSION_ALIVE_MINUTES'])
    app.session_interface = ItsdangerousSessionInterface()
    # SOCKET
    # url = '127.0.0.1'
    # client_socket.connect((url, 8000))

    # logging module
    log_filepath = os.path.join(app.config['ROOT_DIR'], 'app_server/log')
    log.init(log_filepath=log_filepath, log_level=app.config['LOG_LEVEL'])
    log.info("CREATE HIMS APP : "+__name__)

    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)

    from youngs_server.api.auth_controllers import api_auth
    from youngs_server.api.member_controllers import api_member
    from youngs_server.api.lecture_controllers import api_lecture
    from youngs_server.api.question_controllers import api_question

    app.register_blueprint(api_auth)
    app.register_blueprint(api_member)
    app.register_blueprint(api_lecture)
    app.register_blueprint(api_question)
    return app
Beispiel #13
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
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
Beispiel #15
0
def init_app():
    db_path = 'db1.sqlite'

    # 初始化并配置 flask
    app = Flask(__name__)
    # 这一行 加了就没 warning
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    # 设置你的加密 key
    app.secret_key = 'TODO fixme'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(db_path)
    # 初始化 db
    db.init_app(app)
    db.app = app

    # 必须在函数中 import 蓝图
    # 否则循环引用(因为蓝图中 import 了 model, model 引用了这个文件里面目的 db)
    # from .auth import blue as auth
    from .controllers import main as controllers
    from .api import main as api1

    # 注册蓝图
    # app.register_blueprint(auth)
    app.register_blueprint(controllers)
    app.register_blueprint(api1, url_prefix='/api')

    # 把 app 引用返回
    return app
Beispiel #16
0
def create_app(config=config):
    app = Flask(__name__)
    app.config.from_object(config)
    app.secret_key = 'tekitouna himitu no kagi'
    init_extensions(app)
    init_views(app)
    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
def get_app():
    """load modules and return WSGI application"""

    import os
    from flask import Flask
    import sys
    from common import *
    global get_app, _app

    _app = Flask(__name__)

    get_app = lambda: _app  # avoid duplicate import

    _app.config.from_object(app_config)

    _app.secret_key = "hokey dokey, here's the key"

#    login_manager = LoginManager()
#    login_manager.init_app(_app)

#    @login_manager.user_loader
#    def load_user(username):
#        from model.user import User
#        user = User.get_one(username=username)
#        user._authenticated = True
#        return user

    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 = jsonify(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.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

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

    return app, admin
Beispiel #21
0
def create_application():
	global app

	if not config.check():
		return None

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

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

	app.teardown_appcontext(teardown_db)

	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)

	from supysonic import frontend
	from supysonic import api

	return app
Beispiel #22
0
def create_app(db_uri):
    app = Flask(__name__)
    app.engine = create_engine(db_uri, convert_unicode=True)
    from monkeyapp.views import api
    app.register_blueprint(api)
    app.secret_key = "devays key"
    return app
Beispiel #23
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
def create_app(configpath):
    app = Flask('Neuronal activity analyzer',
                template_folder='templates',
                static_folder='webgui/static')
    app.config.from_pyfile(configpath)
    app.secret_key = app.config['SECRET_KEY']

    # Create folders if they don't exist
    folders = [app.config['VIDEO_FOLDER'],
               app.config['UPLOAD_FOLDER'],
               app.config['DATA_FOLDER']]
    for folder in folders:
        if not os.path.isdir(folder):
            os.mkdir(folder)

    app.register_blueprint(main_blueprint)
    app.register_blueprint(file_select_blueprint)
    app.register_blueprint(segmentation_blueprint)
    app.register_blueprint(roi_editor_blueprint)
    app.register_blueprint(statistics_blueprint)
    app.register_blueprint(batch_blueprint)

    app.after_request(disable_cache)

    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False

    compress.init_app(app)

    return app
Beispiel #25
0
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
Beispiel #26
0
def create_app(debug=settings.DEBUG):
    app = Flask(
        __name__,
        template_folder=settings.TEMPLATE_FOLDER,
        static_folder=settings.STATIC_FOLDER,
    )

    # 注册所有的蓝图
    app.register_blueprint(bp_test)
    app.register_blueprint(bp_ball)

    # 配置jinja模板
    app.jinja_env.globals.update(JINJA2_GLOBALS)
    app.jinja_env.filters.update(JINJA2_FILTERS)

    # 配置secret_key
    app.secret_key = 'secret_key'


    @app.before_request
    def before_request():
        g.file = open('./nothing')

    @app.after_request
    def after_request(exception):
        g.file.close()


    return app
Beispiel #27
0
def test_content_type(sign_func):
    responses.add(responses.GET, "https://flask.atlassian.net/")

    app = Flask(__name__)
    app.secret_key = "anything"
    app.debug = True
    backend = MemoryBackend({
        "oauth_token": "faketoken",
        "oauth_token_secret": "fakesecret",
        "oauth_session_handle": "fakehandle",
        "oauth_expires_in": "157680000",
        "oauth_authorization_expires_in": "160272000",
    })
    jira_bp = make_jira_blueprint(
        "https://flask.atlassian.net",
        consumer_key="fakekey",
        backend=backend,
    )
    app.register_blueprint(jira_bp)

    @app.route("/test")
    def api_request():
        jira_bp.session.get("/")
        return "success"

    resp = app.test_client().get("/test")
    headers = responses.calls[0].request.headers
    assert "Content-Type" in headers
    assert headers["Content-Type"] == "application/json"
Beispiel #28
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
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
    if database: 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
Beispiel #30
0
    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'