def create_app(testing=None):
    app = Flask(__name__)
    if testing:
        config.TESTING = True
        m = re.search("_test", config.MONGO_DATABASE)
        if not m:
            config.MONGO_DATABASE = "%s_test" % config.MONGO_DATABASE

        config.ADMIN = "rusty.shackelford"

    app.config.from_object(config)
    app.register_blueprint(admin_bp, url_prefix="/admin")
    app.register_blueprint(manage_bp, url_prefix="/manage")
    app.register_blueprint(engine_bp, url_prefix="/engine")

    mongo, db = HapPyMongo(config)

    custom_filters = {name: function for name, function in getmembers(template_filters) if isfunction(function)}
    app.jinja_env.filters.update(custom_filters)
    app.context_processor(context_functions.utility_processor)

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

    views.ProductsView.register(app)
    views.MiscView.register(app)

    return app, db
Beispiel #2
1
def create_app(db_name=None):
    app = Flask(__name__)
    app.config.from_object(config)
    if db_name:
        config.MONGO_DATABASE = db_name

    mongo, db = HapPyMongo(config)
    app.permanent_session_lifetime = timedelta(hours=2)

    auth = CloudAuth(app, db)
    app.context_processor(template_functions.view_functions)

    Admin(app)

    @app.before_first_request
    def logger():
        if not app.debug:
            app.logger.addHandler(logging.StreamHandler())
            app.logger.setLevel(logging.INFO)

    @app.before_request
    def before_request():
        g.db, g.auth = db, auth

    defaults.application_initialize(db, app)
    views.BaseView.register(app)
    views.GlobalManageView.register(app)
    views.QueryView.register(app)

    if db_name:
        return app, db
    else:
        return app
Beispiel #3
0
def _initialize_context_processors(application: Flask) -> None:
    """
        Initialize context processors to inject variables and methods into the context of the templates.

        :param application: The application instance for which the context processors will be registered.
    """
    def inject_processors() -> Dict[str, Any]:
        """
            Inject methods and variables into the template context.

            :return: A list of methods and variables.
        """
        from app.userprofile import Permission
        from app.userprofile import User

        processors = dict(
            bitwise_and=Permission.bitwise_and,
            bitwise_or=Permission.bitwise_or,
            bitwise_xor=Permission.bitwise_xor,
            has_permission=User.current_user_has_permission,
            has_permissions_all=User.current_user_has_permissions_all,
            has_permissions_one_of=User.current_user_has_permissions_one_of,
            Permission=Permission,
        )

        return processors

    application.context_processor(inject_processors)
Beispiel #4
0
def create_app(debug=False):
    app = Flask(__name__)
    app.debug = debug
    app.secret_key = 'this is a secret'
    app.json_encoder = Jsonifier

    app.file_root = os.path.abspath(os.path.dirname(__file__))

    app.before_request(before_request)
    app.after_request(after_request)
    app.context_processor(context_processor)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

    db.init_app(app)
    with app.app_context():
        init_all()
    app.register_blueprint(admin_app, url_prefix='/admin')
    app.register_blueprint(campaign_app, url_prefix='/')
    app.register_blueprint(character_app, url_prefix='/character')
    app.register_blueprint(dm_app, url_prefix='/dm')
    app.register_blueprint(chat_app, url_prefix='/chat')
    app.register_blueprint(items_app, url_prefix='/item-type')
    app.register_blueprint(knowledge_app, url_prefix='/knowledge')

    return app
Beispiel #5
0
Datei: main.py Projekt: vddd/rn
def create_app():
    app = Flask(__name__)

    load_config(app)

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

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

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

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

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

	# Apply configurations
	app.config.from_object(CONFIG[config_name])

	# Allow including raw templates without being escaped (e.g. Hogan templates)
	app.jinja_env.globals['include_raw'] = lambda filename : Markup(app.jinja_loader.get_source(app.jinja_env, filename)[0])

	# Check for versioning of static assets
	app.context_processor(revved_url_for)
	init_revisioned_urls(app)

	# Register blueprints and init routes
	register_app_blueprints(app)
	init_app_routes(app)

	# Bind the translations
	babel.init_app(app)
	@babel.localeselector
	def get_locale():
		if 'language' in g:			
			return g.language
		return request.accept_languages.best_match(['fr', 'en'])

	return app
