Beispiel #1
0
def create_app(config_file):
    # load config
    app.config.from_pyfile(config_file)

    from views.backgrounds import load_backgrounds
    load_backgrounds(app)

    # setup db
    from database import db
    db.init_app(app)

    # setup login
    login_manager.init_app(app)

    # login_manager.setup_app(app)

    from monkey.views import index_view, login_view

    for bp in [login_view, index_view]:
        app.register_blueprint(bp)

    # init all
    with app.app_context():
        db.create_all()
        import api

        api.start_api([UserModel])
        UserModel.initialize()

    return app
Beispiel #2
0
def create_app():
    app = Flask(__name__)
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////Users/olivergoodman/Documents/github/app-blueprint/my_app/personal.db"
    db.init_app(app)    
    app.register_blueprint(hello, url_prefix='')
    return app 
Beispiel #3
0
def create_app(app):
    # config app
    app.config.from_object(os.environ["APP_SETTINGS"])

    # initiate extensions
    db.init_app(app)
    ma.init_app(app)
    celery.init_app(app)
    jack_apns.init_app(app)

    # declare models
    import models

    # init app
    with app.app_context():
        # db.reflect()
        # db.drop_all()
        db.create_all()
        app.register_blueprint(auth, url_prefix="/auth")
        app.register_blueprint(user, url_prefix="/user")
        app.register_blueprint(group, url_prefix="/group")
        app.register_blueprint(post, url_prefix="/post")
        app.register_blueprint(comment, url_prefix="/comment")
        app.register_blueprint(invite, url_prefix="/invite")
        app.register_blueprint(generic, url_prefix="/generic")
        app.register_blueprint(rule, url_prefix="/rule")
Beispiel #4
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # use gzip compress response
    compress.init_app(app)

    # init database
    db.init_app(app)

    # init static resource
    # assets.init_app(app)
    # bundles = {
    #     'fullpage_css': Bundle(
    #         'css/base.css',
    #         output='gen/base.css',
    #         filters='cssmin'),

    #     'fullpage_js': Bundle(
    #         'js/base.js',
    #         output='gen/base.js',
    #         filters='jsmin'),
    # }
    # assets.register(bundles)

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    #solve the CORS problem(cross domain request)
    CORS(app, resources={r'/api/*': {"origins": "*"}})

    return app    
Beispiel #5
0
def create_app(config):
	app = Flask(__name__)
	app.config.from_object(config)
	# 載入 db model
	from db.common import *
	from db.user import *
	from db.store import *
	from db.discount import *
	db.init_app(app)

	# # 安裝 JSGlue
	# jsglue = JSGlue()
	# jsglue.init_app(app)

	# # Session Secret Key
	# app.secret_key = os.urandom(24).encode('hex')
	# print app.secret_key

	# # 擴充 url map
	# app.url_map.converters['regex'] = RegexConverter
	# # # 安裝 Session 強化擴充
	# # sess = Session()
	# # sess.init_app(app)
	# # 載入 view
	# from app.web.client import client
	# from app.web.deposit import deposit
	# from app.web.donation import donation
	# # 註冊藍圖
	# app.register_blueprint(client)
	# app.register_blueprint(deposit)
	# app.register_blueprint(donation)

	return app
Beispiel #6
0
def create_app(config):
    app = Flask(__name__)
    app.config.update(default_config)
    app.config.update(config)
    app.register_blueprint(api, url_prefix='/1.0')

    db.app = app
    db.init_app(app)

    @app.before_request
    def load_current_user():
        g.user = (User.query.filter_by(email=session['email']).first()
                  if 'email' in session else None)

    @app.route('/', methods=['GET'])
    def main():
        """Default landing page."""
        return render_template('index.html', authenticated=bool(g.user))

    @app.route('/authenticate', methods=['POST'])
    def set_email():
        """Verify via Persona.

        Upon success, create the user if it doesn't already exist and set the
        email for the user's session.
        """
        data = browserid.verify(request.form['assertion'], '%s://%s' % (
            app.config['PREFERRED_URL_SCHEME'], app.config['SERVER_NAME']))
        email = data['email']

        # Create user record.
        try:
            user = User.query.filter(User.email==email).one()
        except NoResultFound:
            user = User(email=email)
            db.session.add(user)
            db.session.commit()
            # Add self as contact.
            user.contacts.append(user)
            db.session.commit()

        session['email'] = user.email
        return jsonify({'message': 'okay'})

    @app.route('/logout', methods=['GET', 'POST'])
    def logout():
        """Log the user out."""
        session.pop('email', None)
        return jsonify({'message': 'okay'})

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('404.html')

    @app.errorhandler(500)
    def something_broke(error):
        return render_template('500.html')

    return app
