Ejemplo n.º 1
0
    def install(cls, app):
        """Install the extension into the application."""
        Environment.resolver_class = InvenioResolver
        env = Environment(app)
        env.url = "{0}/{1}/".format(app.static_url_path,
                                    app.config["ASSETS_BUNDLES_DIR"])
        env.directory = os.path.join(app.static_folder,
                                     app.config["ASSETS_BUNDLES_DIR"])
        env.append_path(app.static_folder)
        env.auto_build = app.config.get("ASSETS_AUTO_BUILD", True)

        # The filters less and requirejs don't have the same behaviour by
        # default. Make sure we are respecting that.
        app.config.setdefault("REQUIREJS_RUN_IN_DEBUG", False)
        # Fixing some paths as we forced the output directory with the
        # .directory
        app.config.setdefault("REQUIREJS_BASEURL", app.static_folder)
        requirejs_config = os.path.join(env.directory,
                                        app.config["REQUIREJS_CONFIG"])
        if not os.path.exists(requirejs_config):
            app.config["REQUIREJS_CONFIG"] = os.path.relpath(
                os.path.join(app.static_folder,
                             app.config["REQUIREJS_CONFIG"]), env.directory)

        app.jinja_env.add_extension(BundleExtension)
        app.context_processor(BundleExtension.inject)
Ejemplo n.º 2
0
    def install(cls, app):
        """Install the extension into the application."""
        Environment.resolver_class = InvenioResolver
        env = Environment(app)
        env.url = "{0}/{1}/".format(app.static_url_path,
                                    app.config["ASSETS_BUNDLES_DIR"])
        env.directory = os.path.join(app.static_folder,
                                     app.config["ASSETS_BUNDLES_DIR"])
        env.append_path(app.static_folder)
        env.auto_build = app.config.get("ASSETS_AUTO_BUILD", True)

        # The filters less and requirejs don't have the same behaviour by
        # default. Make sure we are respecting that.
        app.config.setdefault("LESS_RUN_IN_DEBUG", True)
        app.config.setdefault("REQUIREJS_RUN_IN_DEBUG", False)
        # Fixing some paths as we forced the output directory with the
        # .directory
        app.config.setdefault("REQUIREJS_BASEURL", app.static_folder)
        requirejs_config = os.path.join(env.directory,
                                        app.config["REQUIREJS_CONFIG"])
        if not os.path.exists(requirejs_config):
            app.config["REQUIREJS_CONFIG"] = os.path.relpath(
                os.path.join(app.static_folder,
                             app.config["REQUIREJS_CONFIG"]),
                env.directory)

        app.jinja_env.add_extension(BundleExtension)
        app.context_processor(BundleExtension.inject)
