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
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
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
def create_app(): app = Flask(__name__) app.config.from_object(DefaultConfig) bootstrap.init_app(app) db.init_app(app) app.site = {} def site_context_processor(): return dict(site=app.site) app.context_processor(site_context_processor) login_manager.init_app(app) from app.web import web app.register_blueprint(web) from app.admin import admin app.register_blueprint(admin, url_prefix='/admin') from app.api import api app.register_blueprint(api, url_prefix="/api") template_filters(app) login_manager.login_view = "admin.login" login_manager.login_message = "请先登录!!!" return app
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
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
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
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)
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) # app.secret_key = "SESSION_SECRET_KEY" config[config_name].init_app(app) bootstrap.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) babel.init_app(app) qiniu.init_app(app) # pageDown.init_app(app) # babel = Babel(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') # admin from .admin import admin admin.init_app(app) from .utils.processors import utility_processor app.context_processor(utility_processor) return app
def init_app(app: Flask) -> None: app.add_template_filter(date) app.add_template_filter(make_slugify, 'slugify') app.add_template_filter(render_markdown, 'render') app.add_template_filter(text_part, 'textpart') app.context_processor(get_current_time) app.context_processor(blog_objects)
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( 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)
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
def create_app(settings_override=None): """ Create a Flask application using the app factory pattern. :param settings_override: Override settings :return: Flask app """ app = Flask(__name__, instance_relative_config=True) def disable_varnish(response): response.cache_control.private = True return response app.after_request(disable_varnish) SSLify(app, skips=['healthcheck']) gunicorn_logger = logging.getLogger('gunicorn.error') app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) app.config.from_object('config.settings') if 'GOOGLE_CLIENT_ID' in app.config: setup_authentication(app) app.register_blueprint(page) plugins = {} for plugin in app.config['ENABLED_PLUGINS']: module = importlib.import_module(f'dashboard.plugins.{plugin}') app.register_blueprint(module.plugin, url_prefix=module.base_path) plugins[plugin] = {'tab_name': module.tab_name} app.airflow_data_provider = AirflowDBDataProvider( app.config, app.logger, MySQLClient(app.config, app.logger)) app.influx_data_provider = InfluxDBData( app.config, app.logger) if app.config.get('INFLUXDB_HOST') else None app.prometheus_data_provider = PrometheusData( app.config, app.logger) if app.config.get('PROMETHEUS_HOST') else None # Reading tables configs, setting variable to `None` if file is not present tables = get_yaml_file_content(TABLES_PATH) app.table_data_provider = TableDataProvider( app.airflow_data_provider, app.influx_data_provider, app.prometheus_data_provider, tables, app.logger, app.config) if tables else None app.etl_data_provider = EtlDataProvider(app.config, app.airflow_data_provider, app.table_data_provider) app.async_request_executor = ThreadPoolExecutor(max_workers=3) app.cache = SimpleCache() if app.debug: app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True) app.context_processor(lambda: {'now': datetime.now(), 'plugins': plugins}) return app
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
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__) 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
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
def create_app(): app = Flask(__name__) app.config.from_object(defaultConfig) bootstrap.init_app(app) app.site = {} def site_context_processor(): return dict(site=app.site) app.context_processor(site_context_processor) create_path(app) loadConfigCustom(app) @app.before_request def _request_check_start(): request_check_start(app) from appdc.web import web from appdc.api import api from appdc.log import init_logging from appdc.api.userAuth import init as userAuthInit userAuthInit(app) app.register_blueprint(web) app.register_blueprint(api, url_prefix="/api") init_logging(app) return app
def create_app(config_name=Config): load_dotenv() app = Flask(__name__.split('.')[0]) app.config.from_object(config_name) app.redis = redis.from_url(app.config['REDIS_URL']) app.config['SITEMAP_VIEW_DECORATORS'] = [load_page] # Don't cache js bundles if in development if app.config['ENV'] == 'development': app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Register before requests mixins prior to those that are inside extensions register_extensions(app) register_url_rules(app) register_blueprints(app) register_errorhandlers(app) app.shell_context_processor( lambda: { 'db': db, 'User': main.models.User, 'CourseColor': calendar.models.CourseColor, 'CourseFilter': calendar.models.CourseFilter, 'CourseIdentifier': calendar.models.CourseIdentifier }) app.context_processor(inject_date) return app
class AppFactory(object): def __init__(self, config=None, envvar='PROJECT_SETTINGS'): self.app_config = config self.app_envvar = os.environ.get(envvar, 'settings.DevelopmentConfig') 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))
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))
def init(): app = Flask(__name__, static_folder="./app", static_url_path="/fras/app/") app.secret_key = C.random_str(size=30) app.context_processor(C.inject_user) app.before_request(C.db_connect) app.after_request(C.db_close) # Add custom filters app.add_template_filter(C.jinja2_filter_datefmt, "datefmt") # Initialize uploads folder uploads = os.path.join(app.root_path, "uploads") app.config['UPLOAD_FOLDER'] = uploads Path(uploads).mkdir(parents=True, exist_ok=True) # Register views V.user_blueprint.add_url_rule('/home', view_func=V.home, methods=['GET']) V.user_blueprint.add_url_rule('/login', view_func=V.login, methods=['POST']) V.user_blueprint.add_url_rule('/logout', view_func=V.logout, methods=['GET', 'POST']) V.user_blueprint.add_url_rule('/current_user', view_func=V.current_user, methods=['GET']) V.user_blueprint.add_url_rule('/users_upload', view_func=V.users_upload, methods=['POST']) V.face_blueprint.add_url_rule('/kface_bulk_add', view_func=V.kface_bulk_add, methods=['POST']) V.face_blueprint.add_url_rule('/kface', view_func=V.kface_find, methods=['POST']) V.face_blueprint.add_url_rule('/kface/<int:id>', view_func=V.kface_view, methods=['GET']) V.face_blueprint.add_url_rule('/kface_save', view_func=V.kface_save, methods=['POST']) V.face_blueprint.add_url_rule('/kface_delete', view_func=V.kface_delete, methods=['POST']) V.attendance_blueprint.add_url_rule('/mark_attendance', view_func=V.mark_attendance, methods=['POST']) V.attendance_blueprint.add_url_rule('/all_attendance', view_func=V.all_attendance, methods=['GET']) app.register_blueprint(V.user_blueprint, url_prefix='/fras/app') app.register_blueprint(V.face_blueprint, url_prefix='/fras/app') app.register_blueprint(V.attendance_blueprint, url_prefix='/fras/app') return app
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
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
def create_app(): app = Flask(__name__) # 只接受此app发送的信号 @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user if hasattr(current_user, 'id'): if current_user.email == '*****@*****.**': identity.provides.add(RoleNeed('admin')) identity.provides.add(UserNeed(current_user.id)) if hasattr(current_user, 'roles'): for role in current_user.roles: identity.provides.add(RoleNeed(role.name)) if hasattr(current_user, 'articles'): for post in current_user.articles: identity.provides.add(EditBlogPostNeed(post.id)) app.config.from_object(config) db.init_app(app) db.app = app socketio.init_app(app) csrf.init_app(app) cache.init_app(app) principal.init_app(app) login_manager.init_app(app) from .admin.views import admin admin.init_app(app) from .utils.filters import register_filters register_filters(app) from .utils.processors import utility_processor app.context_processor(utility_processor) from .account import account app.register_blueprint(account) from .api import api app.register_blueprint(api) from .chatroom import chartroom app.register_blueprint(chartroom) from .comment import comment app.register_blueprint(comment) from .main import main app.register_blueprint(main) @app.route('/favicon.ico') def favicon(): return send_from_directory(app.static_folder, 'favicon.ico', mimetype='images/vnd.microsoft.icon') @app.route('/robots.txt') def robotstxt(): return send_from_directory(app.static_folder, 'robots.txt') @app.errorhandler(PermissionDenied) def permission_denied(error): return 'sorry permission denied ' db.create_all() return app
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
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 = [] app.session_interface = LazySecureCookieSessionInterface() 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
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))
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
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(): app = Flask(__name__) # Configuration sys.path.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) import default_config app.config.from_object(default_config) import config app.config.from_object(config) # Logging from webserver.loggers import init_loggers init_loggers(app) # Database connection from db import init_db_engine init_db_engine(app.config['SQLALCHEMY_DATABASE_URI']) # Extensions from flask_uuid import FlaskUUID FlaskUUID(app) # MusicBrainz import musicbrainzngs from db import SCHEMA_VERSION musicbrainzngs.set_useragent(app.config['MUSICBRAINZ_USERAGENT'], SCHEMA_VERSION) if app.config['MUSICBRAINZ_HOSTNAME']: musicbrainzngs.set_hostname(app.config['MUSICBRAINZ_HOSTNAME']) # OAuth from webserver.login import login_manager, provider login_manager.init_app(app) provider.init(app.config['MUSICBRAINZ_CLIENT_ID'], app.config['MUSICBRAINZ_CLIENT_SECRET']) # Error handling from webserver.errors import init_error_handlers init_error_handlers(app) # Static files import static_manager static_manager.read_manifest() # Template utilities app.jinja_env.add_extension('jinja2.ext.do') from webserver import utils app.jinja_env.filters['date'] = utils.reformat_date app.jinja_env.filters['datetime'] = utils.reformat_datetime app.context_processor( lambda: dict(get_static_path=static_manager.get_static_path)) _register_blueprints(app) 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
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))
def create_app(): _config_log() app = Flask(__name__) app.config.from_object(config) app.context_processor(_inject_variables) _init_plugins(app) add_routes(app) _config_jinja(app) return app
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
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
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
def create_app(config_filename="config"): """Flask application factory. This is the flask application factory for this project. It loads the other submodules used to runs the collectives website. It also creates the blueprins and init apps. :param config_filename: name of the application config file. :type config_filename: string :return: A flask application for collectives :rtype: :py:class:`flask.Flask` """ app = Flask(__name__, instance_relative_config=True) # Config options - Make sure you created a 'config.py' file. app.config.from_object(config_filename) app.config.from_pyfile("config.py") # To get one variable, tape app.config['MY_VARIABLE'] # Initialize plugins models.db.init_app(app) auth.login_manager.init_app(app) # app is a Flask object api.marshmallow.init_app(app) profile.images.init_app(app) extranet.api.init_app(app) app.context_processor(context_processor.helpers_processor) _migrate = Migrate(app, models.db) with app.app_context(): # Register blueprints app.register_blueprint(root.blueprint) app.register_blueprint(profile.blueprint) app.register_blueprint(api.blueprint) app.register_blueprint(administration.blueprint) app.register_blueprint(auth.blueprint) app.register_blueprint(event.blueprint) # print(app.url_map) forms.configure_forms(app) forms.csrf.init_app(app) # Initialize DB # models.db.create_all() # Create admin user auth.init_admin(app) init.activity_types(app) return app
def __init__(self): template_path = os.path.join(APP_DIR, "app/templates") static_path = os.path.join(APP_DIR, "app/static") flask_app = Flask(__name__, static_folder=static_path, template_folder=template_path) self.__flask_app = flask_app flask_app.secret_key = "\x81\xb6\xcc\xbdep\xff\\\xfbu\xec~R\xb8S\x12\xddm0\x0e\xdc\xdc\x07\xee" babel = Babel(flask_app) Bower(flask_app) flask_app.before_request(self.__before_request) flask_app.context_processor(self.__inject_locale_info) self.__login_manager = flask_login.LoginManager() self.__login_manager.init_app(flask_app) main_controller = app.controllers.main.MainController( self.__get_locale) flask_app.add_url_rule('/', view_func=main_controller.root) flask_app.add_url_rule('/<locale>', view_func=main_controller.index) flask_app.add_url_rule('/datasets/', view_func=main_controller.datasets) # self.add_url_rule('/datasets/', fget=main_controller.datasets) # flask_app.add_url_rule('/kernels/', view_func=main_controller.kernels) self.add_url_rule('/kernels/', fget=main_controller.kernels) ds_factory = app.domain.dataset.DatasetFactory() ds_mapper = app.domain.dataset.DatasetMapper(DATASETS_PATH, ds_factory) ds_controller = app.controllers.dataset.DatasetController( ds_mapper, DATASETS_PATH) self.add_url_rule('/datasets/list/', fget=ds_controller.list) flask_app.add_url_rule('/storage/<path:ds_path>/', view_func=ds_controller.upload, methods=['POST']) flask_app.config['DEBUG'] = DEBUG flask_app.config['BABEL_DEFAULT_LOCALE'] = settings.DEFAULT_LOCALE flask_app.config[ 'BOWER_COMPONENTS_ROOT'] = 'app/static/bower_components' flask_app.config['MAX_CONTENT_LENGTH'] = settings.MAX_CONTENT_LENGTH wsgi_container = WSGIContainer(flask_app) # tornado settings handlers = [ (r".*", FallbackHandler, dict(fallback=wsgi_container)), ] s = dict(xsrf_cookies=False, cookie_secret="11oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=", debug=DEBUG) tornado.web.Application.__init__(self, handlers, **s)
def configured_app(): app = Flask(__name__) app.register_blueprint(public_bp) app.register_blueprint(user_bp) app.register_blueprint(weibo_bp) app.secret_key = secret_key SQLModel.init_db() app.errorhandler(404)(error_view) app.template_filter('formatted_time')(formatted_time) app.context_processor(current_time) return app
def register(app: Flask): """Register the filters and context processors for jinja""" app.jinja_env.filters["relative_date"] = relative_date app.jinja_env.filters["is_import_file"] = is_import_file app.jinja_env.filters["chained_object_links_by_date"] = chained_object_links_by_date app.jinja_env.filters["badge_color"] = badge_color app.jinja_env.filters["badge_display"] = badge_display app.jinja_env.filters["filter_display"] = filter_display app.jinja_env.filters["transition_color"] = transition_color app.jinja_env.filters["template_highlight"] = template_highlight app.jinja_env.filters["filename"] = filename app.jinja_env.filters["pluralize"] = pluralize app.context_processor(query)
def create_app(config_object="registry.settings"): """Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/. :param config_object: The configuration object to use. """ app = Flask(__name__.split(".")[0]) app.config.from_object(config_object) app.context_processor(template_globals) register_extensions(app) register_blueprints(app) register_commands(app) configure_logger(app) return app
def build_flask_app(use_local_db): """ Build and initialize the flask app. """ app = Flask(__name__) app.config['DEBUG'] = DEBUG # Set the log level for the super logger logger.set_log_level(LOG_LEVEL) # Secret key used by Flask to sign cookies. app.config['SECRET_KEY'] = FLASK_SECRET # Cache all static files for 1 year by default. app.config['SEND_FILE_MAX_AGE_DEFAULT'] = ONE_YEAR if use_local_db: logger.info('app', 'Loading local user database...') app.config['SQLALCHEMY_DATABASE_URI'] = LOCAL_DB_URI else: logger.info('app', 'Loading remote user database...') app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_RECORD_QUERIES'] = True # Initialize SQLAlchemy and integrate it with the Flask instance DB.init_app(app) app.register_blueprint(blueprint) # Enable login management login_manager.init_app(app) # Enable WebSocket integration socketio.init_app(app) # Enable gzip compression of static assets Compress().init_app(app) # Enable indefinite caching of static assets based on hash values CacheBuster(config=STATIC_CACHE_CONFIG).init_app(app) # Enable the Flask debug toolbar ONLY if debug mode is enabled debug_toolbar = DebugToolbarExtension() debug_toolbar.init_app(app) # Inject certain constants defined in 'inject_constants' for Jinja processing app.context_processor(inject_constants) return app
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
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(env): """Application factory.""" logging.basicConfig( level=logging.INFO, format="[%(asctime)s] [sev %(levelno)s] [%(levelname)s] [%(name)s]> %(message)s", datefmt="%a, %d %b %Y %H:%M:%S", ) if env == EnvConfig.TESTING.value: logging.getLogger("shhh").setLevel(logging.CRITICAL) logging.getLogger("apscheduler").setLevel(logging.CRITICAL) logging.getLogger("tasks").setLevel(logging.CRITICAL) app = Flask(__name__) configurations = { EnvConfig.TESTING.value: "shhh.config.TestConfig", EnvConfig.DEV_LOCAL.value: "shhh.config.DefaultConfig", EnvConfig.DEV_DOCKER.value: "shhh.config.DockerConfig", EnvConfig.HEROKU.value: "shhh.config.HerokuConfig", EnvConfig.PRODUCTION.value: "shhh.config.ProductionConfig", } app.config.from_object(configurations.get(env, "shhh.config.ProductionConfig")) register_extensions(app) with app.app_context(): register_blueprints(app) db.create_all() try: scheduler.start() except SchedulerAlreadyRunningError: pass assets.manifest = False assets.cache = False try: compile_assets(assets) except RegisterError: pass app.context_processor(inject_global_vars) app.after_request(optimize_response) app.after_request(security_headers) app.register_error_handler(HTTPStatus.NOT_FOUND.value, not_found_error) app.register_error_handler(HTTPStatus.INTERNAL_SERVER_ERROR.value, internal_server_error) 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
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
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
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
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
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