Beispiel #7
0
def create_app(debug=False):
    def load_env(env_name, conf_name = None):
        """Load the specified key to config from env if exists"""
        if conf_name is None:
            conf_name = env_name
        
        app.config[conf_name] = os.environ.get(env_name, app.config.get(conf_name))


    app = Flask(__name__)
    app.debug = debug

    app.config.from_object(os.environ.get('APP_CONFIG', 'config.DevelopmentConfig'))

    load_env('DATABASE_URL', 'SQLALCHEMY_DATABASE_URI')
    load_env('GCM_TOKEN')

    app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')

    # Database creation
    db.init_app(app)
    with app.app_context():
        db.create_all()

    #
    # Create the services
    #
    gcm = GCM(app.config['GCM_TOKEN'])
    authService = AuthenticationService(db)
    messageService = GCMMessengerService(db, gcm)
    locatorService = LocatorService(db, messageService)
    relayService = RelayService(db, messageService)

    # Easy method to get currentuser
    def current_user():
        token = request.headers.get('Authorization')
        return authService.getUserFromAccessToken(token)

    #
    # Blueprints
    # 
    authcheckBlueprint = authcheck_blueprint(authService, locatorService)
    locatorBlueprint = locator_blueprint(db, locatorService, current_user)
    relayBlueprint = relay_blueprint(db, relayService, current_user)
    refBlueprint = refactor_blueprint(db, authService, app, current_user) # Needs app for now as it has the apimanager...
    app.register_blueprint(locatorBlueprint)
    app.register_blueprint(relayBlueprint)
    app.register_blueprint(authcheckBlueprint)
    app.register_blueprint(refBlueprint)
    
    # Create admin interface
    admin.init_app(app, messageService, locatorService)

    # I'm a teapot.
    @app.route("/")
    def index():
        abort(418)

    return app
def create_app(config_filename = 'cf'):
    app = Flask(__name__)
    app.config.from_object(__name__)
    app.config.from_pyfile('config.py', silent=False)
    db.init_app(app)
    # app.register_blueprint(bp)

    return app
Beispiel #9
0
def create_app():
    '''Initialize Flask and SQLAlchemy contexts and register blueprints'''
    app = Flask(__name__)
    db.init_app(app)

    app.register_blueprint(root_app)
    app.register_blueprint(api_app)
    return app
Beispiel #10
0
def configure_database(app):
    """
    Database configuration should be set here
    """
    # uncomment for sqlalchemy support
    from database import db
    db.app = app
    db.init_app(app)
Beispiel #11
0
def create_app():
    # set the project root directory as the static folder, you can set others.
    config_path = os.environ.get("APP_CONFIG_FILE", "config.py")
    print "loading config from ", config_path
    app.config.from_pyfile(config_path)
    with app.app_context():
        db.init_app(app)
        create_model_tables()
    return app
Beispiel #12
0
def create_app():
	app = Flask(__name__)
	app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/user_management.db'
	db.init_app(app)
	db.app = app
	from models import User, Group
	db.create_all()
	migrate.init_app(app,db)
	return app
    def setUp(self):
        app.config.from_object('config.TestingConfig')
        self.client = app.test_client()

        db.init_app(app)
        with app.app_context():
            db.create_all()
            user_datastore.create_user(email='test', password=encrypt_password('test'))
            db.session.commit()
Beispiel #14
0
def test_db(flask_app):
    uuid = str(uuid4())
    flask_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test-{}.db'.format(uuid)

    db.init_app(flask_app)
    with flask_app.app_context():
        db.create_all()

    return db