Beispiel #7
0
def create_app(settings_ns):

    babel = Babel()
    app = Flask(
        __name__,
        static_url_path="/static",
        static_folder="static",
        instance_relative_config=False,
    )

    app.config.from_object(settings_ns)

    app.register_blueprint(main_bp)
    app.jinja_env.filters["clean_uri"] = clean_uri
    app.context_processor(utility_processor)
    babel.init_app(app)

    if app.config["DEBUG"]:
        try:
            from flask_debugtoolbar import DebugToolbarExtension
        except ImportError:
            LOGGER.info('cannot import lib "flask_debugtoolbar". '
                        'Make sure it is installed and available in the '
                        'import path.')
        else:
            toolbar = DebugToolbarExtension()
            toolbar.init_app(app)

    return app
Beispiel #8
0
def app_factory(extra_config=None):
    """Builds the flask application"""
    app = Flask(__name__)

    # App defaults
    app.config.update(dict(
        DEBUG=True,
        CLEANCSS_EXTRA_ARGS=['--skip-rebase'],
        FLATPAGES_ROOT='blog',
        FLATPAGES_EXTENSION='.md',
        FLATPAGES_MARKDOWN_EXTENSIONS=['codehilite', JavierExtensions()],
        FLATPAGES_AUTO_RELOAD=True))
    # Extra config
    if extra_config:
        app.config.update(extra_config)

    # Blueprints
    app.register_blueprint(BLOG, url_prefix='/blog')
    app.register_blueprint(INDIVIDUAL)
    app.register_blueprint(FEEDS)

    # Other configuration
    app.context_processor(template_settings)
    app.add_template_filter(l10n_date)
    register_assets(app)
    register_pages(app)
    return app
def create_app(debug=False):
    app = Flask(__name__.split('.')[0],
                static_folder=STATIC_ROOT,
                template_folder=path.join(APPLICATION_ROOT, 'templates'))

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

    app.register_blueprint(shared_bp)
    app.register_blueprint(blog_bp, url_prefix='/blog')
    app.register_blueprint(admin_bp, url_prefix='/admin')

    register_frontend_routes(app)

    # Configure webassets environment.
    init_assets_environment(app, include_dependencies=debug, auto_build=debug)

    # Initialize SQLAlchemy connection with the application.
    db.init_app(app)

    # Add a Jinja context processor.
    app.context_processor(current_year)
    app.context_processor(current_revision)

    return app
Beispiel #10
0
def create_app():
    app = Flask(__name__, static_folder='public')

    CsrfProtect(app)

    env = os.environ.get('TOGETHER_ENV', 'dev')
    app.config.from_object('together.settings.{}Config'.format(env.capitalize()))
    app.config['ENV'] = env

    from together.models import db, migrate, login_manager
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)

    from together.meta import meta
    app.register_blueprint(meta, url_prefix='/')

    from together.api import api, json_user
    api.init_app(app)

    app.context_processor(json_user)

    from together.assets import assets_env
    assets_env.init_app(app)

    return app
Beispiel #11
0
class AppFactory(object):

    def __init__(self, config, envvar='PROJECT_SETTINGS', bind_db_object=True):
        self.app_config = config
        self.app_envvar = os.environ.get(envvar, False)
        self.bind_db_object = bind_db_object

    def get_app(self, app_module_name, **kwargs):
        self.app = Flask(app_module_name, **kwargs)
        self.app.config.from_object(self.app_config)
        self.app.config.from_envvar(self.app_envvar, silent=True)

        self._bind_extensions()
        self._register_blueprints()
        self._register_context_processors()
        self._register_template_filters()

        return self.app

    def _get_imported_stuff_by_path(self, path):
        module_name, object_name = path.rsplit('.', 1)
        module = import_string(module_name)

        return module, object_name

    def _bind_extensions(self):
        for ext_path in self.app.config.get('EXTENSIONS', []):
            module, e_name = self._get_imported_stuff_by_path(ext_path)
            if not hasattr(module, e_name):
                raise NoExtensionException('No {e_name} extension found'.format(e_name=e_name))
            ext = getattr(module, e_name)
            if getattr(ext, 'init_app', False):
                ext.init_app(self.app)
            else:
                ext(self.app)

    def _register_template_filters(self):
        for filter_path in self.app.config.get('TEMPLATE_FILTERS', []):
            module, f_name = self._get_imported_stuff_by_path(filter_path)
            if hasattr(module, f_name):
                self.app.jinja_env.filters[f_name] = getattr(module, f_name)
            else:
                raise NoTemplateFilterException('No {f_name} template filter found'.format(f_name=f_name))

    def _register_context_processors(self):
        for processor_path in self.app.config.get('CONTEXT_PROCESSORS', []):
            module, p_name = self._get_imported_stuff_by_path(processor_path)
            if hasattr(module, p_name):
                self.app.context_processor(getattr(module, p_name))
            else:
                raise NoContextProcessorException('No {cp_name} context processor found'.format(cp_name=p_name))

    def _register_blueprints(self):
        for blueprint_path in self.app.config.get('BLUEPRINTS', []):
            module, b_name = self._get_imported_stuff_by_path(blueprint_path)
            if hasattr(module, b_name):
                self.app.register_blueprint(getattr(module, b_name))
            else:
                raise NoBlueprintException('No {bp_name} blueprint found'.format(bp_name=b_name))
