def create_app(self):
     """ Set up an app object with testing config """
     app = Flask(__name__)
     app.config.from_object("config")
     db.init_app(app)
     app.db = db
     return app
Beispiel #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
Beispiel #3
0
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)

    CsrfProtect(app)

    # Register extensions
    for ext in all_extensions:
        print(ext)
        ext.init_app(app)
    # Add DB resource to app object for use later.
    app.db = db

    # Creates DB if it doesn't exist. Comment out to avoid checking every time.
    if not os.path.exists(app.config['DBFILE_PATH']):
        print("Need to create {} at {}".format(app.config['DB_NAME'],
                                               app.config['APP_DIR']))
        @app.before_first_request
        def initialize_database():
            print("Creating {} at {}".format(app.config['DB_NAME'],
                                             app.config['APP_DIR']))
            db.create_all()

    # Register blueprints
    app.register_blueprint(pages.blueprint)
    pages.blueprint.extra_init(app)
    app.register_blueprint(user.views.blueprint)

    app.logger.setLevel(logging.WARNING)

    register_errorhandlers(app)

    return app
Beispiel #4
0
def create_app(config_obj):
    app = Flask(__name__)
    app.config.from_object(config_obj)

    app.db = SQLAlchemy(app)
    app.db.register_base(models.Base)

    login_manager = LoginManager(app)

    # Register a user loader
    @login_manager.user_loader
    def load_user(user_id):
        return app.db.session.query(User).get(user_id)

    # Flask Migrate
    Migrate(app, app.db)

    # Endpoints
    add_healthcheck(app)

    # App Version
    app.version = get_release()


    # Trello API
    app.trello = TrelloClient(api_key=app.config.get('TRELLO_APP_KEY'))

    # Register Views
    IndexView.register(app, route_base='/')


    return app
Beispiel #5
0
def init_app(db_name=None):
    """Initialize the app.

    Because the database name has to be set before the app inits,
    we allow it to be passed in outside of configs, because we can't
    set it on app.config['DATABASE'] before we actually have an app.

    This is mainly for testing, because it could be set via env vars,
    but we don't want the test to override any env vars that are already set.
    """

    # create a Flask app, force SSL when debug is False
    app = Flask(__name__, static_folder='./ui/static')
    app.config.from_pyfile('config.py')

    # load custom config file
    custom_config = app.config['CUSTOM_CONFIG_PATH']
    if os.environ.get(custom_config) is not None:
        app.config.from_envvar(custom_config)

    # setup
    app.db = db.connect(db_name)
    setup_auth(app)
    SSLify(app, subdomains=True)

    # register blueprints
    app.register_blueprint(api, url_prefix='/api')
    app.register_blueprint(auth)
    app.register_blueprint(ui)

    return app
Beispiel #6
0
def create_app():
    app = Flask(__name__)
    api = Api(app)


    # Mongo DB Settings
    app.config['MONGODB_DATABASE'] = 'yoda'


    # add api endpoint basic code evaluation
    api.add_resource(ycode.TestCode, '/')

    # add api endpoint testcase list view and detail view of testcase based on Object ID
    api.add_resource(ycode.GetTestCase, '/testcases', '/testcases/<string:testcase_id>')

    # add api endpoint to create a testcase
    api.add_resource(ycode.NewTestCase, '/testcase/new' )


    # TODO:  Check if MongoDB is up and running
    app.db = MongoKit (app)

    # Register MongoDB documents
    app.db.register([RootDocumentModel])
    app.db.register([CodeDocumentModel])
    app.db.register([CodeSetDocumentModel])
    app.db.register([TestCaseDocumentModel])


    @app.errorhandler(500)
    def internal_error(exception):
        return "Some internal error has taken place.  Alert somebody!"

    return app
Beispiel #7
0
def create_app():
    """ Initializing the app """
    app = Flask(__name__)
    app.config.update(Config.__dict__)

    # Set up extensions
    db.init_app(app)
    app.db = db
    Migrate(app, db)
    CORS(app) # TODO: Don't allow all in production

    assets.init_app(app)
    login_manager.init_app(app)

    # Install views
    from views.oauth import bp as oauth_bp
    app.register_blueprint(oauth_bp)

    # Install API
    from views import account
    from views import authorization
    api.init_app(app)

    # Install models
    from models.account import User

    return app