Beispiel #15
0
def create_app(config=None):
    # init flask app
    app = Flask(__name__)
    app.config.from_pyfile('config.cfg', silent=True)
    if config is not None:
        app.config.from_pyfile(config, silent=True)
    db.init_app(app)
    app.register_blueprint(classes.bp, url_prefix = '/classes')
    return app
Beispiel #16
0
def configure_database(app):
    """
    Database configuration should be set here
    """
    from database import db
    db.app = app
    db.init_app(app)

    app.db = db
    return app
def create_app():
    app = Flask(__name__)

    from database import db
    db.init_app(app)

    app.register_blueprint(HelloRouter.hello_router)
    app.register_blueprint(GoodByeRouter.goodbye_router)

    return app
Beispiel #18
0
def configure_database(app):
    """
    Database configuration should be set here
    """
    from database import db
    from flask_migrate import Migrate

    db.app = app
    db.init_app(app)
    Migrate(app, db)
Beispiel #19
0
def create_app(workdir):
    app = flask.Flask(__name__)
    db.init_app(app)
    oid.init_app(app)

    app.register_blueprint(frontend)

    configure_app(app, workdir)

    return app
Beispiel #20
0
def init_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')
    db.init_app(app)
    db.app = app
    app.debug = app.config['DEBUG']

    init_logger(app)
    init_views(app)

    return app
