示例#1
1
文件: app.py 项目: zmcghee/kardboard
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
示例#2
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'
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
示例#4
0
def setup():
    app = Flask(__name__)
    app.config['CSRF_ENABLED'] = False
    app.secret_key = '1'
    admin = Admin(app)

    return app, admin
示例#5
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'
示例#6
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
示例#7
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"
示例#8
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
示例#9
0
文件: app.py 项目: ninjadq/argonath
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
示例#10
0
文件: web.py 项目: jhargis/supysonic
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
示例#11
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
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
示例#13
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
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
示例#15
0
文件: 14end.py 项目: ideascf/play
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
示例#16
0
文件: app.py 项目: tonicbupt/elegon
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
示例#17
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
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
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
示例#20
0
def setup():
    app = Flask(__name__)
    app.config["CSRF_ENABLED"] = False
    app.secret_key = "1"
    admin = Admin(app)

    return app, admin
示例#21
0
文件: main.py 项目: 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
示例#22
0
文件: app.py 项目: typpo/watchtower
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://*****:*****@localhost/watchtower'
  elif is_scan():
    #app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@75.101.157.206/watchtower'
    # TODO assumes static private ip
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@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
示例#23
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
示例#24
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
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
示例#26
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
示例#27
0
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
示例#28
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
示例#29
0
文件: app.py 项目: 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
示例#30
0
from flask import Flask, render_template, request, url_for, redirect, session
import sqlite3 as lite

app = Flask(__name__)
app.secret_key = 'minhdang241'


@app.route('/')
def home():
    result, show_order, order_history, username, password = session.get(
        'result'), session.get('show_order', False), session.get(
            'order_history', []), session.get('username',
                                              ''), session.get('password', '')

    return render_template('demo.html',
                           result=result,
                           show_order=show_order,
                           order_history=enumerate(order_history),
                           username=username,
                           password=password)


@app.route('/logout', methods=['GET'])
def logout():
    session.clear()
    return redirect(url_for('home'))


@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
示例#31
0
from iptvfilter import IPTVFilter

IPTV_M3U_URL = os.environ['IPTV_M3U_URL']
BLACKLIST_GROUPS = os.environ['BLACKLIST_GROUPS']
API_KEY = os.environ['API_KEY']
SECRET_KEY = os.environ['SECRET_KEY']
SEPARATOR = ';'
NAME_NEW_FILE = 'list.m3u'
NAME_FILE_COMPLEMENT = 'list_complement.m3u'
UPLOAD_LIST_COMPLEMENT_FOLDER = 'storage'

## Flask

app = Flask(__name__)
app.secret_key = SECRET_KEY
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024
app.config['UPLOAD_FOLDER'] = UPLOAD_LIST_COMPLEMENT_FOLDER


@app.route("/list", methods=["GET"])
def get_list():
    if API_KEY != request.args.get('api_key'):
        return Response('api_key unauthorized',
                        status=403,
                        mimetype='text/plain')

    iptv_filter = IPTVFilter(IPTV_M3U_URL, BLACKLIST_GROUPS, SEPARATOR)
    iptv_list = iptv_filter.generate_list()
    iptv_list = iptv_list.encode("utf-8")
    file_binary = bytearray(iptv_list)
示例#32
0
文件: app.py 项目: tehnix53/AgroDrone
from flask import Flask, render_template, url_for
from database import df

app = Flask(__name__)
app.secret_key = "randomstring"


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


@app.route('/db')
def drone_table():
    sorted_file = df.sort_values(['name']).values
    return render_template('db.html', df=sorted_file)


@app.route('/map/<id>')
def drone_map(id):
    category = df.loc[df.id == int(id)]['category'].values[0]
    N = df.loc[df.id == int(id)]['N'].values[0]
    E = df.loc[df.id == int(id)]['E'].values[0]
    return render_template('map.html', id=id, category=category, N=N, E=E)


@app.route('/about')
def drone_about():
    return render_template('about.html')

示例#33
0
from flask import Flask, render_template, request, redirect, session, flash
from flask_bcrypt import Bcrypt
from datetime import datetime
import re
from mysqlconnection import connectToMySQL