Ejemplo n.º 3
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    moment.init_app(app)
    rq.init_app(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(basedir / path)
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .task import task as task_blueprint
    app.register_blueprint(task_blueprint, url_prefix='/task')

    if config_name == 'production':
        from app.jobs.doc_cache import doc_cache
        # Create cron jobs
        doc_cache.cron('0 0 12 * * *', 'cache_job')

        @rq.exception_handler
        def send_alert_to_ops(job, *exc_info):
            print(job)
            print(exc_info)

    return app
Ejemplo n.º 4
0
def register_assets(app):
	assets = Environment(app)
	assets.url = app.static_url_path
	assets.directory = app.static_folder
	assets.append_path('assets')
	scss = Bundle('scss/main.scss', filters='pyscss', output='main.css', depends=('scss/*.scss'))
	assets.register('scss_all', scss)
Ejemplo n.º 5
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .data import data as data_blueprint
    app.register_blueprint(data_blueprint, url_prefix='/data')

    from .request import request_blueprint
    app.register_blueprint(request_blueprint, url_prefix='/request')

    @app.after_request
    def add_header(response):
        response.cache_control.max_age = 0
        return response

    return app
Ejemplo n.º 6
0
def create_app(configfile=None):
    app = Flask(__name__)
    AppConfig(app)
    Bootstrap(app)
    sql_dir = os.path.join(basedir, 'tmp/')
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(
        sql_dir, 'user-login.sqlite')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    REDIS_URL = 'http://localhost:6379'
    urllib.parse.uses_netloc.append('redis')
    url = urllib.parse.urlparse(REDIS_URL)
    app.config['RQ_DEFAULT_HOST'] = url.hostname
    app.config['RQ_DEFAULT_PORT'] = url.port
    app.config['RQ_DEFAULT_PASSWORD'] = url.password
    app.config['RQ_DEFAULT_DB'] = 0

    # EAM : Set limit on the number of items in cache (RAM)
    cache.init_app(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)
    assets_env.register('browser_js', browser_js)
    assets_env.register('browser_css', browser_css)
    assets_env.register('tabular_ensemble_js', tabular_ensemble_js)
    assets_env.register('tabular_rs1_js', tabular_rs1_js)
    assets_env.register('tabular_rs2_js', tabular_rs2_js)
    assets_env.register('request_new_ensemble_js', request_new_ensemble_js)
    assets_env.register('tabular_css', tabular_css)

    with app.app_context():
        from .frontend import frontend
        #app.register_blueprint(frontend, url_prefix="/portal")
        app.register_blueprint(frontend)

        from .content import content
        app.register_blueprint(content)
        #app.register_blueprint(content, url_prefix="/portal")

    app.json_encoder = MiniJSONEncoder

    nav.init_app(app)
    mail.init_app(app)
    csrf.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    compress.init_app(app)
    htmlmin.init_app(app)
    RQ(app)

    return app
def create_app(config):
    app = Flask(__name__)
    config_name = config

    if not isinstance(config, str):
        config_name = os.getenv('FLASK_CONFIG', 'default')

    app.config.from_object(Config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    Config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .volunteer import volunteer as volunteer_blueprint
    app.register_blueprint(volunteer_blueprint, url_prefix='/volunteer')

    from .staff import staff as staff_blueprint
    app.register_blueprint(staff_blueprint, url_prefix='/staff')

    return app
Ejemplo n.º 8
0
def init_assets(app):

	coffee_bundle = Bundle(
		*coffeeScripts,
		filters='coffeescript', output='js/coffee.js')

	js_bundle = Bundle(
		#lib_js_bundle,
		coffee_bundle,
		#filters='yui_js',
		output='js/main.min.js')



	clientCoffee = Bundle(
		*clientCoffeeScripts,
		filters='coffeescript', output='js/client.v1.js')

	# FIXME - still don't understand why these JS bundles arent compiling ....
	clientJs = Bundle(
		#lib_js_bundle,
		clientCoffee,
		#filters='yui_js',
		output='js/client.min.js')


	#app.config['ASSETS_DEBUG'] = settings.DEBUG
	app.config['ASSETS_DEBUG'] = False
	flaskAssets = Environment(app)

	print 'assets dir is: ', flaskAssets.directory
	print 'root path: ', app.root_path

	flaskAssets.append_path(app.root_path+'/app')
	flaskAssets.append_path(app.static_folder)

	flaskAssets.config['PYSCSS_STATIC_ROOT'] = join(STATIC_FOLDER, 'scss')
	flaskAssets.config['PYSCSS_STATIC_URL'] = join(STATIC_FOLDER, 'css/main.css')
	flaskAssets.config['PYSCSS_DEBUG'] = app.debug

	flaskAssets.register('css', css_bundle)


	flaskAssets.register('coffee', coffee_bundle)
	flaskAssets.register('js', js_bundle)

	flaskAssets.register('clientcoffee', clientCoffee)
	#flaskAssets.register('clientjs', clientJs)

	# webassets.manifest = 'cache' if not app.debug else False
	# webassets.cache = not app.debug
	#flaskAssets.cache = False
	flaskAssets.debug = app.debug

	#flaskAssets.debug = False

	for bundle, name in externalBundles:
		flaskAssets.register(name, bundle)
Ejemplo n.º 9
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # setup the celery client
    celery = Celery(app, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)

    # Register Jinja template functions
    from .template_utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .tools import tools as tools_blueprint
    app.register_blueprint(tools_blueprint, url_prefix='/tools')

    from .projects import projects as projects_blueprint
    app.register_blueprint(projects_blueprint, url_prefix='/projects')

    return app
Ejemplo n.º 10
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .inventory import inventory as inventory_blueprint
    app.register_blueprint(inventory_blueprint, url_prefix='/inventory')

    from .provisioning import provisioning as provisioning_blueprint
    app.register_blueprint(provisioning_blueprint, url_prefix='/provisioning')

    from .rtd import rtd as provisioning_rtd
    app.register_blueprint(provisioning_rtd, url_prefix='/rtd')

    return app
Ejemplo n.º 11
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Set up extensions
    bootstrap.init_app(app)
    moment.init_app(app)
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .diary import diary as diary_blueprint
    app.register_blueprint(diary_blueprint, url_prefix='/diary')

    from .video import video as video_blueprint
    app.register_blueprint(video_blueprint, url_prefix='/video')

    from .survey import survey as survey_blueprint
    app.register_blueprint(survey_blueprint, url_prefix='/survey')

    return app
Ejemplo n.º 12
0
def create_app(config_name):
    app = Flask(__name__)

    with app.app_context():
        app.config.from_object(config[config_name])
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

        config[config_name].init_app(app)

        # Set up extensions
        mail.init_app(app)
        db.init_app(app)
        login_manager.init_app(app)
        csrf.init_app(app)
        compress.init_app(app)
        RQ(app)

        # Register Jinja template functions
        from .utils import register_template_utils
        register_template_utils(app)

        # Set up asset pipeline
        assets_env = Environment(app)
        dirs = ['assets/styles', 'assets/scripts']
        for path in dirs:
            assets_env.append_path(os.path.join(basedir, path))
        assets_env.url_expire = True

        assets_env.register('app_css', app_css)
        assets_env.register('app_js', app_js)
        assets_env.register('vendor_css', vendor_css)
        assets_env.register('vendor_js', vendor_js)

        # Configure SSL if platform supports it
        if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
            from flask_sslify import SSLify
            SSLify(app)

        # Create app blueprints
        from .main import main as main_blueprint
        app.register_blueprint(main_blueprint)

        from .account import account as account_blueprint
        app.register_blueprint(account_blueprint, url_prefix='/account')

        from .adtributor import admin as admin_blueprint
        app.register_blueprint(admin_blueprint, url_prefix='/admin')

        from .adtributor import contributor as contributor_blueprint
        app.register_blueprint(contributor_blueprint,
                               url_prefix='/contributor')

        db.app = app

        return app
Ejemplo n.º 13
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .participant import participant as participant_blueprint
    app.register_blueprint(participant_blueprint, url_prefix='/participant')

    return app
Ejemplo n.º 14
0
def create_app():
    app = Flask(__name__)
    bcrypt.init_app(app)

    config_name = os.environ.get('FLASK_ENV', 'production')
    config = config_map[config_name]
    app.config.from_object(config)
    config.init_app(app)

    db.init_app(app)

    login_manager.init_app(app)

    register_template_filters(app)
    register_context_processors(app)

    assets_env = Environment(app)
    assets_env.append_path(os.path.join(basedir, 'assets/scripts'))
    assets_env.append_path(os.path.join(basedir, 'assets/styles'))
    assets_env.append_path(os.path.join(basedir, 'assets/vendor'))
    assets_env.url_expire = True

    assets_env.register('app_css', assets.app_css)
    assets_env.register('app_js', assets.app_js)
    assets_env.register('vendor_css', assets.vendor_css)
    assets_env.register('vendor_js', assets.vendor_js)

    from app.main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from app.usuario import usuario as usuario_blueprint
    app.register_blueprint(usuario_blueprint, url_prefix='/usuarios')

    from app.porto import porto as porto_blueprint
    app.register_blueprint(porto_blueprint, url_prefix='/portos')

    from app.empresa import empresa as empresa_blueprint
    app.register_blueprint(empresa_blueprint, url_prefix='/empresas')

    from app.relatorio import relatorio as relatorio_blueprint
    app.register_blueprint(relatorio_blueprint, url_prefix='/relatorios')

    from app.navio import navio as navio_blueprint
    app.register_blueprint(navio_blueprint, url_prefix='/navios')

    from app.viagem import viagem as navio_blueprint
    app.register_blueprint(navio_blueprint, url_prefix='/viagens')

    return app
Ejemplo n.º 15
0
def create_app(config_name, main=True):
	app = Flask(__name__)
	app.config.from_object(config[config_name])
	app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
	# not using sqlalchemy event system, hence disabling it

	config[config_name].init_app(app)

	# Set up extensions
	db.init_app(app)
	db.sessionmaker(autoflush=False)
	login_manager.init_app(app)
	csrf.init_app(app)
	compress.init_app(app)
	RQ(app)
	socketio.init_app(app, message_queue=app.config['SOCKETIO_MESSAGE_QUEUE'])

	# Register Jinja template functions
	from .utils import register_template_utils
	register_template_utils(app)

	# Set up asset pipeline
	assets_env = Environment(app)
	dirs = ['assets/styles', 'assets/scripts']
	for path in dirs:
		assets_env.append_path(os.path.join(basedir, path))
	assets_env.url_expire = True

	assets_env.register('app_js', app_js)
	assets_env.register('vendor_css', vendor_css)
	assets_env.register('vendor_js', vendor_js)

	# Configure SSL if platform supports it
	if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
		from flask.ext.sslify import SSLify
		SSLify(app)

	# Create app blueprints
	from .main import main as main_blueprint
	app.register_blueprint(main_blueprint)

	from .account import account as account_blueprint
	app.register_blueprint(account_blueprint, url_prefix='/account')

	from .admin import admin as admin_blueprint
	app.register_blueprint(admin_blueprint, url_prefix='/admin')

	return app
Ejemplo n.º 16
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .SnEMechs import SnEMechs as SnEMechs_blueprint
    app.register_blueprint(SnEMechs_blueprint,
                           url_prefix='/Sn_1+Sn_2+E1+E2+Mechanisms')

    return app
Ejemplo n.º 17
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    config[config_name].init_app(app)

    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    from app.utils import register_template_utils
    register_template_utils(app)

    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    from app.main.views import main_blueprint
    app.register_blueprint(main_blueprint)

    from app.account.views import account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from app.admin.views import admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    return app
Ejemplo n.º 18
0
def create_app(config_enviroment):
    app = Flask(__name__)

    app.config.from_object(config[config_enviroment])

    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)

    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_enviroment].init_app(app)

    # Create app blueprints
    from app.main import main_bp
    app.register_blueprint(main_bp)

    from app.account import account_bp
    app.register_blueprint(account_bp, url_prefix='/account')

    return app
