Adds the flask url routes for the apidoc files.
        :param app: the flask application.
438550
def init_app(self, app):
        

        self.app = app

        self.dynamic_url = self.app.config.get('APIDOC_DYNAMIC_URL', self.dynamic_url)
        self.allow_absolute_url = self.app.config.get('APIDOC_ALLOW_ABSOLUTE_URL', self.allow_absolute_url)

        url = self.url_path

        if not self.url_path.endswith('/'):
            url += '/'

        app.add_url_rule(url, 'docs', self.__send_static_file, strict_slashes=True)
        app.add_url_rule(url + '<path:path>', 'docs', self.__send_static_file, strict_slashes=True)
713849
def app_routes(app):
    
    _routes = []
    for rule in app.url_map.iter_rules():
        _routes.append({
            'path': rule.rule,
            'name': rule.endpoint,
            'methods': list(rule.methods)
        })
    return jsonify({'routes': _routes})
1045377
def init_app(self, app, decorators=None):
        
        self.decorators = decorators or self.decorators
        self.app = app

        self.load_config(app)
        # self.load_apispec(app)
        if self.template_file is not None:
            self.template = self.load_swagger_file(self.template_file)
        self.register_views(app)
        self.add_headers(app)

        if self.parse:
            if RequestParser is None:
                raise RuntimeError('Please install flask_restful')
            self.parsers = {}
            self.schemas = {}
            self.format_checker = jsonschema.FormatChecker()
            self.parse_request(app)

        self._configured = True
        app.swag = self
966318
def add_url_rule(self, route, endpoint, handler):
        
        self.app.add_url_rule(route, endpoint, handler)
1014185
def _decorate_routes(self):
        
        self.logger.debug("Decorating routes")
        # self.app.add_url_rule('/', 'catch', self.catch, methods=['GET'],
        #                        defaults={'path': ''})
        self.app.add_url_rule('/<path:path>', 'catch', self.catch,
                              methods=['GET', 'POST'], defaults={'path': ''})
        self.app.add_url_rule('/', 'index', self.index,
                              methods=['POST', 'GET'])
        self.app.add_url_rule('/feed', 'feed', self.feed,
                              methods=['POST'])
        self.app.add_url_rule('/poll', 'poll', self.poll,
                              methods=['POST'])
795798
def write_urls_index(app, exc):
    '''
    
    '''
    inventory = os.path.join(app.builder.outdir, 'objects.inv')
    objects = sphinx.ext.intersphinx.fetch_inventory(app, DOCS_URL, inventory)

    with open(os.path.join(app.builder.outdir, 'shorturls.json'), 'w') as f:
        json.dump(objects, f)
112153
def init_app(self, app):
        
        if not hasattr(app, 'extensions'):
            app.extensions = {}

        app.extensions['nav'] = self
        app.add_template_global(self.elems, 'nav')

        # register some renderers
        for args in self._renderers:
            register_renderer(app, *args)
25120
def init_app(self, app):
        
        if not hasattr(app, 'extensions'):  # pragma: no cover
            app.extensions = {}
        app.extensions['imagine'] = self

        self._set_defaults(app)

        self._redirect_code = app.config['IMAGINE_CACHE_REDIRECT_CODE']

        if isinstance(app.config['IMAGINE_ADAPTERS'], dict):
            self._adapters.update(app.config['IMAGINE_ADAPTERS'])
        if isinstance(app.config['IMAGINE_FILTERS'], dict):
            self._filters.update(app.config['IMAGINE_FILTERS'])

        self._handle_adapter(app)
        self._handle_filter_sets(app)

        self._add_url_rule(app)
1190669
def add_route(app, fn, context=default_context):
    
    transmute_func = TransmuteFunction(
        fn,
        args_not_from_request=["request"]
    )
    handler = create_handler(transmute_func, context=context)
    get_swagger_spec(app).add_func(transmute_func, context)

    for p in transmute_func.paths:
        aiohttp_path = _convert_to_aiohttp_path(p)
        resource = app.router.add_resource(aiohttp_path)
        for method in transmute_func.methods:
            resource.add_route(method, handler)
1145753
def app_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/apps.json"
        return self.call(api_path, method="POST", data=data, **kwargs)
1287886
def routes_register(app, handler, *paths, methods=None, router=None, name=None):
    """"""
    if router is None:
        router = app.router

    handler = to_coroutine(handler)

    resources = []

    for path in paths:

        # Register any exception to app
        if isinstance(path, type) and issubclass(path, BaseException):
            app._error_handlers[path] = handler
            continue

        # Ensure that names are unique
        name = str(name or '')
        rname, rnum = name, 2
        while rname in router:
            rname = "%s%d" % (name, rnum)
            rnum += 1

        path = parse(path)
        if isinstance(path, RETYPE):
            resource = RawReResource(path, name=rname)
            router.register_resource(resource)

        else:
            resource = router.add_resource(path, name=rname)

        for method in methods or [METH_ANY]:
            method = method.upper()
            resource.add_route(method, handler)

        resources.append(resource)

    return resources
