Bind the service API urls to a flask app.
557137
def bind(self, flask_app):
        """"""
        self.metadata.bind(flask_app, self.name, self.group)
471296
def register_app(app):
    "  "

    from .views import urls
    app.register_blueprint(urls)

    from .ext import admin
    admin.init_app(app)

    from flask_bootstrap import Bootstrap
    bootstrap = Bootstrap()
    bootstrap.init_app(app)

    from flask import render_template
    app.errorhandler(404)(lambda e: (render_template('core/404.html'), 404))
234245
def _update_url_map(self):
        '''
        
        '''
        if HAS_WEBSOCKETS:
            self.url_map.update({
                'ws': WebsocketEndpoint,
            })

        # Allow the Webhook URL to be overridden from the conf.
        self.url_map.update({
            self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook,
        })

        # Enable the single-page JS app URL.
        self.url_map.update({
            self.apiopts.get('app_path', 'app').lstrip('/'): App,
        })
696606
def inject(self, request, response):
        
        # called in host app
        if not isinstance(response, Response):
            return
        settings = request.app[APP_KEY]['settings']
        response_html = response.body
        route = request.app.router['debugtoolbar.request']
        toolbar_url = route.url_for(request_id=request['id'])

        button_style = settings['button_style']

        css_path = request.app.router[STATIC_ROUTE_NAME].url_for(
            filename='css/toolbar_button.css')

        toolbar_css = toolbar_css_template % {'css_path': css_path}
        toolbar_html = toolbar_html_template % {
            'button_style': button_style,
            'css_path': css_path,
            'toolbar_url': toolbar_url}

        toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
        toolbar_css = toolbar_css.encode(response.charset or 'utf-8')
        response_html = replace_insensitive(
            response_html, b'</head>', toolbar_css + b'</head>')
        response.body = replace_insensitive(
            response_html, b'</body>',
            toolbar_html + b'</body>')
1250667
def register_swaggerui_app(app, swagger_uri, api_url, page_title='Swagger UI', favicon_url=None, config=None, uri_prefix=""):

    """"""

    templates_folder = 'templates'
    static_folder = 'dist'

    default_config = {
        'client_realm': 'null',
        'client_id': 'null',
        'client_secret': 'null',
        'app_name': 'null',
        'docExpansion': "none",
        'jsonEditor': False,
        'defaultModelRendering': 'schema',
        'showRequestHeaders': False,
        'supportedSubmitMethods': ['get', 'post', 'put', 'delete', 'patch'],
    }

    if config:
        default_config.update(config)

    default_context = {
        'page_title': page_title,
        'favicon_url': favicon_url,
        'base_url': uri_prefix + swagger_uri,
        'api_url': api_url,
        'app_name': default_config.pop('app_name'),
        'client_realm': default_config.pop('client_realm'),
        'client_id': default_config.pop('client_id'),
        'client_secret': default_config.pop('client_secret'),
        # Rest are just serialized into json string
        # for inclusion in the .js file
        'config_json': json.dumps(default_config)
    }

    app.add_sink(
        StaticSinkAdapter(static_folder),
        r'%s/(?P<filepath>.*)\Z' % swagger_uri,
    )

    app.add_route(
        swagger_uri,
        SwaggerUiResource(templates_folder, default_context)
    )
1046934
def load_clients(self, path=None, apis=[]):
        """"""

        if not path:
            raise Exception("Missing path to api swagger files")

        if type(apis) is not list:
            raise Exception("'apis' should be a list of api names")

        if len(apis) == 0:
            raise Exception("'apis' is an empty list - Expected at least one api name")

        for api_name in apis:
            api_path = os.path.join(path, '%s.yaml' % api_name)
            if not os.path.isfile(api_path):
                raise Exception("Cannot find swagger specification at %s" % api_path)
            log.info("Loading api %s from %s" % (api_name, api_path))
            ApiPool.add(
                api_name,
                yaml_path=api_path,
                timeout=self.timeout,
                error_callback=self.error_callback,
                formats=self.formats,
                do_persist=False,
                local=False,
            )

        return self
516201
def __build_url(self, api_call, **kwargs):
        """"""
        kwargs['key'] = self.api_key
        if 'language' not in kwargs:
            kwargs['language'] = self.language
        if 'format' not in kwargs:
            kwargs['format'] = self.__format
        api_query = urlencode(kwargs)

        return "{0}{1}?{2}".format(urls.BASE_URL,
                                   api_call,
                                   api_query)