Ejemplo n.º 19
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    # not using sqlalchemy education system, hence disabling it
    config[config_name].init_app(app)
    # Set up extensions
    # mail.init_app(app)
    # db.init_app(app)
    # login_manager.init_app(app)
    # csrf.init_app(app)
    # jwt.init_app(app)
    compress.init_app(app)
    # RQ(app)
    cors.init_app(app, resources={r"/v1/*": {"origins": "*"}})
    # configure_uploads(app, [photos, docs])
    # patch_request_class(app, 10 * 1024 * 1024)
    # swagger.init_app(app)
    # # Register Jinja template functions
    # from .utils import register_template_utils
    # register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

        # Create app blueprints
    from .api.blockchain import blockchain as blockchain_blueprint
    app.register_blueprint(blockchain_blueprint, url_prefix='/v1/vote')

    return app
Ejemplo n.º 20
0
migrate = Migrate(app, db)

ma = Marshmallow(app)

manager = Manager(app)
manager.add_command('runserver', Server())
manager.add_command(
    'shell', Shell(make_context=lambda: {
        'app': app,
        'db_session': db_session
    }))
manager.add_command('db', MigrateCommand)
manager.add_command('init', Init())

environment = Environment(app)
environment.append_path(str(cwd / 'static'))
environment.append_path(str(cwd / 'bower_components'))

version = subprocess.check_output(['git', 'describe', '--tags', '--always'],
                                  cwd=str(cwd)).decode(
                                      sys.stdout.encoding).strip()

app.config['SECRET_KEY'] = config['SECRET_KEY']
app.config['SESSION_PROTECTION'] = 'strong'
app.config['SOCIAL_AUTH_LOGIN_URL'] = '/login'
app.config['SOCIAL_AUTH_LOGIN_REDIRECT_URL'] = '/?logged_in=1'
app.config['SOCIAL_AUTH_USER_MODEL'] = 'models.User'
app.config['SOCIAL_AUTH_AUTHENTICATION_BACKENDS'] = (
    'social_core.backends.google.GoogleOAuth2', )