Beispiel #8
0
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
Beispiel #9
0
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
    app.jinja_env.filters['jsonencode'] = jsonencode
    app.jinja_env.globals['newrelic_head'] = newrelic_head
    app.jinja_env.globals['newrelic_foot'] = newrelic_foot

    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

    app.wsgi_app = FixGunicorn(app.wsgi_app)

    return app
Beispiel #10
0
def create_app(config='CTFd.config'):
    app = Flask("CTFd")
    with app.app_context():
        app.config.from_object(config)

        from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking

        db.init_app(app)
        db.create_all()

        app.db = db

        global mail
        mail = Mail(app)

        Session(app)

        from CTFd.views import views
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.utils import init_utils, init_errors, init_logs

        init_utils(app)
        init_errors(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(admin)

        return app
Beispiel #11
0
def setup():
    """Setup function for tests."""
    # global variable shouldn't be used but is quite useful here
    # pylint: disable=W0603
    global TEMP_DIR
    TEMP_DIR = mkdtemp()
    if not os.path.exists(FAKE_DIR):
        os.mkdir(FAKE_DIR)
        Git(os.path.join(FAKE_DIR, 'documents.git')).init()
    app = Flask(
        __name__,
        static_folder=os.path.join(PATH, 'static'),
        template_folder=os.path.join(PATH, 'templates'))
    app.config.from_object(config)
    app.db = SQLAlchemy(app)
    nuts = application.Koztumize(app)
    application.app = app
    application.nuts = nuts
    app.config['MODELS'] = os.path.join(TEMP_DIR, 'models')
    git = Git(app.config['MODELS'])
    git.init()
    git.remote('add', '-t', 'models', 'origin', app.config['GIT_REMOTE'])
    git.pull()
    git.checkout('models')
    execute_sql(app, 'db.sql')
    import koztumize.routes
    import koztumize.tests.document
Beispiel #12
0
def create_app(config_dict={}):
    global env, config

    # Set up scruffy environment
    env = Environment(
        dir=Directory('~/.flexo', create=False,
            config=ConfigFile('config', defaults=File('default.conf', parent=PackageDirectory()), apply_env=True)
        )
    )
    config = env.config

    # Setup flask app
    app = Flask(__name__, static_url_path='/static')
    app.secret_key = config.secret
    app.config["MONGODB_SETTINGS"] = {'host': config.db_uri}
    app.config.update(config_dict)
    app.register_blueprint(main)

    # Setup database
    app.db = MongoEngine(app)

    # Setup login_manager
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    # Setup API
    api = Api(app)
    api.add_resource(MetricAPI, '/api/metric')
    api.add_resource(ExerciseAPI, '/api/exercise')

    # Make sure there's at least an admin user
    if len(User.objects) == 0:
        User(name='admin', password='admin').save()

    return app
Beispiel #13
0
def create_app():   # We could pass a config object here
    app = Flask(__name__)
    app.debug = os.environ.get('TIMERBOARD_PRODUCTION', True)
    app.config.from_envvar("TIMERBOARD_SETTINGS")
    with open(os.environ["TIMERBOARD_SETTINGS"]) as fh:
        app.myconfig = json.loads(fh.read())
    app.config["SQLALCHEMY_DATABASE_URI"] = app.myconfig["SQLALCHEMY_DATABASE_URI"]
    # Register template filters here
    # app.add_template_filter(some_method)

    #app.config.from_object(config)
    #app.config.from_pyfile(config_filename)

    app.secret_key = os.urandom(24)
    assets.init_app(app)
    login_manager.init_app(app)

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

    from users.views import mod as users_blueprint
    from assets import mod as assets_blueprint
    from login import mod as login_blueprint
    app.register_blueprint(users_blueprint)
    app.register_blueprint(assets_blueprint)
    app.register_blueprint(login_blueprint)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        app.db.session.remove()

    return app
Beispiel #14
0
def create_app():
    application = Flask(__name__)
    application.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
    # application.config['BABEL_DEFAULT_LOCALE'] = 'ru-ru'
    application.config['SECRET_KEY'] = SECRET_KEY
    application.permanent_session_lifetime = timedelta(minutes=30)

    Triangle(application)
    assets.init_app(application)
    api.init_app(application)
    api.application = application
    db.init_app(application)
    admin.init_app(application)
    login_manager.init_app(application)
    application.db = db
    application.api = api

    babel = Babel(application)
    @babel.localeselector
    def get_locale():
        return request.accept_languages.best_match(["ru"])

    init_logging(application)

    return application
Beispiel #15
0
def create_app(config, app=None):
    class Result(object):
        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(self, k, v)

    if app is None:
        app = Flask(__name__)
        app.config.from_object(config)

    app.collect = Collect(app)
    app.celery = make_celery(app)
    app.db = MongoEngine(app)
    app.user_datastore = MongoEngineUserDatastore(
        app.db,
        User,
        Role,
    )
    app.security = Security(app, app.user_datastore)
    create_api(app)
    app.socketio = SocketIO(app, logger=True)

    werkzeug = os.environ.get('WERKZEUG_RUN_MAIN', 'true')
    if werkzeug == 'true':
        app.socket_thread = SocketThread(
            app.socketio,
            app.config['REDIS_HOST']
        )
        app.socket_thread.start()
    return app
Beispiel #16
0
def create_app(config=None):
    log.debug('creating app with config: %s', config)

    import models
    from evesso.auth import auth, login_manager
    from evesso.chat import socketio
    import evesso.default_config 

    app = Flask(__name__, instance_relative_config=True,
                static_folder='../static/build/app/', static_url_path='/static')
    app.config.from_object(evesso.default_config)
    #if config != '': app.config.from_pyfile(config)
    setup_logging(app)

    db.init_app(app)
    app.db = db
    db.scoped_session = scoped_session

    socketio.init_app(app)
    app.socketio = socketio

    oauth.init_app(app)
    app.eve_oauth = eve_oauth

    login_manager.init_app(app)
    app.login_manager = login_manager

    app.register_blueprint(auth)

    return app
Beispiel #17
0
def create_app(config, app=None):
    class Result(object):
        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(self, k, v)

    if app is None:
        app = Flask(__name__)
        app.config.from_object(config)

    app.collect = Collect(app)
    db.init_app(app)
    app.db = db

    app.blueprint = Blueprint(
        'app',
        __name__,
        template_folder='templates',
        static_folder='static',
        static_url_path='/static/app',
    )
    app.register_blueprint(app.blueprint)

    from .models.auth import User, Role, UserRoles
    app.user_datastore = PeeweeUserDatastore(
        app.db,
        User,
        Role,
        UserRoles,
    )
    app.security = Security(app, app.user_datastore)
    app.jwt = JWTManager(app)
    create_api(app)

    return app
Beispiel #18
0
def create_app(cmdline=False, test_config=None):
    blueprints = get_blueprints()

    app = Flask(__name__)
    if test_config:
        app.config.update(**test_config)
    else:
        app.config.from_envvar('RELENGAPI_SETTINGS')

    # add the necessary components to the app
    app.db = db.make_db(app)
    app.celery = celery.make_celery(app)
    relengapi.principal.init_app(app)
    relengapi.login_manager.init_app(app)
    api.init_app(app)

    for name, bp in blueprints:
        if cmdline:
            logger.info(" * registering blueprint %s", name)
        app.register_blueprint(bp, url_prefix='/%s' % name)

    # set up a random session key if none is specified
    if not app.config.get('SECRET_KEY'):
        logger.warning(" * setting per-process session key - sessions will be reset on "
                       "process restart")
        app.secret_key = os.urandom(24)

    @app.before_request
    def add_db():
        g.db = app.db

    @app.route('/')
    def root():
        # render all of the blueprints' templates first
        bp_widgets = []
        for bp in app.blueprints.itervalues():
            bp_widgets.extend(bp.root_widget_templates or [])
        bp_widgets.sort()
        bp_widgets = [tpl for (_, tpl, condition) in bp_widgets if not condition or condition()]
        return render_template('root.html', bp_widgets=bp_widgets)

    @app.route('/versions')
    @api.apimethod()
    def versions():
        dists = {}
        for dist in pkg_resources.WorkingSet():
            dists[dist.key] = {
                'project_name': dist.project_name,
                'version': dist.version,
            }
        blueprints = {}
        for ep in pkg_resources.iter_entry_points('relengapi_blueprints'):
            blueprints[ep.name] = {
                'distribution': ep.dist.key,
                'version': ep.dist.version,
            }
        return dict(distributions=dists, blueprints=blueprints)

    return app
Beispiel #19
0
def create_app():
    app = Flask(__name__)

    app.register_blueprint(hashes, url_prefix="/hash")
    app = error_routes(app)

    app.db = Hash()

    return app
Beispiel #20
0
def create_app(__name__=__name__):
    app = Flask(__name__)
    try:
        app.config.from_pyfile(CONFIG_FILEPATH)
    except IOError:
        pass
    auto_register_modules(app)
    app.db = SQLAlchemy(app)
    return app
Beispiel #21
0
def create_app(set_config=set_config):
    app = Flask(__name__)
    set_config(app)

    db.init_app(app)
    app.db = db

    register_uris(app)

    return app
Beispiel #22
0
def create_app(package_name):
    app = Flask(package_name)

    from project.database import db_init
    app.db = db_init()

    from project.routes import routes_init
    routes_init(app)

    return app
Beispiel #23
0
def create_app(set_config=set_config):
    app = Flask(__name__)
    set_config(app)

    db.init_app(app)
    app.db = db

    register_uris(app)

    app.response_class = ApiResponse

    return app
Beispiel #24
0
def app(request):
    app = Flask(__name__)
    app.client = app.test_client()
    app.db = connect(**{'db': db_name()})

    from project.routes import routes_init
    routes_init(app)

    def teardown():
        app.db.drop_database(db_name())

    request.addfinalizer(teardown)
    return app
Beispiel #25
0
def create_app(config='CTFd.config'):
    app = Flask("CTFd")

    with app.app_context():
        app.config.from_object(config)

        from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking, mysql

        app.config['MYSQL_DATABASE_USER'] = 'root'
        app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
        app.config['MYSQL_DATABASE_DB'] = 'EmpData'
        app.config['MYSQL_DATABASE_HOST'] = 'localhost'
        mysql.init_app(app)

        cursor = mysql.connection.cursor()
        

#        cursor.execute('CREATE DATABASE  IF NOT EXISTS info_sec;')
#        cursor.execute('USE info_sec;')        
#        cursor.execute('CREATE TABLE IF NOT EXISTS info_sec.security_table \
#        (\
#        username varchar(255),\
#        pass char(255));')



        db.init_app(app)
        db.create_all()

        app.db = db

        #Session(app)

        from CTFd.views import views
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.utils import init_utils, init_errors, init_logs

        init_utils(app)
        init_errors(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(admin)

        return app
Beispiel #26
0
def get_app():
    app = Flask('breezeminder')

    settings_file = os.environ.get('BREEZEMINDER_SETTINGS', 'breezeminder.settings.local')
    app.config.from_object(settings_file)
    app.config['BREEZEMINDER_ENV'] = settings_file.split('.')[-1].upper()
    app.config['SHOW_ADS'] = app.config.get('ADSENSE_CLIENT', None) is not None

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

    app.db = PortAwareMongoEngine(app)

    logger.configure_logging(app)
    return app
Beispiel #27
0
    def create_app(self, config):
        if self.app:
            return self.app

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

        db.init_app(app)
        db.create_all(app=app)
        app.db = db

        self.register_blueprint(app)
        self.app = app

        return app
Beispiel #28
0
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 = MongoEngine(app)

    app.jinja_env.add_extension('kardboard.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 app.config.get('COMPILE_TEMPLATES', False):
        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)

    app.wsgi_app = FixGunicorn(app.wsgi_app)

    statsd_conf = app.config.get('STATSD_CONF', {})

    statsd_connection = statsd.Connection(
        host=statsd_conf.get('host', '127.0.0.1'),
        port=statsd_conf.get('port', 8125),
        sample_rate=statsd_conf.get('sample_rate', 1),
    )

    machine_name = socket.getfqdn().split('.')[0]
    environment_name = app.config.get('ENV_MAPPING', {}).get(machine_name, 'default')
    prefix_name = '%s.%s.kardboard' % (environment_name, machine_name)
    app.statsd = statsd.Client(prefix_name, statsd_connection)

    if SENTRY_SUPPORT and 'SENTRY_DSN' in app.config.keys():
        sentry = Sentry(app)
        sentry

    return app
Beispiel #29
0
def create_app(app_name, config):
	
	app = Flask(app_name)
	app.config.from_object(config)

	app.db = SQLAlchemy(app)

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

	app.bcrypt = Bcrypt(app)

	app.api = Api(app, prefix='/api/v1')

	app.api_registry = []

	return app
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config.get(config_name, "default"))

    # Create database with the config settings
    app.db = create_db(app)

    from .api import api1_0 as api1_0_blueprint

    app.register_blueprint(api1_0_blueprint, url_prefix="/api/v1_0")

    from .api import login_blueprint

    app.register_blueprint(login_blueprint, url_prefix="")

    return app