Beispiel #12
0
def create_app(config):

    """A factory that returns an application object from the passed config.

    The factory accepts further configuration from ENV variables. Some simple
    checks for core configuration settings are made to raise errors early
    if vital information is missing.

    """

    import os
    from flask import Flask
    from flask.ext.babel import Babel
    from flask.ext.cors import CORS
    from flask.ext.markdown import Markdown
#    from flask.ext.assets import Environment, Bundle
    from .components import api, pages
    from .components.commons import context_processors, encoders

    app_label = 'web'

    # Get the static and template folder for the passed theme
    static_folder = os.path.join('theme', 'static')
    template_folder = os.path.join('theme', 'templates')

    # Construct app and service objects
    app = Flask(app_label, template_folder=template_folder,
                static_folder=static_folder, static_url_path='/static')
    trans = Babel()
    cors = CORS(resources=r'/api/*', allow_headers='Content-Type')
#    assets = Environment()

    # Configure the app with defaults
    app.config.from_object(config)

    # Set app core services
    trans.init_app(app)
    cors.init_app(app)
#    assets.init_app(app)
    Markdown(app)

    # Register routable components
    app.register_blueprint(api.blueprint)
    app.register_blueprint(pages.blueprint)

    # Set additional jinja2 extensions
    app.jinja_env.add_extension('jinja2.ext.do')

    # Set custom context processors
    app.context_processor(context_processors.inject_app_data)

    # Set custom encoders
    app.json_encoder = encoders.JSONEncoder

    # Register webassets bundles
#    sass = Bundle('css/base.scss', filters='pyscss', output='css/base.css')
#    assets.register('sass', sass)

    return app
Beispiel #13
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(os.environ['SETTINGS'])
    register_errorhandlers(app)
    register_blueprints(app)
    register_extensions(app)
    app.context_processor(asset_path_context_processor)
    return app
Beispiel #14
0
class CreateApp(object):

    def __init__(self, cfg=BaseConfig, envvar='PROJECT_SETTINGS', bind_db=True):
        self.app_config = cfg
        self.app_envvar = envvar
        self.bind_db = bind_db

    def get_app(self, app_module_name, **kwargs):
        self.app = Flask(app_module_name, **kwargs)
        self.app.config.from_object(self.app_config)
        self.app.config.from_envvar(self.app_envvar, silent=True)
        self.app.config.from_pyfile('local_settings.py', silent=True)

        self._bind_extensions()
        self._register_blueprints()
        self._register_context_processors()
        
        #self.app.db = db
        #connection = get_connection()
        #self.app.db = connection[self.app.config['MONGO_DBNAME']]
        
        return self.app

    def _get_imported_stuff_by_path(self, path):
        mo_pa = path.split('.')
        module_name = '.'.join(mo_pa[:-1])
        objNam = mo_pa[-1]
        module = __import__(module_name, fromlist=[objNam])

        return module, objNam

    def _bind_extensions(self):
        for ext_path in self.app.config.get('EXTENSIONS', []):
            module, e_name = self._get_imported_stuff_by_path(ext_path)
            if not hasattr(module, e_name):
                raise NoExtensionException('No {e_name} extension found'.format(e_name=e_name))
            ext = getattr(module, e_name)
            if getattr(ext, 'init_app', False):
                ext.init_app(self.app)
            else:
                ext(self.app)

    def _register_context_processors(self):
        for processor_path in self.app.config.get('CONTEXT_PROCESSORS', []):
            module, p_name = self._get_imported_stuff_by_path(processor_path)
            if hasattr(module, p_name):
                self.app.context_processor(getattr(module, p_name))
            else:
                raise NoContextProcessorException('No {cp_name} context processor found'.format(cp_name=p_name))

    def _register_blueprints(self):
        for blueprint_path in self.app.config.get('BLUEPRINTS', []):
            module, b_name = self._get_imported_stuff_by_path(blueprint_path)
            if hasattr(module, b_name):
                self.app.register_blueprint(getattr(module, b_name))
            else:
                raise NoBlueprintException('No {bp_name} blueprint found'.format(bp_name=b_name))