app = Flask(__name__)
app.secret_key = "Welcome to the thunder dome"
bcrpyt = Bcrypt(app)
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')


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


@app.route('/create_user', methods=['POST'])
def create_user():
    is_valid = True
    SpecialSym = ['$', '@', '#', '%']

    if len(request.form['fname']) < 2:
        is_valid = False
        flash("Please enter a first name")

    if len(request.form['lname']) < 2:
        is_valid = False
        flash("Please enter a last name")

    if not EMAIL_REGEX.match(request.form['email']):
app.register_blueprint(error_handlers, url_prefix="/error/")
# Blueprint for movie routes
app.register_blueprint(movies)
# Blueprint for authentication routes
app.register_blueprint(auth)
# Get database access from env.py
app.config["MONGO_DBNAME"] = os.environ.get("MONGO_DBNAME")
app.config["MONGO_URI"] = os.environ.get("MONGO_URI")
# Set session type to filesystem
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_REDIS'] = redis.from_url(
    os.environ.get("REDIS_URL"), health_check_interval=30)
# Get secret key from env.py
app.secret_key = os.environ.get("SECRET_KEY")
# Initiate PyMongo
mongo.init_app(app)
# Initiate Flask Session (server-side)
sess = Session(app)


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


if __name__ == "__main__":
    app.run(host=os.environ.get("IP"),
            port=int(os.environ.get("PORT")),
            debug=True)
示例#35
0
from flask import Flask, render_template, redirect, request, session, flash
from mysqlconnection import connectToMySQL
from flask_bcrypt import Bcrypt
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')

app = Flask(__name__)
bcrypt = Bcrypt(app)
app.secret_key = "ThisIsSecret!"

mysql = connectToMySQL("userdb")

# def emailDUB ():


@app.route("/")
def index():
    # print("*****!!!WORKS!!!*****")
    return render_template("index.html")


@app.route('/regprocess', methods=['POST'])
def submit():
    session["first_name"] = request.form["first_name"]
    session["last_name"] = request.form["last_name"]
    session["email"] = request.form["email"]

    if len(session["first_name"]) < 1:
        flash("First name cannot be blank!", "first_name")

    elif len(session["first_name"]) < 3:
示例#36
0
from flask import Flask
app = Flask(__name__)
app.secret_key = "login"
示例#37
0
from flask import Flask, render_template, request, url_for, redirect, flash, session
from event import *
from manager import *

app = Flask(__name__)
app.secret_key = 'some_secret'

manager_instance = Manager()
json_instance = JsonHandler()


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


@app.route("/add_event", methods=['POST', 'GET'])
def addeventmethod():

    if request.method == 'POST':
        event_instance = Event(request.form["name"], request.form["date"],
                               request.form["city"], request.form["info"])
        event_id = manager_instance.add_event(event_instance)
        message = "Save Event ID: {}".format(event_id)
        flash(message)
        return redirect(url_for('addeventmethod'))

    return render_template('home.html')


@app.route("/search", methods=['POST', 'GET'])
示例#38
0
    pass

  conn = dbconn()
  cur = conn.cursor()
  try:
    cur.execute('select id from game_sessions where code=%s', [session_id])
    row = cur.fetchone()
    if row is not None:
      session_pk = row[0]
    else:
      # use default session if not found
      session_pk = 1

    q = 'select u.name, score from levels l join users u on l.user_id=u.id where session_id=%s and level=%s order by score'
    cur.execute(q, [session_pk, level])
    result = [{"userName": "******".join(uname.split('-')[:3]), "value": score} for uname, score in cur.fetchall()]
    return jsonify(status="ok", result=result)
  except:
    traceback.print_exc()
    return jsonify(status="error", result=[])
  finally:
    if cur is not None:
      cur.close()



if __name__ == '__main__':
    app.debug = True
    app.secret_key = 'trststrtsrtgprestnorgp654g'
    app.run(host='0.0.0.0', debug=True)
示例#39
0
import random
from flask import Flask, request, redirect, render_template, session, flash
import cgi
from decimal import Decimal
from metricManips import Number, selectUnits, selectNumbers, convertValue, roundValue, sciToStd