Beispiel #21
0
def create_app(object_name, env="development"):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. appname.settings.ProdConfig

        env: The name of the current environment, e.g. prod or dev
    """

    app = Flask(__name__)

    app.config.from_object(object_name)
    app.config['ENV'] = env

    #init the cache
    cache.init_app(app)

    #init SQLAlchemy
    db.init_app(app)

    # Initialize Flask-Babel
    babel = Babel(app)                              
    
    # Initialize Flask-Mail
    mail = Mail(app)       

    # Initialize Flask-Migrate
    migrate = Migrate(app,db)
                         
    @babel.localeselector
    def get_locale():
        translations = [str(translation) for translation in babel.list_translations()]
        return request.accept_languages.best_match(translations)
    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,  Users)       # Select database adapter
    user_manager = UserManager(db_adapter, 
                               app,
                               register_form = IceRegisterForm)     # Init Flask-User and bind to app
    # register blueprints
    from controllers.main import main
    from controllers.customer import customer
    from controllers.email import email
    from controllers.schedule import schedule
    from controllers.kiosk import kiosk
    app.register_blueprint(main)
    app.register_blueprint(customer)
    app.register_blueprint(email)
    app.register_blueprint(schedule)
    app.register_blueprint(kiosk)

    return app
Beispiel #22
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    db.init_app(app)
    csrf.init_app(app)
    crypt.init_app(app)
    login_manager.init_app(app)
    app.register_blueprint(user_blueprint)
    app.register_blueprint(list_blueprint,url_prefix='/lists')
    app.register_blueprint(item_blueprint,url_prefix='/items')

    return app
Beispiel #23
0
def init_app(config_file='config.py', is_register_api=True, is_register_view=True):
    app = Flask(__name__)
    app.config.from_pyfile(config_file)
    app.debug = app.config.get('DEBUG', True)

    db.app = app;
    db.init_app(app)

    if is_register_api:
        register_api(app)

    return app
def create_app(config):
    """
    Given a configuration object, create a WSGI(Flask) app
    See `APP_CONFIG` in ../config.py for example configuration.
    """
    app = Flask(__name__)
    app.config.update(config)
    register_blueprints(app)
    db.init_app(app)
    with app.app_context():
        db.create_all()
    return app
Beispiel #25
0
def create_app():
    app = Flask(__name__)
    # app.config['DEBUG'] = True
    #
    # app.config['SQLALCHEMY_DATABASE_URI'] =  "sqlite:///" +__curdir__ + "/LP.db"

    app.config.from_pyfile('app.cfg')

    db.init_app(app)

    from ship import ship_bp
    app.register_blueprint(ship_bp)
    return app
Beispiel #26
0
def main(run_folders, users_file):
    db.init_app(app)
    logging.basicConfig(filename = 'NIPT_database_log', level=logging.DEBUG)
    db.create_all()
    NDBS = NiptDBSetup(db)
    NDBS.set_users(users_file)

    for folder in run_folders:
        BM = BatchMaker(db)
        BM.get_run_folder_info(folder)
        if BM.batch_id:
            BM.update_nipt_db(folder)
        else:
            logging.warning("Could not add to database from resultfile: %s" % path)
Beispiel #27
0
def main(flowcell_ids, users_file):
    db.init_app(app)
    logging.basicConfig(filename = 'NIPT_database_log', level=logging.DEBUG)
    db.create_all()
    NDBS = NiptDBSetup(db)
    NDBS.set_users(users_file)

    for flowcell_id in flowcell_ids:
        BM = BatchMaker(db)
        BM.parse_path(flowcell_id)
        BM.get_run_folder_info()
        if BM.batch_id:
            BM.update_nipt_db()
        else:
            logging.warning("Could not add to database from run: %s" % flowcell_id)
Beispiel #28
0
def configure_database(app):
	"Database configuration should be set here"
	# uncomment for sqlalchemy support
	from database import db
	db.app = app
	db.init_app(app)

	login_manager = LoginManager()
	login_manager.setup_app(app) 
	@login_manager.user_loader
	def load_user(userid):
		user = User.query.get(userid)
		if user:
			return FLUserWrapper(user)
		else:
			return None
		pass
Beispiel #29
0
def create_app(config_override: Mapping = None) -> Flask:
    """Create the flask app for the debug server.

    Parameters:
        config_override:
            Dict containing custom configuration to apply after loading the
            normal config. Useful for testing.
    """
    config_override = {} if config_override is None else config_override
    # TODO: Rename app, no longer used only for debugging
    app = Flask('stuffrdebugserver',
                instance_relative_config=True,
                static_url_path='',
                template_folder='static')
    app.config.from_object('config.default')
    app.config.from_envvar('STUFFR_SETTINGS')
    app.config.from_mapping(config_override)
    app.json_encoder = StuffrJSONEncoder
    logger.set_logger(app.logger)

    db.init_app(app)
    security = Security(app, user_store, confirm_register_form=StuffrRegisterForm)
    security.unauthorized_handler(api_unauthenticated_handler)
    Mail(app)

    # In debug mode Swagger documentation is served at root
    if not app.config['DEBUG']:
        def api_root_view():
            """Provide a link to API documentation if root accessed."""
            return error_response(
                'TODO: Link to documentation here', HTTPStatus.NOT_FOUND)
        blueprint_api.add_url_rule('/', 'apiindex', api_root_view)

    app.register_blueprint(blueprint_simple, url_prefix='/simple')
    app.register_blueprint(blueprint_api, url_prefix='/api')

    def default404(e):
        """Default handler for 404."""
        # TODO: Conditional JSON/HTML response (for simple mode)
        return error_response(e.description, HTTPStatus.NOT_FOUND)
    app.register_error_handler(HTTPStatus.NOT_FOUND, default404)

    # TODO: Make friendlier error message (40x or 50x?)
    app.add_url_rule('/', 'index', lambda: "You probably shouldn't be here")

    return app
Beispiel #30
0
def create_app():
	app = Flask(__name__)
	app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
	app.config['SQLALCHEMY_ECHO'] = False
	app.config['DEBUG'] = True
	app.secret_key = 'DEVELOPMENT KEY CHANGE ME'

	# register all blueprints here
	#app.register_blueprint(examplemodule.bp)
	app.register_blueprint(core.bp)

	# start up sqlalchemny
	db.init_app(app)

	configure_login(app)
	configure_admin(app)

	return app
Beispiel #31
0
def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
Beispiel #32
0
api_instance.add_namespace(endpoint_api, path='/endpoint')
api_instance.init_app(app)  # Initialize the api

TaskBase = celery.Task  # Fiddle with celery because Flask needs to be able to work with celery, and without this bit celery doesn't have the correct app context.


class ContextTask(TaskBase):
    abstract = True

    def __call__(self, *args, **kwargs):
        with app.app_context():
            return TaskBase.__call__(self, *args, **kwargs)


celery.Task = ContextTask

# Set up database
db.init_app(app)  # Initialize the database with the app
print("Resetting the database")
db.drop_all(
    app=app)  # Drop the table here, so we have a fresh start every time.
db.create_all(
    app=app
)  # If the database table doesn't already exist, then create it here.

# Setup cache
cache.init_app(app)

if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True, port=80)
Beispiel #33
0
def create_app():
    flask_app = Flask(__name__)
    configure_app(flask_app)
    with flask_app.app_context():
        db.init_app(flask_app)
    return flask_app
Beispiel #34
0
from flask_sqlalchemy import SQLAlchemy

from database import db
from database.operations import save_to


print ("loading data ...")

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///base.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']  = False



db.init_app(app)
app.app_context().push()
db.create_all()



subunidades = get_subunidades()


start = 0
for sub in subunidades[start:]: 
    #s = Subunidade (sub)
    #save_to(s, db)
    docentes = get_docentes(sub["codigo"])
    print (start, sub["codigo"])
    start = start + 1
Beispiel #35
0
def register_database(app):
    """Register database."""
    db.init_app(app)
Beispiel #36
0
from flask import Flask
from routes.fileRoutes import fileApi
from database import db
import logging

application = Flask(__name__)

application.register_blueprint(
    fileApi, url_prefix="/file"
)  ### Registers a blueprint. All /file  requests will be routed to  fileApi

application.config[
    'SQLALCHEMY_DATABASE_URI'] = "sqlite:////tmp/fileStores.db"  ## fileStore is SQLITE DB name

application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(application)

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

##### Configure Logging ########
if __name__ != '__main__':
    gunicorn_logger = logging.getLogger('gunicorn.error')
    application.logger.handlers = gunicorn_logger.handlers
    application.logger.setLevel(gunicorn_logger.level)

# Only for development server . will never executes when ran via gunicorn #
if __name__ == "__main__":
    application.run()
Beispiel #37
0
def init_app(app):
    db.init_app(app)
    migrate.init_app(app, db)
    api.init_app(app)
Beispiel #38
0
import flask as f
import flask_openid
from database import db as d
import database
import bcrypt
import re
import steam.webapi
import functools
# noinspection PyUnresolvedReferences
import configuration

app = f.Flask(__name__)
app.config.from_object("configuration.Config")
d.init_app(app)
steam_oid = flask_openid.OpenID(app)
steam_api = steam.WebAPI(app.config["STEAM_API_KEY"])


@app.after_request
def after_every_request(response):
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response


@app.route("/api/v1/user/register", methods=["POST"])
def api_v1_user_register():
    f_data = f.request.form
    username = f_data.get("username")
    password = f_data.get("password")
    if username is None or password is None:
        return f.jsonify({
def main():
    configure_app(app)
    db.init_app(app)
    app.register_blueprint(blueprint, url_prefix='/api')
    app.run(debug=config.FLASK_DEBUG)
Beispiel #40
0
def init_db():
    db.init_app(app)
    dbPictures.init_app(app)
    db.app = app
    dbPictures.app = app
Beispiel #41
0
def init_app(app):
    db.init_app(app)
    flask_migrate.Migrate(app, db, directory='database/migrations')
Beispiel #42
0
def create_app(config_name='production'):
    """Create the app instance via Factory Method"""

    app = Flask(__name__)

    # Set the app config
    app.config.from_object(config[config_name])
    app.config["SECURITY_I18N_DIRNAME"] = [
        pkg_resources.resource_filename("flask_security", "translations"),
        "translations"
    ]
    app.secret_key = app.config['SECRET_KEY']
    # setup autoreload jinja cache
    app.jinja_env.auto_reload = True
    # Init db
    db.init_app(app)

    # DebugToolbarExtension(app)

    # Init the Flask-Session via app object
    # flask_session.init_app(app)

    # Init the Flask-Login via app object
    # login_manager.init_app(app)

    # Setup Flask-Security
    flask_security.init_app(
        app, user_datastore)  # register_form=ExtendedRegisterForm)

    # Init the Flask-Bable via app object
    flask_bable.init_app(app)

    # Init the Flask-bootstrap via app object
    flask_bootstrap.init_app(app)

    # Init the swgger via app object
    swagger.init_app(app)

    # Init the Flask-Restful via app object
    restful_api_bp = Blueprint('api_v1',
                               __name__,
                               url_prefix=app.config['API_PREFIX'] + '/v1')
    restful_api = Api(restful_api_bp)
    api_v1.api_setup(restful_api)
    app.register_blueprint(restful_api_bp)

    #函数模板
    from common.helper.urlmanager import UrlManager
    app.add_template_global(UrlManager.makeup_static_url, 'makeup_static_url')
    app.add_template_global(UrlManager.makeup_image_url, 'makeup_image_url')
    from common.fields import str2json
    app.add_template_global(str2json, 'str2json')
    from common.date import Date
    app.add_template_global(Date.datetime_calculate, 'datetime_calculate')
    manage.reg_bp(app)

    @app.route('/')
    def index():
        from flask_babelex import refresh
        refresh()
        return redirect(url_for('security.login'))

    @flask_bable.localeselector
    def get_local():
        language = request.accept_languages.best_match(['zh', 'en'])
        language = 'zh_Hans_CN' if language == 'zh' else 'en'
        # Log.info(language)
        return language

    return app
Beispiel #43
0
def init_app(app):
    sess = Session()
    sess.init_app(app)
    db.init_app(app)
    flask_migrate.Migrate(app, db, directory='database/migrations')
Beispiel #44
0
def db(request, app):
    app.config['SQLALCHEMY_DATABASE_URI'] = TEST_DB

    test_db.init_app(app)
    test_db.create_all()
    yield test_db
Beispiel #45
0
def init_app(app):
    db.init_app(app)
Beispiel #46
0
def main():
    ssl(app)
    db.init_app(app)
    app.run(ssl_context = ctx, host='0.0.0.0', port=8082)    
Beispiel #47
0
def configure_database(app):
    "Database configuration should be set here"
    # uncomment for sqlalchemy support
    from database import db
    db.app = app
    db.init_app(app)
Beispiel #48
0
def init_db(flask_app):
    db.init_app(flask_app)
    db.create_all()
Beispiel #49
0
def init_app(app):
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    db.init_app(app)
Beispiel #50
0
def create_app(config_filename='config.py', config_override={}):
    """Factory function for flask application.

    Args:
        config_filename:
            path to python config file
        config_override:
            a dict with settings to use to override config from file;
            useful for writing very specific tests.
    """
    app = Flask(__name__)

    #
    # Configuration handling
    #

    if config_filename:
        app.config.from_pyfile(config_filename)

    for key, value in config_override.items():
        app.config[key] = value

    # ReCaptcha
    recaptcha.init_app(app)

    # Limiter
    limiter.init_app(app)

    # Scheduler
    if app.config.get('SCHEDULER_ENABLED', True):
        if scheduler.running:
            scheduler.shutdown()
        scheduler.init_app(app)
        scheduler.start()

    # Celery
    celery.init_app(app)
    from celery.security import setup_security
    setup_security()

    #
    # Error logging
    #
    if not app.debug:
        import logging
        from logging.handlers import RotatingFileHandler

        os.makedirs('logs', exist_ok=True)

        file_handler = RotatingFileHandler('logs/app.log',
                                           maxBytes=10 * 1024 * 1024,
                                           backupCount=5)
        file_handler.setLevel(logging.WARNING)
        root_logger = logging.getLogger()
        root_logger.addHandler(file_handler)

    #
    # Database creation
    #
    db.app = app
    db.init_app(app)
    db.create_all(bind='__all__')

    mode = app.config.get('BDB_MODE', 'c')
    bdb.open(app.config['BDB_DNA_TO_PROTEIN_PATH'], mode=mode)
    bdb_refseq.open(app.config['BDB_GENE_TO_ISOFORM_PATH'], mode=mode)

    if app.config['USE_LEVENSTHEIN_MYSQL_UDF']:
        with app.app_context():
            for bind_key in ['bio', 'cms']:
                engine = get_engine(bind_key)
                engine.execute("DROP FUNCTION IF EXISTS levenshtein_ratio")
                engine.execute(
                    "CREATE FUNCTION levenshtein_ratio RETURNS REAL SONAME 'levenshtein.so'"
                )

    #
    # Configure Login Manager
    #
    from models import User
    from models import AnonymousUser

    login_manager.anonymous_user = AnonymousUser
    login_manager.user_loader(User.user_loader)

    login_manager.init_app(app)

    #
    # Configure mail service
    #
    mail.init_app(app)

    #
    # Register assets
    #
    assets = Environment(app)

    for name, bundle in bundles.items():
        assets.register(name, bundle)

    #
    # Import views
    #

    # allow access to this app from views through module
    import sys
    sys.path.insert(0, '..')

    with app.app_context():

        from website.views import views

        for view in views:
            view.register(app)

    #
    # Register functions for Jinja
    #

    import jinja2

    base_dir = os.path.dirname(os.path.realpath(__file__))

    template_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(os.path.join(base_dir, 'static/js_templates')),
    ])
    app.jinja_loader = template_loader

    from website.views.cms import substitute_variables
    from website.views.cms import thousand_separated_number
    from website.views.cms import ContentManagementSystem
    from jinja2_pluralize import pluralize
    import json

    # csrf adds hooks in before_request to validate token
    app.before_request(csrf.csrf_protect)

    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    jinja_globals = app.jinja_env.globals
    jinja_filters = app.jinja_env.filters

    app.dependency_manager = DependencyManager(app)

    jinja_globals['dependency'] = app.dependency_manager.get_dependency
    jinja_globals['system_menu'] = ContentManagementSystem._system_menu
    jinja_globals['system_setting'] = ContentManagementSystem._system_setting
    jinja_globals['inline_help'] = ContentManagementSystem._inline_help
    jinja_globals['text_entry'] = ContentManagementSystem._text_entry
    jinja_globals['t_sep'] = thousand_separated_number
    jinja_globals['csrf_token'] = csrf.new_csrf_token
    jinja_globals['is_debug_mode'] = app.debug

    jinja_filters['json'] = json.dumps
    jinja_filters['substitute_allowed_variables'] = substitute_variables
    jinja_filters['pluralize'] = pluralize

    return app
Beispiel #51
0
 def configure_database(self):
     """
     Database configuration should be set here
     """
     db.init_app(self)
Beispiel #52
0
def create_app(name=__name__):
    app = Flask(name)
    app.config.from_object("config.DevelopmentConfig")
    db.init_app(app)
    return app
Beispiel #53
0
    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    return celery


flask_app = Flask(__name__)

flask_app.config.from_object(__name__ + '.CeleryConfig')

db.init_app(flask_app)
celery = make_celery(flask_app)


@celery.task
def event_listener(web3=None):
    # Load our block cursor from the event_tracker table.
    event_tracker = db_models.EventTracker.query.first()
    if not event_tracker:
        # No cursor found. Start from the beginning at block 0.
        event_tracker = db_models.EventTracker(last_read=0)
        db.session.add(event_tracker)
        db.session.commit()

    # Create an event handler and attempt to fetch events from the network.
    handler = EventHandler(web3=web3)
def load_test_app():
    _test_app_ctx.push()
    db.init_app(_test_app)
    db.create_all()
def init_ext(app):
    db.init_app(app)
    commands.init_app(app)
Beispiel #56
0
def init_db():
    db.init_app(app)
    db.app = app
    db.create_all()
Beispiel #57
0
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    return app
Beispiel #58
0
 def init_app(self, app, url_prefix='/api'):
     db.init_app(app)
     app.register_blueprint(blueprint, url_prefix=url_prefix)
def app():
    app = create_app("config_test.py")
    with app.app_context():
        db.init_app(app)
        db.create_all()
    yield app
Beispiel #60
0
def initialize_extensions(app):
    db.init_app(app)
    marshmallow.init_app(app)
    bcrypt.init_app(app)
    auth_token_db.init_app(app)