372898
def init_app(self, app):
        

        self.__app = app
        self.__app.before_first_request(self.__setup)

        self.tracer.enabled = self.__app.config.get('TRACE_ENABLED', self.tracer.enabled)
313433
def swaggerify(app, parse_module_info=True, **kwargs):
    

    async def swagger_handler(request):
        """
        Request handler to serve swagger json config for given app
        """
        return web.json_response(app["_swagger_config"])

    # Populate configs for paths from app routes
    paths_config = defaultdict(dict)
    for r in app.router.routes():
        # Title and description are retrieved from docstring of a handler
        docstrings = parse_docstring(r.handler.__doc__ or "")
        if len(docstrings["title"]) > 120:
            # TODO: logging
            docstrings["title"] = docstrings["title"][:120]

        # Some information is just hardcoded as we have strict requirements
        # to input and output format of ws endpoints
        desc = {
            "summary": docstrings["title"],
            "description": docstrings["description"],
            "consumes": ["application/json"],
            "produces": ["application/json"],
            "responses": {
                "400": {"description": "Request is malformed or invalid"},
                "500": {"description": "Response malformed or invalid"},
                "405": {"description": "Method is not allowed"},
            }
        }

        if hasattr(r.handler, "_request_schema"):
            desc["parameters"] = [{
                "in": "body",
                "name": "body",
                "required": True,
                "schema": r.handler._request_schema
            }]
        else:
            desc["parameters"] = [{
                "in": "body",
                "name": "body"
            }]

        if hasattr(r.handler, "_swg_input"):
            desc["parameters"][0].update(r.handler._swg_input)

        if hasattr(r.handler, "_response_schema"):
            desc["responses"]["200"] = {
                # TODO: think how to override
                "description": "Results of the request",
                "schema": r.handler._response_schema
            }
        else:
            desc["responses"]["200"] = {
                "description": "Results of the request"
            }

        if hasattr(r.handler, "_swg_output"):
            desc["responses"]["200"].update(r.handler._swg_output)

        if hasattr(r.handler, "_swg_info"):
            desc.update(r.handler._swg_info)

        paths_config[r._resource._path][r.method.lower()] = desc

    # Populate complete config

    # Get optional information that overrides info part of the config
    swagger_config_info = kwargs.pop("info", {})
    # Some sane defaults
    swagger_config = {
        "swagger": "2.0",
        "schemes": ["http"],
        "paths": paths_config
    }

    # That can be overriden with kwargs
    swagger_config.update(kwargs)

    # Some sane defaults for info part of the config
    swagger_config_info_default = {
        "version": "1.0.0",
    }

    # Which we now can try to extend using introspection, docstrings and
    # global variables of the main module of the app
    if parse_module_info:
        try:
            caller = inspect.currentframe().f_back
            mod = sys.modules[caller.f_globals['__name__']]

            # Try to pull information from docstrings
            swagger_config_info_default.update(parse_docstring(mod.__doc__))

            # As well as global variables
            if hasattr(mod, "__version__"):
                swagger_config_info_default["version"] = mod.__version__

            if hasattr(mod, "__license__"):
                swagger_config_info_default["license"] = {
                    "name": mod.__license__
                    # TODO: add urls for well-known licenses
                }

            # And map it to swagger definitions
            contact_info = {}
            if hasattr(mod, "__author__"):
                contact_info["name"] = mod.__author__
            if hasattr(mod, "__maintainer__"):
                contact_info["name"] = mod.__maintainer__
            if hasattr(mod, "__email__"):
                contact_info["email"] = mod.__email__

            if contact_info:
                swagger_config_info_default["contact"] = contact_info
        except:
            # TODO: logging
            pass

    swagger_config["info"] = swagger_config_info_default

    # override it with data from kwargs["info"]
    swagger_config["info"].update(swagger_config_info)

    app["_swagger_config"] = swagger_config

    app.router.add_route("GET", "/swagger.json", swagger_handler)

    return app
1315259
def add_url(self, name: str, pattern: str, application: Callable) -> None:
        
        self.urlmapper.add(name, self.prefix + pattern)
        self.register_app(name, application)