app.config['SOCIAL_AUTH_FIELDS_STORED_IN_SESSION'] = ['keep']
app.config['SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS'] = {
Ejemplo n.º 21
0
class TestUrlAndDirectory(TempEnvironmentHelper):
    """By default, the 'url' and 'directory' settings of webassets are
    not used in Flask-Assets; that is, the values are automatically
    handled based on the configuration of the Flask app and the modules
    used.

    The user can disable the automatic handling by setting these values
    if he needs to for some reason.

    Let's test the different scenarios to ensure everything works.
    """

    def setup(self):
        TempEnvironmentHelper.setup(self)

        self.app = Flask(__name__, static_path='/app_static')
        from tests import test_module
        if not Blueprint:
            self.module = Module(test_module.__name__, name='module',
                                 static_path='/mod_static')
            self.app.register_module(self.module)
        else:
            self.blueprint = Blueprint('module', test_module.__name__,
                                       static_url_path='/mod_static',
                                       static_folder='static')
            self.app.register_blueprint(self.blueprint)
        self.env = Environment(self.app)

    def test_config_values_not_set_by_default(self):
        assert not 'directory' in self.env.config
        assert not 'url' in self.env.config
        assert_raises(KeyError, self.env.config.__getitem__, 'directory')
        assert_raises(KeyError, self.env.config.__getitem__, 'url')

    def test_directory_auto(self):
        """Test how we resolve file references through the Flask static
        system by default (if no custom 'env.directory' etc. values
        have been configured manually).
        """
        assert not 'directory' in self.env.config
        root = self.app.root_path
        assert get_all_bundle_files(Bundle('foo'), self.env) == [root + '/static/foo']
        # Modules prefixes in paths are handled specifically.
        assert get_all_bundle_files(Bundle('module/bar'), self.env) == [root + '/test_module/static/bar']
        # Prefixes that aren't valid module names are just considered
        # subfolders of the main app.
        assert get_all_bundle_files(Bundle('nomodule/bar'), self.env) == [root + '/static/nomodule/bar']
        # In case the name of a app-level subfolder conflicts with a
        # module name, you can always use this hack:
        assert get_all_bundle_files(Bundle('./module/bar'), self.env) == [root + '/static/module/bar']

        # Custom static folder
        self.app.static_folder = '/'
        assert get_all_bundle_files(Bundle('foo'), self.env) == ['/foo']

    def test_url_auto(self):
        """Test how urls are generated via the Flask static system
        by default (if no custom 'env.url' etc. values have been
        configured manually).
        """
        assert not 'url' in self.env.config

        assert Bundle('foo', env=self.env).urls() == ['/app_static/foo']
        # Urls for files that point to a module use that module's url prefix.
        assert Bundle('module/bar', env=self.env).urls() == ['/mod_static/bar']
        # Try with a prefix that's not actually a valid module
        assert Bundle('nomodule/bar', env=self.env).urls() == ['/app_static/nomodule/bar']

        # [Regression] Ensure that any request context we may have added
        # to the stack has been removed.
        from flask import _request_ctx_stack
        assert _request_ctx_stack.top is None

    def test_custom_load_path(self):
        """A custom load_path is configured - this will affect how
        we deal with source files.
        """
        self.env.append_path(self.tempdir, '/custom/')
        self.create_files(['foo', 'module/bar'])
        assert get_all_bundle_files(Bundle('foo'), self.env) == [self.path('foo')]
        # We do not recognize references to modules.
        assert get_all_bundle_files(Bundle('module/bar'), self.env) == [self.path('module/bar')]


        assert Bundle('foo', env=self.env).urls() == ['/custom/foo']
        assert Bundle('module/bar', env=self.env).urls() == ['/custom/module/bar']

        # [Regression] With a load path configured, generating output
        # urls still works, and it still uses the flask system.
        self.env.debug = False
        self.env.url_expire = False
        assert Bundle('foo', output='out', env=self.env).urls() == ['/app_static/out']

    def test_custom_directory_and_url(self):
        """Custom directory/url are configured - this will affect how
        we deal with output files."""
        # Create source source file, make it findable (by default,
        # static_folder) is set to a fixed subfolder of the test dir (why?)
        self.create_files({'a': ''})
        self.app.static_folder = self.tempdir
        # Setup custom directory/url pair for output
        self.env.directory = self.tempdir
        self.env.url = '/custom'
        self.env.debug = False   # Return build urls
        self.env.url_expire = False  # No query strings

        assert Bundle('a', output='foo', env=self.env).urls() == ['/custom/foo']
        # We do not recognize references to modules.
        assert Bundle('a', output='module/bar', env=self.env).urls() == ['/custom/module/bar']

    def test_existing_request_object_used(self):
        """[Regression] Check for a bug where the url generation code of
        Flask-Assets always added a dummy test request to the context stack,
        instead of using the existing one if there is one.

        We test this by making the context define a custom SCRIPT_NAME
        prefix, and then we check if it affects the generated urls, as
        it should.
        """
        with self.app.test_request_context(
                  '/', environ_overrides={'SCRIPT_NAME': '/yourapp'}):
            assert Bundle('foo', env=self.env).urls() == ['/yourapp/app_static/foo']

    def test_glob(self):
        """Make sure url generation works with globs."""
        self.app.static_folder = self.tempdir
        self.create_files({'a.js': 'foo', 'b.js': 'bar'})
        assert list(sorted(self.mkbundle('*.js', env=self.env).urls())) == [
            '/app_static/a.js', '/app_static/b.js']
Ejemplo n.º 22
0
# Set up extensions
mail.init_app(app)
db.init_app(app)
login_manager.init_app(app)
csrf.init_app(app)
compress.init_app(app)

# Register Jinja template functions
from .utils import register_template_utils
register_template_utils(app)

# Set up asset pipeline
assets_env = Environment(app)
dirs = ['assets/styles', 'assets/scripts']
for path in dirs:
    assets_env.append_path(os.path.join(basedir, path))
assets_env.url_expire = True

assets_env.register('app_css', app_css)
assets_env.register('app_js', app_js)
assets_env.register('vendor_css', vendor_css)
assets_env.register('vendor_js', vendor_js)

# Configure SSL if platform supports it
if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
    from flask_sslify import SSLify
    SSLify(app)

# Create app blueprints
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
def create_app(config_name, url_prefix=""):
    app = Flask(__name__,
                static_url_path=url_prefix + "/static",
                subdomain_matching=True)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    # csrf.init_app(app)
    CSRFProtect(app)
    compress.init_app(app)
    RQ(app)
    # admin.init_app(app)
    # admin.add_view(ModelView(User, db.session))
    # admin.add_view(ModelView(OralHistory, db.session))
    # jsglue.init_app(app, url_prefix=url_prefix)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    hypothesis_service = os.environ.get('HYPOTHESIS_SERVICE',
                                        'http://localhost:5000')
    hyp_client = HypothesisClient(
        authority=os.environ['HYPOTHESIS_AUTHORITY'],
        client_id=os.environ['HYPOTHESIS_CLIENT_ID'],
        client_secret=os.environ['HYPOTHESIS_CLIENT_SECRET'],
        jwt_client_id=os.environ['HYPOTHESIS_JWT_CLIENT_ID'],
        jwt_client_secret=os.environ['HYPOTHESIS_JWT_CLIENT_SECRET'],
        service=hypothesis_service)
    app.hypothesis_client = hyp_client

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint, url_prefix=url_prefix)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint,
                           url_prefix=url_prefix + '/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix=url_prefix + '/admin')

    from .experimental import experimental as experimental_blueprint
    app.register_blueprint(experimental_blueprint,
                           url_prefix=url_prefix + '/experimental')

    return app