base_units = ['m','L','g','s']
prefixes = [('M','Mega',6), ('k','kilo',3), ('h','hecto',2), ('da','deca',1), (base_units,'base',0), ('d','deci',-1), ('c','centi',-2), ('m','milli',-3), ('µ','micro',-6), ('n','nano',-9)]
standard_prefixes = [('k','kilo',3), ('h','hecto',2), ('da','deca',1), (base_units,'base',0), ('d','deci',-1), ('c','centi',-2), ('m','milli',-3)]
no_excuse_prefixes = [('k','kilo',3), (base_units,'base',0), ('c','centi',-2), ('m','milli',-3)]

app = Flask(__name__)
app.config['DEBUG'] = True
app.secret_key = 'yrtsimehc'

def checkAnswer(correct_answer, answer):
    if answer == '':        #Check for null result.
        return False

    if answer[0] == ".":    #Convert '.xx' to '0.xx'.
        answer = "0"+answer

    if answer == correct_answer:    #Check for exact result.
        return True
    else:
        return False

@app.route('/')
def index():
    session.clear()
    return render_template('index.html',title="Metric Practice")
示例#40
0
from flask import Flask
from flask import Response
from flask import render_template, url_for, redirect, request, flash
from functools import wraps
from pyf import map
from pipe import concat
from Postgres import Postgres
from CloudSQLProxy import CloudSQLProxy

proxy = CloudSQLProxy('./cloud_sql_proxy', 'inbep-185414-2607f469165a.json')
proxy.run()

dsn = os.environ.get('PGSQL_DSN', None)
app = Flask(__name__)
app.secret_key = 's0m3_s3c43t'


def authorization(f):
    @wraps(f)
    def wrapped(**kwargs):
        r = requests.post('https://api.inbep.com.br/auth/token',
                          json=request.authorization)

        if r.status_code == 200:
            return f(**kwargs)

        return Response(None, 401,
                        {'WWW-Authenticate': 'Basic realm="Login Required"'})

    return wrapped
示例#41
0
import arrow
from flask import Flask, request, send_from_directory, g, render_template, abort
from werkzeug.utils import secure_filename

from xmind2testlink.main import xmind_to_testlink

UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = ['xmind']
DEBUG = True
DATABASE = './data.db3'
HOST = '0.0.0.0'

app = Flask(__name__)
app.config.from_object(__name__)
app.secret_key = os.urandom(32)


def connect_db():
    return sqlite3.connect(app.config['DATABASE'])


def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()


def init():
    if not exists(UPLOAD_FOLDER):
import random
import string
import httplib2
import json
import requests

# import oauth client

from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from oauth2client.client import AccessTokenCredentials

#app configuration including secret key

app = Flask(__name__)
app.secret_key = 'super_secret'

# google client secret
secret_file = json.loads(open('client_secrets.json', 'r').read())
CLIENT_ID = secret_file['web']['client_id']
APPLICATION_NAME = 'AlbumCatalog'

# Binds the engine to the metadata of the Base class so
# that the declaratives can be accessed through a DBSession instance

engine = create_engine('postgresql://*****:*****@localhost/catalog')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()
示例#43
0
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT

from security import authenticate, identity
from resources.user import UserRegister
from resources.item import Item, ItemList
from resources.store import Store, StoreList

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///my_app.db'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # turn off auto tracking???
app.secret_key = 'second_server' # for JWT
api = Api(app)

@app.before_first_request
def create_tables():
    db.create_all()

jwt = JWT(app, authenticate, identity) # endpoint is /auth

api.add_resource(Item, '/item/<string:name>') # http://127.0.0.1/5000/item/yeojoy
api.add_resource(ItemList, '/items')
api.add_resource(Store, '/store/<string:name>')
api.add_resource(StoreList, '/stores')

api.add_resource(UserRegister, '/register')

if __name__ == '__main__': # if launch with python, this is the main!
    from db import db
    db.init_app(app)
示例#44
0
from flask import Flask, render_template, flash, request
from flask_wtf import FlaskForm as Form
from flask_wtf.csrf import CSRFProtect
from wtforms import HiddenField, TextField, SubmitField
from wtforms.validators import Required
from werkzeug import secure_filename
import os
import json


