from flask import Flask
from wask.routing import add_route
import req
from . import logger as default_logger
def _uri_to_flask(uri):
path = []
for segment in uri.segments:
if isinstance(segment, req.uri.URIParameter):
path.append("<" + segment.name + ">")
else:
path.append(segment.name)
return "/".join(path)
[docs]def register(app, endpoint, logger=None):
r"""Register ``endpoint`` and all its children with the given Flask
application using the wask adapter library.
Raises:
TypeError: When ``app`` is not a flask.Flask instance.
Parameters:
app (flask.Flask): The application with which to
register the endpoints.
endpoint (Endpoint): The root endpoint to register.
logger (Logger): An optional logger instance to use when
displaying debugging information.
Examples:
>>> import example_app.endpoints
>>> from flask import Flask
>>> import req.wask
>>> app = Flask(__name__)
>>> req.wask.register(app, example_app.endpoints.V1)
"""
if not isinstance(app, Flask):
raise TypeError(
"The application you passed in to 'req.wask.register' "
"is not a valid `flask.Flask` instance."
)
logger = logger or default_logger
for endpoint in endpoint.flatten():
if endpoint.handler is not None:
name = endpoint.name
path = _uri_to_flask(endpoint.full_uri)
handler = endpoint.handler_class
handler.__spec__ = endpoint
logger.debug("Registered endpoint '%s' with path '%s'...", name, path)
add_route(app, path, view_func=handler.as_view(name))