461724
def resource_urls(request):
    """"""

    url_parsed = urlparse(settings.SEARCH_URL)
    defaults = dict(
        APP_NAME=__description__,
        APP_VERSION=__version__,
        SITE_URL=settings.SITE_URL.rstrip('/'),
        SEARCH_TYPE=settings.SEARCH_TYPE,
        SEARCH_URL=settings.SEARCH_URL,
        SEARCH_IP='%s://%s:%s' % (url_parsed.scheme, url_parsed.hostname, url_parsed.port)
    )
    return defaults
297140
def _prepare_uri(self, service_name, **parameters):
        
        query_parameters = []
        for key, value in parameters.items():
            if isinstance(value, (list, tuple)):
                value = ",".join([str(member) for member in value])
            if isinstance(value, bool):
                value = "true" if value else "false"
            query_parameters.append("{}={}".format(key, value))

        if query_parameters:
            uri = "{}{}?{}".format(self.base_url, service_name,
                                   "&".join(query_parameters))
        else:
            uri = "{}{}".format(self.base_url, service_name)
        return uri
1133126
def url_for(self, attr=None, filter_value=None,
            service_type=None, endpoint_type="publicURL",
            service_name=None, volume_service_name=None):
        """"""
        matching_endpoints = []
        # We don't always get a service catalog back ...
        if "serviceCatalog" not in self.catalog["access"]:
            return None

        # Full catalog ...
        catalog = self.catalog["access"]["serviceCatalog"]
        for service in catalog:
            if service.get("type") != service_type:
                continue
            endpoints = service["endpoints"]
            for endpoint in endpoints:
                if not filter_value or endpoint.get(attr) == filter_value:
                    endpoint["serviceName"] = service.get("name")
                    matching_endpoints.append(endpoint)

        if not matching_endpoints:
            raise exc.EndpointNotFound()
        elif len(matching_endpoints) > 1:
            raise exc.AmbiguousEndpoints(endpoints=matching_endpoints)
        else:
            return matching_endpoints[0][endpoint_type]
438718
def app_show(self, id, **kwargs):
        ""
        api_path = "/api/v2/apps/{id}.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, **kwargs)
1040142
def make_urldispatch_application(_, **settings):
    
    patterns = [p.split("=", 1)
                for p in settings['patterns'].split('\n')
                if p]
    application = URLDispatcher()

    for pattern, app in patterns:
        pattern = pattern.strip()
        app = app.strip()
        mod, obj = app.split(":", 1)
        if mod not in sys.modules:
            __import__(mod)
        mod = sys.modules[mod]
        obj = getattr(mod, obj)
        application.add_url(app, pattern, obj)

    return application
1120119
def init_app(self, app):
        
        self.init_config(app)

        # Enable CORS support if desired
        if app.config['REST_ENABLE_CORS']:
            from flask_cors import CORS
            CORS(app)
            # CORS can be configured using CORS_* configuration variables.

        app.errorhandler(400)(create_api_errorhandler(
            status=400, message='Bad Request'))
        app.errorhandler(401)(create_api_errorhandler(
            status=401, message='Unauthorized'))
        app.errorhandler(403)(create_api_errorhandler(
            status=403, message='Forbidden'))
        app.errorhandler(404)(create_api_errorhandler(
            status=404, message='Not Found'))
        app.errorhandler(405)(create_api_errorhandler(
            status=405, message='Method Not Allowed'))
        app.errorhandler(406)(create_api_errorhandler(
            status=406, message='Not Acceptable'))
        app.errorhandler(409)(create_api_errorhandler(
            status=409, message='Conflict'))
        app.errorhandler(410)(create_api_errorhandler(
            status=410, message='Gone'))
        app.errorhandler(412)(create_api_errorhandler(
            status=412, message='Precondition Failed'))
        app.errorhandler(415)(create_api_errorhandler(
            status=415, message='Unsupported media type'))
        app.errorhandler(422)(create_api_errorhandler(
            status=422, message='Unprocessable Entity'))
        app.errorhandler(429)(create_api_errorhandler(
            status=429, message='Rate limit exceeded'))
        app.errorhandler(500)(create_api_errorhandler(
            status=500, message='Internal Server Error'))
        app.errorhandler(501)(create_api_errorhandler(
            status=501, message='Not Implemented'))
        app.errorhandler(502)(create_api_errorhandler(
            status=502, message='Bad Gateway'))
        app.errorhandler(503)(create_api_errorhandler(
            status=503, message='Service Unavailable'))
        app.errorhandler(504)(create_api_errorhandler(
            status=504, message='Gateway Timeout'))

        app.extensions['invenio-rest'] = self