app = Flask(__name__)
app.secret_key = 'MRS'

csrf=CSRFProtect()
csrf.init_app(app)

class SampleForm(Form):
    dammy_hidden=HiddenField('dammy_hidden') # required to print csrf token into hidden field by FlaskForm
    name=TextField('Name', validators=[Required()]) # just a dammy
    submit= SubmitField('Submit')

def flash_errors(form):
    """Flashes form errors"""
    for field, errors in form.errors.items():
        for error in errors:
            flash(u"Error in the %s field - %s" % (
                getattr(form, field).label.text,
                error
            ), 'error')

# uploaded data processing server for filepond javascript
示例#45
0
文件: _03form.py 项目: lukehuang/all
from flask import Flask,render_template,request,flash

app=Flask(__name__)

@app.route('/',methods=['GET','POST'])
def html():
    if request.method=='POST':
        name=request.form.get('name')
        password=request.form.get('password')
        password2=request.form.get('password2')
        print(name,password,password2)
        if not all([name,password,password2]):
            flash(u'参数不完整')
        elif password2!=password:
            flash(u'密码不一致')
        else:
            flash(u'登录成功')
    return render_template('1.html')

app.secret_key='itheima'
app.config.from_pyfile('settings.ini')

if __name__ == '__main__':
    app.run(port=80)

示例#46
0
STATIC_TEMPLATE_LIB = pkg_resources.resource_filename("gradio", "frontend/")
STATIC_PATH_LIB = pkg_resources.resource_filename("gradio", "frontend/static")
VERSION_FILE = pkg_resources.resource_filename("gradio", "version.txt")
with open(VERSION_FILE) as version_file:
    GRADIO_STATIC_ROOT = "https://gradio.s3-us-west-2.amazonaws.com/" + \
        version_file.read().strip() + "/static/"

app = Flask(__name__,
            template_folder=STATIC_TEMPLATE_LIB,
            static_folder="",
            static_url_path="/none/")
CORS(app)
cache_buster = CacheBuster(
    config={'extensions': ['.js', '.css'], 'hash_size': 5})
cache_buster.init_app(app)
app.secret_key = os.getenv("GRADIO_KEY", "secret")
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.init_app(app)

# Hide Flask default message
cli = sys.modules['flask.cli']
cli.show_server_banner = lambda *x: None


class User:
    def __init__(self, id):
        self.is_authenticated = True
        self.is_active = True
        self.is_anonymous = False
        self.id = id
        con.commit()
        con.close()
        return render_template('success.html')

@app.route('/login',methods=['post','get'])
def login():    
    session.clear()
    if request.method=='GET':
        return render_template('login.html')
    con = _sqlite3.connect('database.db')
    cur = con.cursor()
    error=False
    email = request.form['email']
    password = request.form['password']
    user_data = cur.execute('SELECT * FROM LIST WHERE email=(?)',(email,))
    if password == user_data.fetchone()[1]:
        con.commit()
        con.close() 
        session['email']=email
        session['logged_in']=True
        return render_template('index.html',message='You have successfully logged in!')
    else:
        con.commit()
        return render_template('index.html',message='Incorrect password or user does not exist')

if __name__ == '__main__':
      app.secret_key='chala secret'  
      app.run(debug=True)
    

示例#48
0
from flask import Flask, render_template, redirect, request, session, flash
import re
app = Flask(__name__)
app.secret_key = 'key'

EMAIL_REGEX = re.compile(r'^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$')
PASS_REGEX = re.compile(r'^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,25}$')

@app.route('/')
def display_index():
    if not 'email' in session:
        session['email'] = ''
    if not 'first_name' in session:
        session['first_name'] = ''
    if not 'last_name' in session:
        session['last_name'] = ''
    if not 'pass1' in session:
        session['pass1'] = ''
    if not 'pass2' in session:
        session['pass2'] = ''

    return render_template('index.html')

@app.route('/form_submit', methods=['POST'])
def on_submit():


    if len(request.form['email']) < 5 or not EMAIL_REGEX.match(request.form['email']):
        flash('Please enter a valid email', 'error')
        return redirect('/')
    elif len(request.form['first']) < 1 or not request.form['first'].isalpha():
