def app_init(app): lisaa_rajapinta(JoukkueLista, "/joukkue") lisaa_rajapinta(JoukkueApi, "/joukkue/<int:joukkue_id>") with app.app_context(): CHARSET = app.config['CHARSET'] app.register_blueprint(bp, url_prefix="/joukkue")
def init_app(): # 初始化app # we still need those global variables during request import os import api import json import mimetypes import common.error current_app.before_request(init_global_variables) @current_app.errorhandler(common.error.ApiError) def error_handler(error): return json.dumps(error.data), 400 @current_app.route('/', defaults={'filename': 'home'}) @current_app.route('/<path:filename>') def send_static_files(filename): if os.path.isfile(os.path.join('static', filename)): pass if os.path.isfile(os.path.join('static', filename + '.html')): filename += '.html' if os.path.isfile(os.path.join('static', filename, 'pre.html')): filename += "/pre.html" resp = current_app.send_static_file(filename) resp.mimetype = mimetypes.guess_type(filename)[0] return resp current_app.register_blueprint(api.get_blueprint(), url_prefix="/api")
def create_app(config=None): app = Flask(__name__) app.secret_key = os.urandom(16) if config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.from_mapping(config) with app.app_context(): if CWEBP_PATH is not None: app.logger.warning("webp enabled, quality: %d, preset: %s" % (app.config['WEBP_QUALITY'], app.config['WEBP_PRESET'])) app.config['WEBP'] = True else: app.config['WEBP'] = False app.logger.warning("default sorted by %s order%s" % (app.config['SORT'], ", descending" if app.config['REVERSE'] else "")) app.repos = [ Repo(dirname, app) for dirname in app.config['DIRECTORIES']] for e in app.repos: app.logger.warning("Directory %s: %d archvies loaded." % (e.dirname, len(e.comics))) app.register_blueprint(cwebviewer_pages) @app.template_filter('strip_path') def strip_path(s, subdir): return os.path.relpath(s, subdir) @app.context_processor def inject_config(): return dict(basename=os.path.basename, islice=islice, app=app) return app
def create_app(debug=False): """Create an application context with blueprints.""" app = Flask(__name__, static_folder='./resources') app.config['SECRET_KEY'] = 'RYVl4Fg3n1JLDaxWyr1m' app.config['MONGO_DBNAME'] = 'chirp' app.config['USERS_COLLECTION'] = 'accounts' app.config['MONITORS_COLLECTION'] = 'monitors' app.config['ARTICLES_COLLECTION'] = 'articles' app.config['GLOBAL_COLLECTION'] = 'global' login_manager.init_app(app) mongo.init_app(app) app.config.update( CELERY_BROKER_URL='redis://localhost:6379', CELERY_RESULT_BACKEND='redis://localhost:6379', CELERYBEAT_SCHEDULE={ # 'heartbeat': { # 'task': 'heartbeat', # 'schedule': crontab(minute='*') # }, 'process_all_rss': { 'task': 'process_all_rss', 'schedule': crontab(minute='*/15') } }) celery.conf.update(app.config) from .core import core as core_blueprint app.register_blueprint(core_blueprint) app.register_error_handler(404, page_not_found) app.register_error_handler(500, server_error) return app
def init_blueprints(): """Register blueprints on the app. Walk the views directory and programmatically try to load .py files as modules. Once loaded, look for a blueprint declaration and register it if present. """ current_app.logger.info('Initialize blueprints') root_dir = os.path.dirname(os.path.dirname(__file__)) view_dir = os.path.join(root_dir, 'views') for root, dirs, files in os.walk(view_dir): basename = os.path.basename(root) if basename == 'views': # Don't forget any files in emol/views itself module_base = 'emol.views' else: # emol/views/foo module_base = 'emol.views.{}'.format(basename) for file_ in files: if not file_.endswith('.py') or '__init__' in file_: continue module = '{}.{}'.format(module_base, os.path.splitext(file_)[0]) mod = import_module(module) if mod is None: continue blueprint = getattr(mod, 'BLUEPRINT', None) if blueprint is None: continue current_app.register_blueprint(blueprint)
def init_app(app): with app.app_context(): app.logger.addHandler(FlashHandler()) app.config.setdefault("DEBUG", True) app.register_blueprint(bp, url_prefix="/admin")
def init_app(): # we still need those global varibales during request import os import api import json import mimetypes import common.error current_app.before_request(init_global_variables) @current_app.errorhandler(common.error.ApiError) def error_handler(error): return json.dumps(error.data), 400 @current_app.route('/', defaults={'filename': 'index'}) @current_app.route('/<filename>') def send_static_files(filename): if not os.path.splitext(filename)[1]: filename += ".html" resp = current_app.send_static_file(filename) resp.mimetype = mimetypes.guess_type(filename)[0] return resp current_app.register_blueprint(api.get_blueprint(), url_prefix="/api")
def init_themes( self, app, loaders=None, app_identifier=None, manager_cls=None, theme_url_prefix="/_themes", static_folder=None ): """This sets up the theme infrastructure by adding a `ThemeManager` to the given app and registering the module/blueprint containing the views and templates needed. :param app: The `~flask.Flask` instance to set up themes for. :param loaders: An iterable of loaders to use. It defaults to `packaged_themes_loader` and `theme_paths_loader`. :param app_identifier: The application identifier to use. If not given, it defaults to the app's import name. :param manager_cls: If you need a custom manager class, you can pass it in here. :param theme_url_prefix: The prefix to use for the URLs on the themes module. (Defaults to ``/_themes``.) """ if app_identifier is None: app_identifier = app.import_name if manager_cls is None: manager_cls = ThemeManager manager_cls(app, app_identifier, loaders=loaders, static_folder=static_folder) app.jinja_env.globals["theme"] = global_theme_template app.jinja_env.globals["theme_static"] = global_theme_static app.jinja_env.globals["theme_get_info"] = global_theme_get_info if static_folder: themes_blueprint.static_folder = static_folder themes_blueprint.static_url_path = app.static_url_path + theme_url_prefix else: themes_blueprint.url_prefix = theme_url_prefix themes_blueprint.add_url_rule("/<themeid>/<path:filename>", "static", view_func=static) app.register_blueprint(themes_blueprint)
def create_app(debug=False, simulate=False): """Create an application context with blueprints.""" app = Flask(__name__, static_folder='./resources') app.config['SECRET_KEY'] = 'iqR2cYJp93PuuO8VbK1Z' app.config['MONGO_DBNAME'] = 'cloud_cafe' app.config['BREWS_COLLECTION'] = 'brews' app.config['HISTORY_COLLECTION'] = 'history' app.config['INVENTORY_COLLECTION'] = 'inventory' app.config['PROFILE_COLLECTION'] = 'profiles' app.config['USERS_COLLECTION'] = 'accounts' app.config['SIMULATE_ROAST'] = simulate app.config['MONGO_URI'] = os.environ.get('MONGO_URI') app.config['REDIS_HOST'] = os.environ.get('REDIS_HOST') app.redis = Redis(host='redis') login_manager.init_app(app) mongo.init_app(app) sio.init_app(app) from .core import core as core_blueprint app.register_blueprint(core_blueprint) if simulate: ht.set_simulate(True) return app
def __init__(self, active, specter): if not hasattr(self, "id"): raise Exception(f"Service {self.__class__} needs ID") if not hasattr(self, "name"): raise Exception(f"Service {self.__class__} needs name") self.active = active self.specter = specter if hasattr(self.__class__, "blueprint_module"): import_name = self.blueprint_module else: import_name = f"cryptoadvance.specter.services.{self.id}.service" if self.has_blueprint: self.__class__.blueprint = Blueprint( f"{self.id}_endpoint", import_name, template_folder=get_template_static_folder("templates"), static_folder=get_template_static_folder("static"), ) def inject_stuff(): """Can be used in all jinja2 templates""" return dict(specter=app.specter, service=self) self.__class__.blueprint.context_processor(inject_stuff) # Import the controller for this service if hasattr(self.__class__, "blueprint_module"): controller_module = self.blueprint_module else: controller_module = ( f"cryptoadvance.specter.services.{self.id}.controller") import_module(controller_module) app.register_blueprint(self.__class__.blueprint, url_prefix=f"/svc/{self.id}")
def wrapper(*args, **kwargs): instance = obj(*args, **kwargs) metadata = get_metadata_storage() blueprints = get_blueprints_storage() api_prefix = current_app.config.get('RESTLY_API_PREFIX').strip('/') if version not in blueprints.keys(): bp = Blueprint('v%d' % version, __name__, url_prefix='/%s/v%d/' % (api_prefix, version)) blueprints.set(version, bp) for key, value in metadata.get(obj.__name__, {}).items(): route = _build_route(obj, value['path']) rule_name = _build_rule_name(obj, value['func'].__name__) view = _view_factory(instance, obj, value['func'], value['serialize']) blueprints.get(version).add_url_rule( route, rule_name, view, methods=[value['method']], ) current_app.register_blueprint(blueprints.get(version)) return instance
def app_init(app): r""" Alustaa kirjautumiseen tarvittavaa shittiä """ login_manager.init_app(app) login_manager.login_view = "kirjautuminen.kirjautumissivu" lisaa_rajapinta(KirjautumisApi, "/kirjaudu") with app.app_context(): app.register_blueprint(bp)
def init_app(app): media_url = app.config.get('THUMBNAIL_MEDIA_URL', '/asset') if media_url[0] != "/": media_url = u"/%s" % media_url app.register_blueprint(bp) app.jinja_env.filters.update(asset_img=asset_img)
def setUp(self): self.application = create_app('config.LoadedConfig') self.ctx = self.application.app_context() self.ctx.push() current_app.config.from_object(config.LoadedConfig) current_app.register_blueprint(ga4gh) current_app.testing = True self.tester = current_app.test_client()
def __init__(self, name, module, callback): self.name = name self.trello = module self.callback = callback self.blueprint = Blueprint(name, __name__) self.blueprint.route('/' + name, methods=['HEAD', 'POST'])(self.webhook) current_app.register_blueprint(self.blueprint)
def seed_endpoints(): from auth.drivers.root import bp current_app.register_blueprint( bp, url_prefix=current_app.config["endpoints"]["root"]) if "oidc" in current_app.config: from auth.drivers.oidc import bp current_app.register_blueprint( bp, url_prefix=current_app.config["endpoints"]["oidc"])
def setup(self): #Import the blueprint defined in views.py from .views import blueprint #Register the blueprint with the PyBossa app instance. #This will allow us to route to views within our plugin. #The url_prefix parameter passed while registering denotes the prefix in the URL to route views within this folder. #You can give any prefix of your choice. app.register_blueprint(blueprint, url_prefix="/prefix")
def register_blueprint_for_ext(cls, clazz, ext): if not clazz.has_blueprint: return if hasattr(clazz, "blueprint_module"): import_name = clazz.blueprint_module controller_module = clazz.blueprint_module else: # The import_name helps to locate the root_path for the blueprint import_name = f"cryptoadvance.specter.services.{clazz.id}.service" controller_module = f"cryptoadvance.specter.services.{clazz.id}.controller" clazz.blueprint = Blueprint( f"{clazz.id}_endpoint", import_name, template_folder=get_template_static_folder("templates"), static_folder=get_template_static_folder("static"), ) def inject_stuff(): """Can be used in all jinja2 templates""" return dict(specter=app.specter, service=ext) clazz.blueprint.context_processor(inject_stuff) # Import the controller for this service logger.info(f" Loading Controller {controller_module}") controller_module = import_module(controller_module) # finally register the blueprint if clazz.isolated_client: ext_prefix = app.config["ISOLATED_CLIENT_EXT_URL_PREFIX"] else: ext_prefix = app.config["EXT_URL_PREFIX"] try: app.register_blueprint(clazz.blueprint, url_prefix=f"{ext_prefix}/{clazz.id}") logger.info(f" Mounted {clazz.id} to {ext_prefix}/{clazz.id}") if (app.testing and len([ vf for vf in app.view_functions if vf.startswith(clazz.id) ]) <= 1): # the swan-static one # Yet again that nasty workaround which has been described in the archblog. # The easy variant can be found in server.py # The good news is, that we'll only do that for testing import importlib logger.info("Reloading Extension controller") importlib.reload(controller_module) app.register_blueprint(clazz.blueprint, url_prefix=f"{ext_prefix}/{clazz.id}") except AssertionError as e: if str(e).startswith("A name collision"): raise SpecterError(f""" There is a name collision for the {clazz.blueprint.name}. \n This is probably because you're running in DevelopementConfig and configured the extension at the same time in the EXTENSION_LIST which currently loks like this: {app.config['EXTENSION_LIST']}) """)
def setup(self, app): print('setup', __plugin__) current_app.register_blueprint(empty_room, url_prefix='/empty-room') this_term = current_app.school_time.term_string classroom_dict = redis_store.get('empty_room:' + this_term) if classroom_dict is None: print('getting _classroom_dict') classroom_dict = self.get_classroom_dict(this_term) redis_store.set('empty_room:' + this_term, classroom_dict)
def blueprint(blueprint, app, **kwargs): """Register flask blueprint. :param blueprint: blueprint instance :param app: flask app instance """ blueprint.kwargs = kwargs prefix = app.api_prefix or None app.register_blueprint(blueprint, url_prefix=prefix, **kwargs)
def setup_blueprint(self): """Setup blueprint.""" from .blueprint import DataBlueprint here = os.path.dirname(os.path.abspath(__file__)) template_folder = os.path.join(here, 'templates') static_folder = os.path.join(here, 'static') blueprint = DataBlueprint(template_folder=template_folder, static_folder=static_folder) app.register_blueprint(blueprint, url_prefix="/data")
def init_auth_blueprint(config_file='config', redis_url='') -> None: if not redis_url: redis_url = current_app.config.get('REDIS_URL', 'redis://redis:6379/0') from authentication.models.db import db db.connect(url=redis_url) from authentication import app current_app.register_blueprint(app.auth)
def _register_components(flask_app): from app.db.models import sql_alchemy sql_alchemy.session = sql_alchemy.create_scoped_session() sql_alchemy.init_app(flask_app) flask_app.db = sql_alchemy flask_app.register_blueprint(api) redis_uri = _get_redis_url(flask_app) flask_app.cache = redis.from_url(redis_uri) return flask_app
def setup_project_browser(app, url_prefix="/browse"): """Sets up the project browser blueprint. Args: app (werkzeug.local.LocalProxy): The current application's instance. url_prefix (str): The blueprint's URL prefix. """ from view.project_browser import blueprint app.register_blueprint(blueprint, url_prefix=url_prefix)
def setup_sourcerer(app, url_prefix="/sourcerer"): """Sets up the sourcerer. Args: app (werkzeug.local.LocalProxy): The current application's instance. url_prefix (str): The blueprint's URL prefix. """ from view.sourcerer import blueprint app.register_blueprint(blueprint, url_prefix=url_prefix)
def create_app(debug=False): """Create an application context with blueprints.""" state = housekeeping() if not state: sys.exit(1) app = Flask(__name__, static_folder='./resources') app.config['SECRET_KEY'] = 'tRSn3mh2bY3@1$W2T9aQ' app.config['MONGO_DBNAME'] = 'netinfo' app.config['MONGO_HOST'] = 'localhost' app.config['ASNDB'] = None app.config['GEOIPDB'] = None app.config['DEBUG'] = debug muri = "mongodb://%s:27017/%s" % (app.config['MONGO_HOST'], app.config['MONGO_DBNAME']) app.config['MONGO_URI'] = muri mongo.init_app(app) app.config.update(CELERY_BROKER_URL='redis://localhost:6379', CELERY_RESULT_BACKEND='redis://localhost:6379', CELERYBEAT_SCHEDULE={ 'fetch-rib': { 'task': 'fetch-rib', 'schedule': crontab(minute='*/5') }, 'fetch-as-name': { 'task': 'fetch-as-names', 'schedule': crontab(hour="*/12") }, 'fetch-geo': { 'task': 'fetch_geoip', 'schedule': crontab(hour=7, minute=30, day_of_week=1) } }) celery.conf.update(app.config) config_file = '%s/resources/config.json' % APP_BASE if not os.path.exists(config_file): config = { 'asn': { 'last_rib_file': None, 'last_update': None }, 'geoip': { 'last_update': None } } json.dump(config, open(config_file, 'w'), indent=4) from .core import core as core_blueprint app.register_blueprint(core_blueprint) app.register_error_handler(404, page_not_found) app.register_error_handler(500, server_error) return app
def setup_blueprints(self): """Setup blueprints.""" from .api.analysis import BLUEPRINT as analysis from .api.projects import BLUEPRINT as projects from .api.categories import BLUEPRINT as categories from .api.admin import BLUEPRINT as admin from .api.proxy import BLUEPRINT as proxy app.register_blueprint(analysis, url_prefix='/lc/analysis') app.register_blueprint(projects, url_prefix='/lc/projects') app.register_blueprint(categories, url_prefix='/lc/categories') app.register_blueprint(admin, url_prefix='/lc/admin') app.register_blueprint(proxy, url_prefix='/lc/proxy')
def _register_blueprint(self, module): name = module.__name__ blueprint = Blueprint(name.split(".")[-1], name, url_prefix="/dashboard", template_folder="templates") views = [] for attr in dir(module): view = getattr(module, attr) if view != MethodView and inspect.isclass(view) and issubclass(view, MethodView): for rule in view.rules: rule["view_func"] = view.as_view(rule["endpoint"]) blueprint.add_url_rule(**rule) app.register_blueprint(blueprint)
def setup_survey(app, url_prefix="/survey"): """Sets up the participation survey. Args: app (werkzeug.local.LocalProxy): The current application's instance. url_prefix (str): The blueprint's URL prefix. """ from view.survey import blueprint setup_default_configuration(app, { "GEOTAGX_FINAL_SURVEY_TASK_REQUIREMENTS": 30, }) app.register_blueprint(blueprint, url_prefix=url_prefix)
def init_app(app): app.register_blueprint(bp) gravatar = Gravatar(app, size=150, rating='r') app.teardown_appcontext(_save_last_seen) with app.app_context(): app.jinja_env.globals.update( login_link=login_link, get_notifications=get_notifications, get_flashed_messages=get_flashed_messages_override) app.context_processor(_get_current_user)
def load(app): # upgrade() app.db.create_all() CHALLENGE_CLASSES['lah'] = LahChallengeClass register_plugin_assets_directory(app, base_path='/plugins/lah_challenges/assets/') global APP_REF APP_REF = app scheduler.start() atexit.register(lambda: scheduler.shutdown()) app.register_blueprint(lah_print) register_user_page_menu_bar("Unlocking", "/unlock") register_plugin_script("/plugins/lah_challenges/assets/lah_challenge_injector.js")
def register_bundle(self, bundles_dict): """ Get the variables bundle and register in the Flask App. :params: bundles_dict - Dictionary with all bundles (Blueprints) """ for bundle_name, bundle in bundles_dict.iteritems(): # Try get bundle variable and bundle_config variable blueprint = getattr(bundle, self.bundle_var_name, None) kwargs = getattr(bundle, self.bundle_var_name + '_config', dict()) if blueprint: # Register the blueprint current_app.register_blueprint(blueprint, **kwargs)
def create_blueprint(self, admin): blueprint = super().create_blueprint(admin) # A blueprint to serve files for media admin if "oy.contrib.media.admin" not in current_app.blueprints: current_app.register_blueprint( Blueprint( name="oy.contrib.media.admin", import_name="oy.contrib.media.admin", static_folder="static", template_folder="templates", static_url_path="/static/admin/media", )) blueprint.register_error_handler(UnsupportedFileTypeError, self.handle_unsupported_file_types) return blueprint
def create_app(spark_context, dataset_path): global recommendation_engine global cb recommendation_engine = RecommendationEngine(spark_context, dataset_path) cb = content(dataset_path) app = Flask(__name__) app.secret_key = "^A%DJAJU^JJ123" app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = '******' app.config['MYSQL_PASSWORD'] = '******' app.config['MYSQL_DB'] = 'flaskapp' app.config['MYSQL_CURSORCLASS'] = 'DictCursor' global mysql mysql = MySQL(app) app.register_blueprint(main) return app
def config_app(app_root_path, test_config=None): # create and configure the web_app app = Flask(__name__, instance_relative_config=True) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) app.config['app_root'] = app_root_path #Configure loggers #App logger app_logger = logging.getLogger('app_logger') app_logger.setLevel(logging.INFO) app_fh = logging.FileHandler(str(app_root_path) + '/LogFiles/web_app.log') app_formatter = logging.Formatter( fmt= '%(levelname)s:%(threadName)s:%(asctime)s:%(filename)s:%(funcName)s:%(message)s', datefmt='%m/%d/%Y %H:%M:%S') app_fh.setFormatter(app_formatter) app_logger.addHandler(app_fh) #STDOUT/STDERR logger """ root_logger = logging.getLogger('ROOT_LOGGER') root_logger.setLevel(logging.INFO) handler = logging.FileHandler(str(app_root_path) + '/LogFiles/web_app.log') formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s') handler.setFormatter(formatter) root_logger.addHandler(handler) sys.stderr.write = auxiliary.write_to_log_error sys.stdout.write = auxiliary.write_to_log_info """ #Load models try: models = load_ml.load_ml_models(app.config['app_root']) app_logger.info("Loaded the following ML models") app_logger.info(models) except Exception as e: app_logger.error("Could not initialize models") app_logger.error(traceback.format_exc()) raise exceptions.InitializationError("Could not initialize models") app.register_blueprint(api.bp) app.register_blueprint(predictors.bp) return app, models
def register_blueprints(flask_application_instance): from medallion.views import collections, discovery, manifest, objects with flask_application_instance.app_context(): log.debug( "Registering medallion blueprints into {}".format(current_app)) current_app.register_blueprint(collections.collections_bp) current_app.register_blueprint(discovery.discovery_bp) current_app.register_blueprint(manifest.manifest_bp) current_app.register_blueprint(objects.objects_bp)
def attach_blueprints(): from orvsd_central.controllers import api from orvsd_central.controllers import category from orvsd_central.controllers import general from orvsd_central.controllers import report current_app.register_blueprint(api.mod) current_app.register_blueprint(category.mod) current_app.register_blueprint(general.mod) current_app.register_blueprint(report.mod)
def init_themes(self, app, loaders=None, app_identifier=None, manager_cls=None, theme_url_prefix="/_themes", static_folder=None): """This sets up the theme infrastructure by adding a `ThemeManager` to the given app and registering the module/blueprint containing the views and templates needed. :param app: The `~flask.Flask` instance to set up themes for. :param loaders: An iterable of loaders to use. It defaults to `packaged_themes_loader` and `theme_paths_loader`. :param app_identifier: The application identifier to use. If not given, it defaults to the app's import name. :param manager_cls: If you need a custom manager class, you can pass it in here. :param theme_url_prefix: The prefix to use for the URLs on the themes module. (Defaults to ``/_themes``.) """ if app_identifier is None: app_identifier = app.import_name if manager_cls is None: manager_cls = ThemeManager manager_cls(app, app_identifier, loaders=loaders, static_folder=static_folder) app.jinja_env.globals['theme'] = global_theme_template app.jinja_env.globals['theme_static'] = global_theme_static app.jinja_env.globals['theme_get_info'] = global_theme_get_info if static_folder: themes_blueprint.static_folder = static_folder themes_blueprint.static_url_path = app.static_url_path + theme_url_prefix else: themes_blueprint.url_prefix = theme_url_prefix themes_blueprint.add_url_rule('/<themeid>/<path:filename>', 'static', view_func=static) app.register_blueprint(themes_blueprint)
def __init__(self, name, **kwargs): kwargs.setdefault("url_prefix", "/") self._blueprint = Blueprint(name, self.__class__.__name__) if hasattr(self, "__expose__"): _, options = getattr(self, "__expose__") options.setdefault("methods", current_app.config["api_methods"]) group = options.get("group", current_app.cfg["admin_group"]) group_dec = current_app.group_access(group) route_dec = self._blueprint.route("/<name>", **options) wrapper = group_dec(self._interface) route_dec(update_wrapper(wrapper, self._interface)) for member_name in dir(self): method = getattr(self, member_name) if not callable(method): # or not hasattr(method, "__expose__"): continue if hasattr(method, "__expose__"): rule, options = getattr(method, "__expose__") options["methods"] = ("POST",) group = options.get("group", current_app.config["admin_group"]) method = self.gen_wrapper(method) elif hasattr(method, "__route__"): rule, options = getattr(method, "__route__") group = options.get("group", None) # current_app.config["guest_group"]) else: continue if group: method = current_app.group_access(group)(method) self._blueprint.add_url_rule(rule, view_func=method, **options) current_app.register_blueprint(self._blueprint, **kwargs)
def setup(self): """Initializes the GeoTag-X plugin. """ from flask import current_app as app from view.admin import blueprint as admin_blueprint from view.blog import blueprint as blog_blueprint from view.community import blueprint as community_blueprint from filter import blueprint as filter_blueprint from view.geojson_exporter import blueprint as geojson_exporter_blueprint from view.feedback import blueprint as feedback_blueprint from view.geotagx import blueprint as geotagx_blueprint from view.survey import blueprint as survey_blueprint # The plugin's default configuration. default_configuration = { "GEOTAGX_NEWSLETTER_DEBUG_EMAIL_LIST": [], } for key in default_configuration: if app.config.get(key, None) is None: app.config[key] = default_configuration[key] # A list of blueprint <handle, URL prefix> pairs. blueprints = [ (admin_blueprint, "/admin"), (blog_blueprint, "/blog"), (community_blueprint, "/community"), (filter_blueprint, None), (feedback_blueprint, "/feedback"), (geojson_exporter_blueprint, None), (geotagx_blueprint, "/geotagx"), ] for (handle, url_prefix) in blueprints: app.register_blueprint(handle, url_prefix=url_prefix) setup_survey(app) setup_sourcerer(app) setup_project_browser(app) setup_helper_functions(app)
def register_users_blueprint_and_signals(app): app.register_blueprint(users_blueprint) user_confirmed.connect(when_user_confirmed)
def setup_blueprint(self): """Setup blueprint.""" from .view import blueprint app.register_blueprint(blueprint, url_prefix="/github")
def register(app): app.register_blueprint(main)
def add_plugin_blueprints(app): for blueprint in RHMapMemory()._blueprints: if not app.config['INDICO_COMPAT_ROUTES'] and blueprint.name.startswith('compat_'): continue app.register_blueprint(blueprint)
def register_pubsub_blueprint_and_signals(app): app.register_blueprint(pubsubhubbub_blueprint) print("Connecting 'when_notification_received' to 'notification-received' signal") notification_received.connect(when_notification_received)
def register_authors_blueprint_and_signals(app): """Registers blueprint to app and connects signals""" app.register_blueprint(authors_blueprint) authors_entries_added.connect(when_authors_entries_added)
def setup(app): app.register_blueprint(blueprint)
def register_blueprint(self, blueprint, **kwargs): """Registers a blueprint. :param blueprint: The blueprint which should be registered. """ current_app.register_blueprint(blueprint, **kwargs)
def register_blueprint(self, blueprint, **kwargs): """Registers a blueprint.""" current_app.register_blueprint(blueprint, **kwargs)
def create_app_ext(flask_config_file=None, flask_config_dict=None, moin_config_class=None, warn_default=True, **kwargs): """ Factory for moin wsgi apps :param flask_config_file: a flask config file name (may have a MOINCFG class), if not given, a config pointed to by MOINCFG env var will be loaded (if possible). :param flask_config_dict: a dict used to update flask config (applied after flask_config_file was loaded [if given]) :param moin_config_class: if you give this, it'll be instantiated as app.cfg, otherwise it'll use MOINCFG from flask config. If that also is not there, it'll use the DefaultConfig built into MoinMoin. :param warn_default: emit a warning if moin falls back to its builtin default config (maybe user forgot to specify MOINCFG?) :param kwargs: if you give additional keyword args, the keys/values will get patched into the moin configuration class (before its instance is created) """ clock = Clock() clock.start('create_app total') app = Flask('MoinMoin') clock.start('create_app load config') if flask_config_file: app.config.from_pyfile(flask_config_file) else: if not app.config.from_envvar('MOINCFG', silent=True): # no MOINCFG env variable set, try stuff in cwd: from os import path flask_config_file = path.abspath('wikiconfig_local.py') if not path.exists(flask_config_file): flask_config_file = path.abspath('wikiconfig.py') if not path.exists(flask_config_file): flask_config_file = None if flask_config_file: app.config.from_pyfile(flask_config_file) if flask_config_dict: app.config.update(flask_config_dict) Config = moin_config_class if not Config: Config = app.config.get('MOINCFG') if not Config: if warn_default: logging.warning("using builtin default configuration") from MoinMoin.config.default import DefaultConfig as Config for key, value in kwargs.iteritems(): setattr(Config, key, value) if Config.secrets is None: # reuse the secret configured for flask (which is required for sessions) Config.secrets = app.config.get('SECRET_KEY') app.cfg = Config() clock.stop('create_app load config') clock.start('create_app register') # register converters from werkzeug.routing import BaseConverter class ItemNameConverter(BaseConverter): """Like the default :class:`UnicodeConverter`, but it also matches slashes (except at the beginning AND end). This is useful for wikis and similar applications:: Rule('/<itemname:wikipage>') Rule('/<itemname:wikipage>/edit') """ regex = '[^/]+?(/[^/]+?)*' weight = 200 app.url_map.converters['itemname'] = ItemNameConverter # register modules, before/after request functions from MoinMoin.apps.frontend import frontend frontend.before_request(before_wiki) frontend.teardown_request(teardown_wiki) app.register_blueprint(frontend) from MoinMoin.apps.admin import admin admin.before_request(before_wiki) admin.teardown_request(teardown_wiki) app.register_blueprint(admin, url_prefix='/+admin') from MoinMoin.apps.feed import feed feed.before_request(before_wiki) feed.teardown_request(teardown_wiki) app.register_blueprint(feed, url_prefix='/+feed') from MoinMoin.apps.misc import misc misc.before_request(before_wiki) misc.teardown_request(teardown_wiki) app.register_blueprint(misc, url_prefix='/+misc') from MoinMoin.apps.serve import serve app.register_blueprint(serve, url_prefix='/+serve') clock.stop('create_app register') clock.start('create_app flask-cache') cache = Cache() cache.init_app(app) app.cache = cache clock.stop('create_app flask-cache') # init storage clock.start('create_app init backends') init_backends(app) clock.stop('create_app init backends') clock.start('create_app flask-babel') i18n_init(app) clock.stop('create_app flask-babel') # configure templates clock.start('create_app flask-themes') setup_themes(app) if app.cfg.template_dirs: app.jinja_env.loader = ChoiceLoader([ FileSystemLoader(app.cfg.template_dirs), app.jinja_env.loader, ]) app.register_error_handler(403, themed_error) clock.stop('create_app flask-themes') clock.stop('create_app total') del clock return app
def setup_blueprints(self, app): app.register_blueprint(api_blueprint, url_prefix='/' + app.config.get('API_PATH_PREFIX', '').strip('/')) @app.route('/error') def test_error(): raise ValueError('Exc')
def add_compat_blueprints(app): for blueprint in COMPAT_BLUEPRINTS: app.register_blueprint(blueprint)
def setup_blueprint(self): """Setup blueprint.""" from .blueprint import DiscourseBlueprint blueprint = DiscourseBlueprint() app.register_blueprint(blueprint, url_prefix="/discourse")
def register_subscription_blueprint_and_signals(app): """Registers blueprint to app and connects signals""" app.register_blueprint(subscription_blueprint) entries_added.connect(when_entries_added)
def register_plugin(app): app.register_blueprint(blueprint)
def register(app): app.register_blueprint(localized)
def add_blueprints(app): for blueprint in BLUEPRINTS: app.register_blueprint(blueprint)
def register_ingestion_blueprint_and_signals(app): """Registers blueprint to app and connects signals""" app.register_blueprint(ingestion_blueprint) notification_received.connect(when_notification_received)