Beispiel #15
0
def create_app(**kwargs):
    """
        create a WSGI application that can be used in the
        modules.
    """

    from flask import Flask
    from pyggi.lib.config import config
    import logging

    static_base = '/static'
    if config.has_option('general', 'static_url_base'):
        static_base = config.get('general', 'static_url_base')
    app = Flask(__name__, static_url_path=static_base)

    # get logging settings
    config_settings = dict(
        level=logging.WARNING,
        format="[%(asctime)s] %(levelname)s: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )

    if config.has_option('log', 'file'):
        config_settings['filename'] = config.get('log', 'file')

    # activate logging
    logging.basicConfig(**config_settings)

    # register modules to application. the modules come
    # from the configuration file. there is a list of
    # modules to be imported. an item in this list has the
    # form ("module:name","prefix") where name is the name of the module
    # object that should be imported
    for module_desc in config.items('modules'):
        module, prefix = module_desc
        module, attribute = module.rsplit('.', 1)

        # now we try to import the module and register it
        # in our application. otherwise ignore and continue
        try:
            _import = __import__(module, globals(), locals(), [attribute], -1)
            prefix = "" if prefix.strip('/') == "" else "/" + prefix.strip('/')
            app.register_blueprint(getattr(_import, attribute), url_prefix=prefix)
        except Exception as e:
            logging.critical("could not load module '%s': %s", module_desc[0], e)

    # register some filters
    import lib.filters
    app.jinja_env.filters['dateformat'] = lib.filters.format_datetime
    app.jinja_env.filters['diffformat'] = lib.filters.format_diff
    app.jinja_env.filters['timesince'] = lib.filters.humanize_timesince
    app.jinja_env.filters['force_unicode'] = lib.filters.force_unicode
    app.jinja_env.filters['first_line'] = lib.filters.first_line
    app.jinja_env.tests['text'] = lib.filters.is_text
    app.context_processor(lambda: dict(static_url_for=lib.filters.static_url_for))

    return app
Beispiel #16
0
def create_app(source=None, config=None):    
    app = Flask("flaskrst")
    
    # Set default config values
    app.config.setdefault('MODULES', {})
    app.config.setdefault('STYLESHEETS', [])
    app.config.setdefault('FEEDS', [])
    
    # Load config
    if config:
        app.config.from_pyfile(config)
        config_loaded = True
    # maybe there is a file declared by env
    elif 'FLASK_RST_CONFIG' in os.environ:
        app.config.from_envvar('FLASK_RST_CONFIG')
        config_loaded = True
    # no config loaded try again later after source setting
    else:
        config_loaded = False
    
    # Set source path
    if source:
        app.config['SOURCE'] = source
    elif 'FLASK_RST_SOURCE' in os.environ:
        app.config['SOURCE'] = os.environ['FLASK_RST_SOURCE']
    else:
        # Use current working directory as source
        app.config['SOURCE'] = os.getcwd()
    
    # If no config already loaded than is a config maybe in source path
    if not config_loaded:
        config_path = os.path.join(app.config['SOURCE'], 'config.py')
        app.config.from_pyfile(config_path, silent=True)
    
    # Set path of static folder
    if 'STATIC_FOLDER' in app.config:
        app.static_folder = app.config['STATIC_FOLDER']
    else:
        # Is a static folder called _static in source path?
        source_static_folder = os.path.join(app.config['SOURCE'], "_static")
        if os.path.isdir(source_static_folder):
            app.static_folder = source_static_folder
    
    # Load flask-rst modules
    manager.init_app(app)
    manager.load_from_config()

    # Add some jinja globals and context processors
    app.jinja_env.globals['date'] = date
    app.context_processor(inject_navigation)
    
    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('404.html'), 404

    return app
def create_app(config_filename):
    ''' An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/
    '''
    app = Flask(__name__)
    app.config.from_object(config_filename)
    register_errorhandlers(app)
    register_blueprints(app)
    app.context_processor(asset_path_context_processor)
    return app
Beispiel #18
0
class AppFactory(object):
    def __init__(self, config=None, envvar="PROJECT_SETTINGS", bind_db_object=True):
        self.app_config = config
        self.app_envvar = os.environ.get(envvar, False)
        self.bind_db_object = bind_db_object

    def get_app(self, app_module_name, **kwargs):
        self.app = Flask(app_module_name, **kwargs)
        if self.app_config:
            self.app.config.from_object(self.app_config)
        if self.app_envvar:
            self.app.config.from_object(self.app_envvar)

        self._bind_extensions()
        self._register_blueprints()
        self._register_context_processors()

        return self.app

    def _get_imported_stuff_by_path(self, path):
        module_name, object_name = path.rsplit(".", 1)
        module = import_string(module_name)

        return module, object_name

    def _bind_extensions(self):
        for ext_path in self.app.config.get("EXTENSIONS", []):
            module, e_name = self._get_imported_stuff_by_path(ext_path)
            if not hasattr(module, e_name):
                raise NoExtensionException("No {e_name} extension found".format(e_name=e_name))

            ext = getattr(module, e_name)
            if hasattr(ext, "init_app"):
                ext.init_app(self.app)
            elif callable(ext):
                ext(self.app)
            else:
                raise NoExtensionException("{e_name} extension has no init_app. Can't initialize".format(e_name=e_name))

    def _register_context_processors(self):
        for processor_path in self.app.config.get("CONTEXT_PROCESSORS", []):
            module, p_name = self._get_imported_stuff_by_path(processor_path)
            if hasattr(module, p_name):
                self.app.context_processor(getattr(module, p_name))
            else:
                raise NoContextProcessorException("No {cp_name} context processor found".format(cp_name=p_name))

    def _register_blueprints(self):
        for blueprint_path in self.app.config.get("BLUEPRINTS", []):
            module, b_name = self._get_imported_stuff_by_path(blueprint_path)
            if hasattr(module, b_name):
                self.app.register_blueprint(getattr(module, b_name))
            else:
                raise NoBlueprintException("No {bp_name} blueprint found".format(bp_name=b_name))
Beispiel #19
0
def create_app():
    select_default_settings()

    app = Flask(__name__)
    app.config.from_object(os.environ.get('MINIFICTION_SETTINGS'))

    default_handler.setLevel(app.config['LOGLEVEL'])
    logging.basicConfig(level=app.config['LOGLEVEL'], format=app.config['LOGFORMAT'])

    app.static_folder = app.config['STATIC_ROOT']
    app.extra_css = []
    app.extra_js = []

    if app.config['UMASK'] is not None:
        if isinstance(app.config['UMASK'], str):
            app.config['UMASK'] = int(app.config['UMASK'], 8)
        os.umask(app.config['UMASK'])

    if app.config['TESTING']:
        if not os.path.isdir(app.config['TESTING_DIRECTORY']):
            os.makedirs(app.config['TESTING_DIRECTORY'])
        elif os.listdir(app.config['TESTING_DIRECTORY']):
            raise RuntimeError('Testing directory %r is not empty' % app.config['TESTING_DIRECTORY'])

    init_bl()

    configure_user_agent(app)
    configure_i18n(app)
    configure_cache(app)
    configure_forms(app)
    configure_users(app)
    configure_error_handlers(app)
    configure_views(app)
    configure_admin_views(app)
    configure_ajax(app)
    configure_errorpages(app)
    configure_templates(app)
    if not app.config['SPHINX_DISABLED']:
        configure_search(app)
    configure_celery(app)
    configure_captcha(app)
    configure_story_voting(app)
    configure_misc(app)
    configure_development(app)
    configure_frontend(app)
    configure_sidebar(app)

    app.context_processor(templates_context)

    init_plugins(app)
    database.configure_for_app(app)

    return app
Beispiel #20
0
def create_app():
	app = Flask(__name__, instance_relative_config=True)
	app.config.from_object('app.config')
	app.config.from_pyfile('config.py', silent=True)

	# Set up application
	configure_blueprints(app)
	configure_extensions(app)

	app.context_processor(context_processor)

	return app
Beispiel #21
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    cache.init_app(app)
    db.init_app(app)
    db.app = app
    login_manager.init_app(app)
    mail.init_app(app)
    setup_themes(app)
    Mobility(app)

    from .utils.filters import register_filters
    register_filters(app)

    from .utils.processors import utility_processor 
    app.context_processor(utility_processor)

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

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

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

    from .admins import admin
    admin.init_app(app)

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(app.static_folder, 'favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

    @app.route('/robots.txt')
    def robotstxt():
        return send_from_directory(app.static_folder, 'robots.txt')

    # 暂时解决因Gunicorn中引发ERROR 11而无法正常提交的问题
    #@app.teardown_request
    #def teardown_request(response_or_exc):
    #    if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
    #        try:
    #            db.session.commit()
    #        except:
    #            db.session.rollback()
    #    db.session.remove()

    return app
Beispiel #22
0
def make_app(routes):
    app = Flask(
        __name__, template_folder=os.environ['TEMPLATE_DIR']
    )
    app.config['FREEZER_DESTINATION'] = os.path.join(ROOT_PATH, 'output')
    app.config['FREEZER_DESTINATION_IGNORE'] = [
        os.path.join(ROOT_PATH, 'build/css/*'),
        os.path.join(ROOT_PATH, 'build/js/*')
    ]
    app.context_processor(context_processors.environment.inject_environment)

    for route in routes:
        app.add_url_rule(*route)

    return app
Beispiel #23
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    db.init_app(app)
    db.app = app

    if not app.config['TESTING']:
        configure_custom_settings(app)
    config[config_name].init_app(app)

    thumbnail.init_app(app)
    babel.init_app(app)
    cache.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    setup_themes(app)
    Mobility(app)

    from .utils.filters import register_filters
    register_filters(app)

    from .utils.processors import utility_processor
    app.context_processor(utility_processor)

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

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

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

    from .admins import admin
    admin.init_app(app)

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(app.static_folder, 'favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

    @app.route('/robots.txt')
    def robotstxt():
        return send_from_directory(app.static_folder, 'robots.txt')

    return app
def create_app(config=None):
    ''' An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/
    '''
    app = Flask(__name__)

    if not config:
        config = os.environ.get('SETTINGS', 'application.config.Config')

    app.config.from_object(config)

    register_errorhandlers(app)
    register_blueprints(app)
    app.context_processor(asset_path_context_processor)
    register_extensions(app)
    register_filters(app)
    return app
Beispiel #25
0
def create_app(config_name):
    app = Flask(__name__)
    app.config['APPENV'] = str(get_appconfig())
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    cache.init_app(app)
    db.init_app(app)
    db.app = app
    login_manager.init_app(app)
    mail.init_app(app)
    setup_themes(app)
    Mobility(app)

    from .utils.filters import register_filters
    register_filters(app)

    from .utils.processors import utility_processor 
    app.context_processor(utility_processor)

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

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

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

    from .admins import admin
    admin.init_app(app)

    # 暂时解决因Gunicorn中引发ERROR 11而无法正常提交的问题
    @app.teardown_request
    def teardown_request(response_or_exc):
        if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
            try:
                db.session.commit()
            except:
                db.session.rollback()
        db.session.remove()

    return app
Beispiel #26
0
def create_app(config):
    app = Flask('muzyczne-bitwy')
    app.config.from_pyfile(config)

    from application.auth import auth
    auth.init_app(app)

    from application.database import db
    db.init_app(app)

    from application.util import jinja2_utilities
    app.context_processor(jinja2_utilities)

    from application.views import index, songs, phases, battles
    app.register_blueprint(index)
    app.register_blueprint(songs)
    app.register_blueprint(phases)
    app.register_blueprint(battles)

    return app
Beispiel #27
0
def make_app(project_dir, url_prefix):
    app_args = {}
    
    app = Flask(__name__, template_folder='templates', **app_args)
    app.config.from_object(app_settings)

    app.url_map.strict_slashes = False
    app.config.update(HOME_DIR=project_dir)

    # Setup the url_prefix for mounting by stripping off the slash
    # that's on the URL.
    options = {'url_prefix': url_prefix}
    if url_prefix.endswith('/'):
        options['url_prefix'] = url_prefix[:-1]
    views.blueprint.register(app, options)
    app.context_processor(context_processor)

    app.errorhandler(404)(handle404)
    app.errorhandler(500)(handle500)

    return app
Beispiel #28
0
def create_app():
    app = Flask(
        __name__,
        template_folder = template_folder,
        static_url_path = '/static',
        static_folder   = '../static',
    )

    # Configure app based on .env file
    app.config.from_object(settings)

    # Automatically inject stuff into the context
    app.context_processor(inject_publication)

    # Add various items to the template globals
    app.jinja_env.globals.update({
        'ENVIRONMENT'       : settings.ENVIRONMENT,
        'DEBUG'             : settings.DEBUG,
        'READER_TOKEN'      : settings.CONTENT_API_TOKEN,
        'CONTENT_API_ROOT'  : settings.CONTENT_API_ROOT,
    })
    app.jinja_env.globals.update(staticURL=staticURL)
    app.jinja_env.globals.update(mediaURL=mediaURL)

    app.jinja_env.filters['toItemSize']     = toItemSize
    app.jinja_env.filters['renderBlock']    = renderBlock
    app.jinja_env.filters['contentPreview'] = contentPreview
    app.jinja_env.filters['renderCover']    = renderCover
    app.jinja_env.filters['asModel']        = asModel
    app.jinja_env.filters['slugify']        = slugify

    # Register views and routes
    PublicationView.register(app, route_base='/')

    # Activate hyperdrive if enabled
    if settings.HYPERDRIVE:
        from hyperdrive.main import hyperdrive
        app.register_blueprint(hyperdrive, url_prefix="/_hyperdrive")

    return app
def create_app(db_name=None):
    app = Flask(__name__)
    app.config.from_object(config)
    if db_name:
        config.MONGO_DATABASE = db_name

    Admin(app)
    Engine(app)
    mongo, db = HapPyMongo(config)
    app.permanent_session_lifetime = timedelta(hours=2)
    auth = CloudAuth(app, db)

    custom_filters = {
        name: function for name, function in getmembers(template_filters)
        if isfunction(function)
    }
    app.jinja_env.filters.update(custom_filters)
    app.context_processor(template_functions.utility_processor)

    @app.before_first_request
    def logger():
        if not app.debug:
            app.logger.addHandler(logging.StreamHandler())
            app.logger.setLevel(logging.INFO)

    @app.before_request
    def before_request():
        g.db, g.auth = db, auth

    defaults.application_initialize(db, app)
    views.ProductsView.register(app)
    views.MiscView.register(app)
    views.FeedbackView.register(app)
    views.GlobalManageView.register(app)

    if db_name:
        return app, db
    else:
        return app
Beispiel #30
0
def create_app():
    app = Flask(__name__)

    for k, v in os.environ.iteritems():
        if k.startswith(CONFIG_KEY_PREFIX):
            app.config[k[len(CONFIG_KEY_PREFIX):]] = v

    if app.config['DEBUG']:
        from werkzeug.debug import DebuggedApplication
        app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
        app.debug = True

    app.url_map.converters['regex'] = utils.RegexConverter
    database.init_app(app)

    if 'NO_INIT_DB' not in app.config:
        from deployer.applications import models
        models.Base.metadata.create_all(app.engine)

        from deployer.hosts import models
        models.Base.metadata.create_all(app.engine)

        from deployer.routing import models
        models.Base.metadata.create_all(app.engine)

    app.register_blueprint(_old.views)
    app.register_blueprint(hosts.views, url_prefix='/hosts')
    app.register_blueprint(applications.views, url_prefix='/apps')

    app.context_processor(context_processors.register_functions)

    for name in filters.__all__:
        app.jinja_env.filters[name] = getattr(filters, name)

    BuildsUpdater(app).start(10, now=True)
    RoutesUpdater(app).start(10, now=True)

    return app