示例#49
0
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT

from security import authenticate, identify
from resources.user import UserRegister
from resources.item import Item, Items

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'juniper'
api = Api(app)

jwt = JWT(app, authenticate, identify)  #/auth

api.add_resource(Item, '/item/<string:name>')
api.add_resource(Items, '/items')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    from db import db
    db.init_app(app)
    app.run(port=5000, debug=True)
        n_neighbors = int(round(sqrt(len(X))))
        if verbose:
            print("Chose n_neighbors automatically as:", n_neighbors)

    knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors,
                                             algorithm=knn_algo,
                                             weights='distance')
    knn_clf.fit(X, y)

    if model_save_path != "":
        with open(model_save_path, 'wb') as f:
            pickle.dump(knn_clf, f)

    return render_template("upload.html", msg1="Data trained for " + id_folder)


@app.route('/changetask', methods=['POST'])
def changetask():
    return render_template("task.html")


@app.route('/logout', methods=['POST'])
def logout():
    return render_template("index.html",
                           title="Admin Login",
                           msg1="Logged out please login again")


if (__name__ == '__main__'):
    app.secret_key = 'secretkey'
    app.run(host="127.0.0.1", port=4555, debug=True)
示例#51
0
from flask import Flask, abort, session, redirect, url_for, request, render_template, json
from markupsafe import escape 

# Basically "name = __init___", but for web servers
app = Flask(__name__)

# The secret ingredient is... how we store session data.
app.secret_key = b'\xe1q\xf5\xd4\xa3=\xa8\xc0\x18\xf9\xb3G`\xe0"\xa2'

"""CAUTION: PREFERENCES ARE DELETED UPON SERVER SHUTDOWN"""
prefs_saved = {} 

# Main Page
@app.route('/', methods=['POST'])
def index():
    # Check that JSON was received
    if request.is_json == False:
        return "Bad Request", 400
    
    # "Log in" the user
    user = request.json['username'] 

    # "is Raw text input?"
    raw = False
    try:
        raw = request.json['raw']
    except Exception:
        raw = True

    # If raw, extract keyword updates
    if raw:
示例#52
0
    if request.method == 'POST':
        text_input = request.form['content'].lower()
        exclude = set(string.punctuation)
        text_input = ''.join(ch for ch in text_input if ch not in exclude)
        for ch in text_input:
            text_input_list.append(ch)

        if text_input != '' and text_input != session['text_input_prev']:
            session['text_input_prev'] = text_input
            print('loading')

            # synthesize speech from text
            print(datetime.datetime.now())
            output_filename = synthesize(text_input)
            # output_filename = synthesize(text_input, ttm_model, ssrn_model)
            session['audio_filename'] = output_filename
            # session['audio_filename'] = 'test_wav.wav'
            print(datetime.datetime.now())

    return render_template('index.html',
                           text_input=text_input,
                           text_input_list=text_input_list,
                           audio_filename=session['audio_filename'])


app.secret_key = 'SECRET KEY'

if __name__ == "__main__":
    app.config['SESSION_TYPE'] = 'filesystem'
    app.run(debug=True, use_reloader=False)
示例#53
0
        response = redirect(url_for('home'))
        response.headers['Content-Type'] = 'application/json'
        flash("successfully signout", "success")
        return response
    else:

        # if given token is invalid, unable to revoke token
        response = make_response(json.dumps('Failed to revoke token for user'),
                                 200)
        response.headers['Content-Type'] = 'application/json'
        return response


@app.route('/logout')
def logout():
    if 'email' in login_session:
        flash('you loggeed out')
        return gdisconnect()
    flash('You are already logout.')
    return redirect(url_for('login'))


@app.context_processor
def inject_all():
    category = session.query(HeadWear).all()
    return dict(mycategories=category)

if __name__ == '__main__':
    app.secret_key = "catalog@123"
    app.run(debug=True, host="localhost", port=5000)