628432
def requires_application_json(f):
    """"""

    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        from flask import request
        if request.get_json(silent=True) is None:
            er = ErrorResponse(description='Improper Content-Type header. Expecting "application/json"')
            return to_json_response(er), HTTPStatus.BAD_REQUEST
        else:
            return f(*args, **kwargs)

    return wrapped
1277066
def _routes(self, app):
        
        _routes = []
        prefix = self.url_prefix if self.url_prefix is not None else ""
        for rule in app.url_map.iter_rules():
            if str(rule).startswith(prefix):
                _routes.append({
                    'path':rule.rule,
                    'name':rule.endpoint,
                    'methods':list(rule.methods)
                })
        returns = {
            'api': self.name,
            'url_root': request.url_root,
            'routes': _routes
        }
        return jsonify(returns)
609865
def app(session_id, app, bind, port):
    
    api_session = None
    runner = None

    async def app_setup():
        nonlocal api_session, runner
        loop = current_loop()
        api_session = AsyncSession()
        # TODO: generalize protocol using service ports metadata
        protocol = 'http'
        runner = ProxyRunner(api_session, session_id, app,
                             protocol, bind, port,
                             loop=loop)
        await runner.ready()
        print_info(
            "A local proxy to the application \"{0}\" ".format(app) +
            "provided by the session \"{0}\" ".format(session_id) +
            "is available at: {0}://{1}:{2}"
            .format(protocol, bind, port)
        )

    async def app_shutdown():
        nonlocal api_session, runner
        print_info("Shutting down....")
        await runner.close()
        await api_session.close()
        print_info("The local proxy to \"{}\" has terminated."
                   .format(app))

    asyncio_run_forever(app_setup(), app_shutdown(),
                        stop_signals={signal.SIGINT, signal.SIGTERM})
797632
def bind(*args):
    """"""
    if _debug: bind._debug("bind %r", args)

    # generic bind is pairs of names
    if not args:
        # find unbound clients and bind them
        for cid, client in client_map.items():
            # skip those that are already bound
            if client.clientPeer:
                continue

            if not cid in server_map:
                raise RuntimeError("unmatched server {!r}".format(cid))
            server = server_map[cid]

            if server.serverPeer:
                raise RuntimeError("server already bound %r".format(cid))

            bind(client, server)

        # see if there are any unbound servers
        for sid, server in server_map.items():
            if server.serverPeer:
                continue

            if not sid in client_map:
                raise RuntimeError("unmatched client {!r}".format(sid))
            else:
                raise RuntimeError("mistery unbound server {!r}".format(sid))

        # find unbound application service elements and bind them
        for eid, element in element_map.items():
            # skip those that are already bound
            if element.elementService:
                continue

            if not eid in service_map:
                raise RuntimeError("unmatched element {!r}".format(cid))
            service = service_map[eid]

            if server.serverPeer:
                raise RuntimeError("service already bound {!r}".format(cid))

            bind(element, service)

        # see if there are any unbound services
        for sid, service in service_map.items():
            if service.serviceElement:
                continue

            if not sid in element_map:
                raise RuntimeError("unmatched service {!r}".format(sid))
            else:
                raise RuntimeError("mistery unbound service {!r}".format(sid))

    # go through the argument pairs
    for i in xrange(len(args)-1):
        client = args[i]
        if _debug: bind._debug("    - client: %r", client)
        server = args[i+1]
        if _debug: bind._debug("    - server: %r", server)

        # make sure we're binding clients and servers
        if isinstance(client, Client) and isinstance(server, Server):
            client.clientPeer = server
            server.serverPeer = client

        # we could be binding application clients and servers
        elif isinstance(client, ApplicationServiceElement) and isinstance(server, ServiceAccessPoint):
            client.elementService = server
            server.serviceElement = client

        # error
        else:
            raise TypeError("bind() requires a client and server")

        if _debug: bind._debug("    - bound")