Ejemplo n.º 24
0
def create_app(config):
    app = Flask(__name__)
    config_name = config

    if not isinstance(config, str):
        config_name = os.getenv('FLASK_CONFIG', 'default')

    app.config.from_object(Config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    Config[config_name].init_app(app)
    app.config['UPLOADED_IMAGES_DEST'] = '/home/ubuntu/flaskapp/flask-base/appstatic/photo/' if \
        not os.environ.get('UPLOADED_IMAGES_DEST') else os.path.dirname(os.path.realpath(__file__)) + os.environ.get(
        'UPLOADED_IMAGES_DEST')
    app.config['UPLOADED_DOCS_DEST'] = '/home/ubuntu/flaskapp/flask-base/appstatic/docs/' if \
        not os.environ.get('UPLOADED_DOCS_DEST') else os.path.dirname(os.path.realpath(__file__)) + os.environ.get(
        'UPLOADED_DOCS_DEST')
    app.config['docs'] = app.config['UPLOADED_DOCS_DEST']

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)
    configure_uploads(app, images)
    configure_uploads(app, docs)
    share.init_app(app)
    CKEditor(app)
    moment.init_app(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .api import blueprint as api_blueprint
    app.register_blueprint(api_blueprint)

    from .public import public as public_blueprint
    app.register_blueprint(public_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .blog import blog as blog_blueprint
    app.register_blueprint(blog_blueprint, url_prefix='/blog')

    return app
Ejemplo n.º 25
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it
    #'C:/Users/oem/Desktop/marketplace/marketplace/app/static/frontend/images/' 
    #'C:/Users/oem/Desktop/marketplace/marketplace/appstatic/docs/'

    app.config['UPLOADED_IMAGES_DEST'] = basedir + 'static/frontend/images' if \
        not os.environ.get('UPLOADED_IMAGES_DEST') else os.path.dirname(os.path.realpath(__file__)) + os.environ.get(
        'UPLOADED_IMAGES_DEST')
    app.config['UPLOADED_DOCS_DEST'] = basedir + 'static/docs' if \
        not os.environ.get('UPLOADED_DOCS_DEST') else os.path.dirname(os.path.realpath(__file__)) + os.environ.get(
        'UPLOADED_DOCS_DEST')
    app.config['docs'] = app.config['UPLOADED_DOCS_DEST']

    app.config['CKEDITOR_SERVE_LOCAL'] = True
    app.config['CKEDITOR_HEIGHT'] = 400
    app.config['CKEDITOR_FILE_UPLOADER'] = 'upload'
    app.config['CKEDITOR_ENABLE_CSRF'] = True  # if you want to enable CSRF protect, uncomment this line
    app.config['UPLOADED_PATH'] = os.path.join(basedir, 'uploads')
    #app.config['WHOOSH_BASE']='whoosh'

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)
    configure_uploads(app, (images))
    configure_uploads(app, docs)
    ckeditor = CKEditor(app)
    share.init_app(app)
    moment.init_app(app)
    jwt.init_app(app)
    sess.init_app(app)
    whooshee.init_app(app)
    # whooshee = Whooshee(app)
    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .blueprints.public import public as public_blueprint
    app.register_blueprint(public_blueprint)

    from .blueprints.seo_world import seo_world as seo_world_blueprint
    app.register_blueprint(seo_world_blueprint)

    from .blueprints.main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .blueprints.account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .blueprints.admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .blueprints.marketplace import marketplace as marketplace_blueprint
    app.register_blueprint(marketplace_blueprint, url_prefix='/marketplace')

    from .blueprints.organisations import organisations as organisations_blueprint
    app.register_blueprint(organisations_blueprint, url_prefix='/organisations')

    from .blueprints.sitemaps import sitemaps as sitemaps_blueprint
    app.register_blueprint(sitemaps_blueprint)

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

    # main_api.init_app(app)
    app.jinja_env.globals.update(json_load=json_load, image_size=image_size, get_cart=get_cart)

    @app.before_request
    def before_request():
        try:
            session['cart_id']
        except:
            u = uuid.uuid4()
            user_agent = request.headers.get('User-Agent')
            if user_agent is not None:
                user_agent = user_agent.encode('utf-8')
            base = 'cart: {0}|{1}|{2}'.format(_get_remote_addr(), user_agent, u)
            if str is bytes:
                base = text_type(base, 'utf-8', errors='replace')  # pragma: no cover
            h = sha512()
            h.update(base.encode('utf8'))
            session['cart_id'] = h.hexdigest()
    
    @app.cli.command()
    def reindex():
        with app.app_context():
            whooshee.reindex()
            
    @app.cli.command()
    def routes():
        """'Display registered routes"""
        rules = []
        for rule in app.url_map.iter_rules():
            methods = ','.join(sorted(rule.methods))
            rules.append((rule.endpoint, methods, str(rule)))

        sort_by_rule = operator.itemgetter(2)
        for endpoint, methods, rule in sorted(rules, key=sort_by_rule):
            route = '{:50s} {:25s} {}'.format(endpoint, methods, rule)
            print(route)


    @app.template_filter('product')
    def product(o):
        """check if object is user"""
        from app.models import MProduct
        return o.__class__ == MProduct
    
    return app
Ejemplo n.º 26
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .bulk_resource import bulk_resource as bulk_resource_blueprint
    app.register_blueprint(bulk_resource_blueprint,
                           url_prefix='/bulk-resource')

    from .descriptor import descriptor as descriptor_blueprint
    app.register_blueprint(descriptor_blueprint, url_prefix='/descriptor')

    from .single_resource import single_resource as single_resource_blueprint
    app.register_blueprint(single_resource_blueprint,
                           url_prefix='/single-resource')

    from .suggestion import suggestion as suggestion_blueprint
    app.register_blueprint(suggestion_blueprint, url_prefix='/suggestion')

    from .contact import contact as contact_blueprint
    app.register_blueprint(contact_blueprint, url_prefix='/contact')
    return app
Ejemplo n.º 27
0
def create_app(config_name):
    app = Flask(__name__, static_folder='static')
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    csrf.init_app(app)
    oauth.init_app(app)
    oauthclient.init_app(app)
    RQ(app)

    db.app = app

    cors = CORS(app,
                resources={
                    r"/api/v1/*": {
                        "origins": "*"
                    },
                    r"/auth/oauth/*": {
                        "origins": "*"
                    }
                })
    api = Api(app)
    babel.init_app(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not os.environ.get('SSL_DISABLE'):
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

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

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from app.api.docs import docs as docs_blueprint
    app.register_blueprint(docs_blueprint)

    from flasgger import APISpec, Schema, Swagger, fields

    spec = APISpec(
        title='Bhagavad Gita API',
        version='1.0.0',
        plugins=[
            'apispec.ext.flask',
            'apispec.ext.marshmallow',
        ],
    )

    app.config['SWAGGER'] = {'title': 'Bhagavad Gita API', 'uiversion': 3}

    swagger = Swagger(app,
                      template={
                          'swagger': '2.0',
                          'info': {
                              'title': 'Bhagavad Gita API',
                              'version': '1.0'
                          }
                      })

    from app.api.v1.verse import VerseList, VerseListByChapter, VerseByChapter
    from app.api.v1.chapter import Chapter, ChapterList

    verse_list_view = VerseList.as_view('VerseList')
    app.add_url_rule('/api/v1/verses', view_func=verse_list_view)

    verse_list_chapter_view = VerseListByChapter.as_view('VerseListChapter')
    app.add_url_rule('/api/v1/chapters/<int:chapter_number>/verses',
                     view_func=verse_list_chapter_view)

    verse_chapter_view = VerseByChapter.as_view('VerseChapter')
    app.add_url_rule(
        '/api/v1/chapters/<int:chapter_number>/verses/<string:verse_number>',
        view_func=verse_chapter_view)

    chapter_view = Chapter.as_view('Chapter')
    app.add_url_rule('/api/v1/chapters/<int:chapter_number>',
                     view_func=chapter_view)

    chapter_list_view = ChapterList.as_view('ChapterList')
    app.add_url_rule('/api/v1/chapters', view_func=chapter_list_view)

    def _force_https():
        if not app.debug:
            from flask import _request_ctx_stack
            if _request_ctx_stack is not None:
                reqctx = _request_ctx_stack.top
                reqctx.url_adapter.url_scheme = 'https'

    app.before_request(_force_https)

    with app.test_request_context():
        spec.add_path(view=verse_list_view)
        spec.add_path(view=verse_list_chapter_view)
        spec.add_path(view=verse_chapter_view)
        spec.add_path(view=chapter_view)
        spec.add_path(view=chapter_list_view)

    return app
Ejemplo n.º 28
0
    ]),
])
app.jinja_loader = my_loader