示例#54
0
# librerías para la figura
#import matplotlib
#matplotlib.use('Agg')
#import matplotlib.pyplot as plt; plt.rcdefaults()
#import numpy as np
#import matplotlib.pyplot as plt

app = Flask(__name__)

# Database connection
app.config.from_json('config/config.json')
mongo = PyMongo(app)

# Session
app.secret_key = 'mysecretkey'


# Login
@app.route('/login', defaults={'error': 0})
@app.route('/login/<error>')
def login(error):

    if 'username' in session:
        return Index()
        #return 'logged as ' + session['username']

    return render_template('login.html', error=error)


# https://www.youtube.com/watch?v=vVx1737auSE
示例#55
0
"""Movie Ratings."""

from jinja2 import StrictUndefined

from flask import (Flask, render_template, redirect, request, flash, session)

from flask_debugtoolbar import DebugToolbarExtension

from model import User, Rating, Movie, connect_to_db, db


app = Flask(__name__)

# Required to use Flask sessions and the debug toolbar
app.secret_key = "ABC"

# Normally, if you use an undefined variable in Jinja2, it fails
# silently. This is horrible. Fix this so that, instead, it raises an
# error.
app.jinja_env.undefined = StrictUndefined


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


@app.route("/users")
def user_list():
    """Show list of users."""
示例#56
0
from flask import Flask, flash, get_flashed_messages

app = Flask(__name__)
app.debug = True
app.secret_key = 'abcdef'


@app.route('/get')
def get():
    data = get_flashed_messages()
    print(data)
    return 'hello world'


@app.route('/set')
def set():
    # 向某个地方设置一个值
    flash('访问一次就设置一次')
    return 'hello world'


if __name__ == '__main__':
    app.run()
示例#57
0
from flask import Flask, render_template, request, redirect, session
app = Flask(__name__)
app.secret_key = 'ThisIsSecret'  # you need to set a secret key for security purposes


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


@app.route('/users', methods=['POST'])
def create_user():
    print "Got Post Info"
    # notice how the key we are using to access the info corresponds with the names
    # of the inputs from our html form
    session['name'] = request.form['name']
    session['email'] = request.form['email']
    return redirect('/show')  # redirects back to the '/' route


@app.route('/show')
def show_user():
    return render_template('user.html',
                           name=session['name'],
                           email=session['email'])


app.run(debug=True)
示例#58
0
from store import store
from my_page import my_page
from message import message_python
from game_center import game_center
from admin import admin_class as ac
from flask_admin import Admin
from flask_sqlalchemy import SQLAlchemy
from flask_admin.contrib.sqla import ModelView
from flask_login import LoginManager, login_user, logout_user, UserMixin
from sql_info import mysql_info

mysql = mysql_info.info

app = Flask(__name__, template_folder='view', static_url_path='', static_folder='static')

app.secret_key = '시크릿_키_발급'

app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://'+mysql['user']+':'+mysql['password']+'@'+mysql['host']+'/'+mysql['db']
app.config['SECRET_KEY'] = 'sfkjlrgnvrefiovnoi'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# set flask_admin 

db = SQLAlchemy(app)

login = LoginManager(app)

class member(db.Model, UserMixin) :
    
    mem_no = db.Column(db.Integer, primary_key = True)
    mem_id = db.Column(db.String(30))
示例#59
0
from flask import Flask, redirect, request, render_template, session, flash
import random

app = Flask(__name__)
app.secret_key = "SecretGarden"
@app.route('/')
def index():
    session['number'] = random.randrange(0,101)
    session['guess'] = 'guess'
    print 'the number is '
    print session['number']
    return render_template('index.html')
@app.route('/guess', methods=['POST'])
def guess():
    session['guess'] = int(request.form['guess'])
    print 'guess: '
    print session['guess']
    print 'the number is '
    print session['number']
    #validate guess
    if session['guess'] < 1:
        flash('Please guess a number higher than 0.')
    elif session['guess'] > 100:
        flash('Please guess a number lower than 100')

    if '_flashes' in session:
        return redirect('/')
    return render_template('index.html')
    #determine whether guess is match, too low, or too high
    # if int(session['guess']) < session['number']:
    #     return render_template('tooLow.html')
示例#60
-3
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