1226447
def declare_api_routes(config):
    """"""
    # The pregenerator makes sure we can generate a path using
    # request.route_path even if we don't have all the variables.
    #
    # For example, instead of having to do this:
    #     request.route_path('resource', hash=hash, ignore='')
    # it's possible to do this:
    #     request.route_path('resource', hash=hash)
    def pregenerator(path):
        # find all the variables in the path
        variables = [(s.split(':')[0], '') for s in path.split('{')[1:]]

        def wrapper(request, elements, kwargs):
            modified_kwargs = dict(variables)
            modified_kwargs.update(kwargs)
            return elements, modified_kwargs
        return wrapper

    def add_route(name, path, *args, **kwargs):
        return config.add_route(name, path, *args,
                                pregenerator=pregenerator(path), **kwargs)

    add_route('content', '/contents/{ident_hash:([^:/@.]+(@[0-9.]*[0-9]+)?)}{separator:(:?)}{page_ident_hash:([^:/@.]+(@[0-9.]*[0-9]+)?)?}{ignore:(/[^/.]*?/?)?}{ext:([.](html|json))?}')  # noqa cnxarchive.views:get_content
    add_route('resource', '/resources/{hash}{ignore:(/.*)?}')  # noqa cnxarchive.views:get_resource
    add_route('export', '/exports/{ident_hash}.{type}{ignore:(/.*)?}')  # noqa cnxarchive.views:get_export
    add_route('extras', '/extras{key:(/(featured|messages|licenses|subjects|languages))?}')  # noqa cnxarchive.views:extras
    add_route('content-extras', '/extras/{ident_hash:([^:/@.]+(@[0-9.]*[0-9]+)?)}{separator:(:?)}{page_ident_hash:([^:/@.]+(@[0-9.]*[0-9]+)?)?}')  # noqa cnxarchive.views:get_extra
    add_route('search', '/search')  # cnxarchive.views:search
    add_route('in-book-search', '/search/{ident_hash:([^:/]+)}')  # noqa cnxarchive.views:in-book-search
    add_route('in-book-search-page', '/search/{ident_hash:([^:/]+)}:{page_ident_hash}')  # noqa cnxarchive.views:in_book_search_highlighted_results
    add_route('sitemap-index', '/sitemap_index.xml')  # noqa cnxarchive.views:sitemap
    add_route('sitemap', '/sitemap-{from_id}.xml')  # noqa cnxarchive.views:sitemap
    add_route('robots', '/robots.txt')  # noqa cnxarchive.views:robots
    add_route('legacy-redirect', '/content/{objid}{ignore:(/)?}')  # noqa cnxarchive.views:redirect_legacy_content
    add_route('legacy-redirect-latest', '/content/{objid}/latest{ignore:(/)?}{filename:(.+)?}')  # noqa cnxarchive.views:redirect_legacy_content
    add_route('legacy-redirect-w-version', '/content/{objid}/{objver}{ignore:(/)?}{filename:(.+)?}')  # noqa cnxarchive.views:redirect_legacy_content
    add_route('recent', '/feeds/recent.rss')  # cnxarchive.views:recent
    add_route('oai', '/feeds/oai')  # cnxarchive.views:oai
    add_route('xpath', '/xpath.html')  # cnxarchive.views.xpath
    add_route('xpath-json', '/xpath.json')
1037826
def setup(self, app: web.Application):
        
        if self.app is app:
            raise ValueError('The router is already configured '
                             'for this application')
        self.app = app
        routes = sorted(
            ((r.name, (r, r.url_for().human_repr())) for r in self.routes()),
            key=utils.sort_key)
        exists = set()  # type: Set[str]
        for name, (route, path) in routes:
            if name and name not in exists:
                exists.add(name)
            else:
                name = None
            app.router.add_route(
                route.method, path,
                route.handler, name=name)
357114
def bind(cls, app, *paths, methods=None, name=None, router=None, view=None):
        """"""
        cls.app = app
        if cls.app is not None:
            for _, m in inspect.getmembers(cls, predicate=inspect.isfunction):
                if not hasattr(m, ROUTE_PARAMS_ATTR):
                    continue
                paths_, methods_, name_ = getattr(m, ROUTE_PARAMS_ATTR)
                name_ = name_ or ("%s.%s" % (cls.name, m.__name__))
                delattr(m, ROUTE_PARAMS_ATTR)
                cls.app.register(*paths_, methods=methods_, name=name_, handler=cls)(m)

        @coroutine
        @functools.wraps(cls)
        def handler(request):
            return cls().dispatch(request, view=view)

        if not paths:
            paths = ["/%s" % cls.__name__]

        return routes_register(
            app, handler, *paths, methods=methods, router=router, name=name or cls.name)