db = SQLAlchemy(app)

Markdown(app, extensions=['footnotes'])
pages = FlatPages(app)

manager = Manager(app)

# Scss
assets = Environment(app)
assets.url_expire = True
assets.auto_build = True
assets.append_path('sni/assets')
assets.cache = 'sni/assets/.webassets-cache'

scss = Bundle('scss/__main__.scss',
              filters='pyscss',
              output='css/main.css',
              depends=['scss/*.scss'])
assets.register('scss_all', scss)

assets.debug = False
app.config['ASSETS_DEBUG'] = False

cache = Cache(app, config={'CACHE_TYPE': 'simple'})

if not app.debug:
    import logging
Ejemplo n.º 29
0
def create_app(config):
    app = Flask(__name__)
    config_name = config

    if not isinstance(config, str):
        config_name = os.getenv("FLASK_CONFIG", "default")

    app.config.from_object(Config[config_name])
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    # not using sqlalchemy event system, hence disabling it

    Config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)
    configure_uploads(app, images)
    configure_uploads(app, docs)
    CKEditor(app)
    share.init_app(app)
    Bootstrap(app)

    # Register Jinja template functions
    from .utils import register_template_utils

    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ["assets/styles", "assets/scripts"]
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register("app_css", app_css)
    assets_env.register("app_js", app_js)
    assets_env.register("vendor_css", vendor_css)
    assets_env.register("vendor_js", vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config["SSL_DISABLE"]:
        from flask_sslify import SSLify

        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .public import public as public_blueprint

    app.register_blueprint(public_blueprint)

    from .account import account as account_blueprint

    app.register_blueprint(account_blueprint, url_prefix="/account")

    from .question import question as question_blueprint

    app.register_blueprint(question_blueprint, url_prefix="/question")

    from .answer import answer as answer_blueprint

    app.register_blueprint(answer_blueprint, url_prefix="/answer")

    from .project import project as project_blueprint

    app.register_blueprint(project_blueprint, url_prefix="/project")

    from .admin import admin as admin_blueprint

    app.register_blueprint(admin_blueprint, url_prefix="/admin")

    from .organisations import organisations as organisations_blueprint

    app.register_blueprint(organisations_blueprint, url_prefix="/organisations")

    from .blog import blog

    app.register_blueprint(blog, url_prefix="/blog")

    return app
Ejemplo n.º 30
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it


    app.config['OAUTH_CREDENTIALS'] = {
        'google': {
            'id': '767868202462-3v28oqcun0fnd0vc89uh7in4mbi7fg4o.apps.googleusercontent.com',
            'secret': 'KfvqdFDqYYn9hXDFeC3BmImD'
        },
        'facebook': {
            'id': '1357352657745486',
            'secret': '52e5d34fef41614988fbd1a7e33deab2'
        },
        'twitter': {
            'id': 'NzD4SB1S9Ulod1k1cqZGH5g6J ',
            'secret': 'CLXzCpbe0NxY8mOzgBtgRNWJjltJth2urwR7EkBzr365EUNEWO'
        }
    }

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    moment.init_app(app)
    ckeditor.init_app(app)
    RQ(app)

    babel.init_app(app)

    photos = UploadSet('photos', IMAGES)
    configure_uploads(app, photos)
    patch_request_class(app)

    app.config['CKEDITOR_ENABLE_CSRF'] = True
    app.config['CKEDITOR_FILE_UPLOADER'] = '/admin/upload'

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    # assets_env.register('app_css', app_css)
    # assets_env.register('app_js', app_js)
    # assets_env.register('vendor_css', vendor_css)
    # assets_env.register('vendor_js', vendor_js)
    # assets_env.register('skye_css', vendor_css)
    # assets_env.register('skye_js', vendor_js)

    # Configure SSL if platform supports it
    #if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
     #   from flask.ext.sslify import SSLify
      #  SSLify(app)

    # # Create app blueprints

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    # customer blue_print

    from .customer import customer as customer_blueprint
    app.register_blueprint(customer_blueprint, url_prefix='/customer')

    # home blue_print

    from .home import home as home_blueprint
    app.register_blueprint(home_blueprint)

    # publisher blue_print

    from .publisher import publisher as publisher_blueprint
    app.register_blueprint(publisher_blueprint, url_prefix='/publisher')

    # home blue_print

    from .auth import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .social import social as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/social_login')

    # csrf.exempt(api_blueprint)

    return app
Ejemplo n.º 31
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    csrf.init_app(app)
    oauth.init_app(app)
    RQ(app)
    api = Api(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

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

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from app.api.docs import docs as docs_blueprint
    app.register_blueprint(docs_blueprint)

    from flasgger import APISpec, Schema, Swagger, fields

    spec = APISpec(
        title='REST API',
        version='1.0.0',
        plugins=[
            'apispec.ext.flask',
            'apispec.ext.marshmallow',
        ],
    )

    app.config['SWAGGER'] = {'title': 'REST API', 'uiversion': 3}

    swagger = Swagger(app,
                      template={
                          'swagger': '3.0',
                          'info': {
                              'title': 'REST API',
                              'version': '1.0'
                          }
                      })

    from app.api.v1.building import Building, BuildingList

    building_view = Building.as_view('Building')
    app.add_url_rule('/v1/buildings/<int:building_id>',
                     view_func=building_view)

    building_list_view = BuildingList.as_view('BuildingList')
    app.add_url_rule('/v1/buildings', view_func=building_list_view)

    with app.test_request_context():
        spec.add_path(view=building_view)
        spec.add_path(view=building_list_view)

    return app
                             'sni/templates/podcast/']),
])
app.jinja_loader = my_loader

db = SQLAlchemy(app)

Markdown(app, extensions=['footnotes'])
pages = FlatPages(app)

manager = Manager(app)

# Scss
assets = Environment(app)
assets.url_expire = True
assets.auto_build = True
assets.append_path('sni/assets')
assets.cache = 'sni/assets/.webassets-cache'

scss = Bundle('scss/__main__.scss', filters='pyscss', output='css/main.css',
              depends=['scss/*.scss'])
assets.register('scss_all', scss)

assets.debug = False
app.config['ASSETS_DEBUG'] = False

cache = Cache(app, config={'CACHE_TYPE': 'simple'})

if not app.debug:
    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler('tmp/snilog.csv',
Ejemplo n.º 33
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint)

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint)

    from .bulk_resource import bulk_resource as bulk_resource_blueprint
    app.register_blueprint(bulk_resource_blueprint)

    from .descriptor import descriptor as descriptor_blueprint
    app.register_blueprint(descriptor_blueprint)

    from .single_resource import single_resource as single_resource_blueprint
    app.register_blueprint(single_resource_blueprint)

    from .suggestion import suggestion as suggestion_blueprint
    app.register_blueprint(suggestion_blueprint)

    from .contact import contact as contact_blueprint
    app.register_blueprint(contact_blueprint)

    @app.before_request
    def br():
        from flask import request
        g.tlf = request.path[1:].split('/', 1)[0]

        from .models import Locale
        Locale.check_locale(g.tlf)

    @app.after_request
    def ar(response):
        #if not tlf(g.tlf):
        pass  #abort(404)
        return response

    return app
Ejemplo n.º 34
0
class TestUrlAndDirectory(TempEnvironmentHelper):
    """By default, the 'url' and 'directory' settings of webassets are
    not used in Flask-Assets; that is, the values are automatically
    handled based on the configuration of the Flask app and the modules
    used.

    The user can disable the automatic handling by setting these values
    if he needs to for some reason.

    Let's test the different scenarios to ensure everything works.
    """
    def setup(self):
        TempEnvironmentHelper.setup(self)

        self.app = Flask(__name__, static_path='/app_static')
        from tests import test_module
        if not Blueprint:
            self.module = Module(test_module.__name__,
                                 name='module',
                                 static_path='/mod_static')
            self.app.register_module(self.module)
        else:
            self.blueprint = Blueprint('module',
                                       test_module.__name__,
                                       static_url_path='/mod_static',
                                       static_folder='static')
            self.app.register_blueprint(self.blueprint)
        self.env = Environment(self.app)

    def test_config_values_not_set_by_default(self):
        assert not 'directory' in self.env.config
        assert not 'url' in self.env.config
        assert_raises(KeyError, self.env.config.__getitem__, 'directory')
        assert_raises(KeyError, self.env.config.__getitem__, 'url')

    def test_directory_auto(self):
        """Test how we resolve file references through the Flask static
        system by default (if no custom 'env.directory' etc. values
        have been configured manually).
        """
        assert not 'directory' in self.env.config
        root = self.app.root_path
        assert get_all_bundle_files(Bundle('foo'),
                                    self.env) == [root + '/static/foo']
        # Modules prefixes in paths are handled specifically.
        assert get_all_bundle_files(Bundle('module/bar'), self.env) == [
            root + '/test_module/static/bar'
        ]
        # Prefixes that aren't valid module names are just considered
        # subfolders of the main app.
        assert get_all_bundle_files(Bundle('nomodule/bar'), self.env) == [
            root + '/static/nomodule/bar'
        ]
        # In case the name of a app-level subfolder conflicts with a
        # module name, you can always use this hack:
        assert get_all_bundle_files(Bundle('./module/bar'),
                                    self.env) == [root + '/static/module/bar']

        # Custom static folder
        self.app.static_folder = '/'
        assert get_all_bundle_files(Bundle('foo'), self.env) == ['/foo']

    def test_url_auto(self):
        """Test how urls are generated via the Flask static system
        by default (if no custom 'env.url' etc. values have been
        configured manually).
        """
        assert not 'url' in self.env.config

        assert Bundle('foo', env=self.env).urls() == ['/app_static/foo']
        # Urls for files that point to a module use that module's url prefix.
        assert Bundle('module/bar', env=self.env).urls() == ['/mod_static/bar']
        # Try with a prefix that's not actually a valid module
        assert Bundle('nomodule/bar',
                      env=self.env).urls() == ['/app_static/nomodule/bar']

        # [Regression] Ensure that any request context we may have added
        # to the stack has been removed.
        from flask import _request_ctx_stack
        assert _request_ctx_stack.top is None

    def test_custom_load_path(self):
        """A custom load_path is configured - this will affect how
        we deal with source files.
        """
        self.env.append_path(self.tempdir, '/custom/')
        self.create_files(['foo', 'module/bar'])
        assert get_all_bundle_files(Bundle('foo'),
                                    self.env) == [self.path('foo')]
        # We do not recognize references to modules.
        assert get_all_bundle_files(Bundle('module/bar'),
                                    self.env) == [self.path('module/bar')]

        assert Bundle('foo', env=self.env).urls() == ['/custom/foo']
        assert Bundle('module/bar',
                      env=self.env).urls() == ['/custom/module/bar']

        # [Regression] With a load path configured, generating output
        # urls still works, and it still uses the flask system.
        self.env.debug = False
        self.env.url_expire = False
        assert Bundle('foo', output='out',
                      env=self.env).urls() == ['/app_static/out']

    def test_custom_directory_and_url(self):
        """Custom directory/url are configured - this will affect how
        we deal with output files."""
        # Create source source file, make it findable (by default,
        # static_folder) is set to a fixed subfolder of the test dir (why?)
        self.create_files({'a': ''})
        self.app.static_folder = self.tempdir
        # Setup custom directory/url pair for output
        self.env.directory = self.tempdir
        self.env.url = '/custom'
        self.env.debug = False  # Return build urls
        self.env.url_expire = False  # No query strings

        assert Bundle('a', output='foo',
                      env=self.env).urls() == ['/custom/foo']
        # We do not recognize references to modules.
        assert Bundle('a', output='module/bar',
                      env=self.env).urls() == ['/custom/module/bar']

    def test_existing_request_object_used(self):
        """[Regression] Check for a bug where the url generation code of
        Flask-Assets always added a dummy test request to the context stack,
        instead of using the existing one if there is one.

        We test this by making the context define a custom SCRIPT_NAME
        prefix, and then we check if it affects the generated urls, as
        it should.
        """
        with self.app.test_request_context(
                '/', environ_overrides={'SCRIPT_NAME': '/yourapp'}):
            assert Bundle('foo',
                          env=self.env).urls() == ['/yourapp/app_static/foo']

    def test_glob(self):
        """Make sure url generation works with globs."""
        self.app.static_folder = self.tempdir
        self.create_files({'a.js': 'foo', 'b.js': 'bar'})
        assert list(sorted(self.mkbundle('*.js', env=self.env).urls())) == [
            '/app_static/a.js', '/app_static/b.js'
        ]