Bind the service API urls to a flask app.
3868
def bind(self, flask_app, service, group=None):
        """"""
        if group not in self.services[service]:
            raise RuntimeError(
                'API group {} does not exist in service {}'.format(
                    group, service)
            )
        for name, api in self.services[service][group].items():
            # only bind APIs that have views associated with them
            if api.view_fn is None:
                continue
            if name not in flask_app.view_functions:
                flask_app.add_url_rule(
                    api.url, name, view_func=api.view_fn, **api.options)
179230
def jsonify(resource):
    

    response = flask.jsonify(resource.to_dict())
    response = add_link_headers(response, resource.links())
    return response
528351
protected function mapApiRoutes(): void
    {
        $file = $this->basePath.'routes/api.php';

        if (file_exists($file)) {
            $this->loadRoutesFrom(
            Route::prefix('api')
                ->middleware('api')
                ->group($file));
        }
    }
386524
def add_swagger(app, json_route, html_route, **kwargs):
    
    spec = getattr(app, SWAGGER_ATTR_NAME)
    if spec:
        spec = spec.swagger_definition(**kwargs)
    else:
        spec = {}
    encoded_spec = json.dumps(spec).encode("UTF-8")

    @app.route(json_route)
    def swagger():
        return Response(
            encoded_spec,
            # we allow CORS, so this can be requested at swagger.io
            headers={"Access-Control-Allow-Origin": "*"},
            content_type="application/json",
        )

    # add the statics
    static_root = get_swagger_static_root()
    swagger_body = generate_swagger_html(
        STATIC_PATH, json_route
    ).encode("utf-8")

    @app.route(html_route)
    def swagger_ui():
        return Response(swagger_body, content_type="text/html")

    # the blueprint work is the easiest way to integrate a static
    # directory into flask.
    blueprint = Blueprint('swagger', __name__, static_url_path=STATIC_PATH,
                          static_folder=static_root)
    app.register_blueprint(blueprint)
1360518
def url_for(self, resource, **kwargs):
        
        if self.blueprint:
            return flask.url_for('.' + resource.endpoint, **kwargs)
        return flask.url_for(resource.endpoint, **kwargs)
692979
def _load_apis(self):
        """"""
        helpscout = __import__('helpscout.apis')
        for class_name in helpscout.apis.__all__:
            if not class_name.startswith('_'):
                cls = getattr(helpscout.apis, class_name)
                api = AuthProxy(self.session, cls)
                setattr(self, class_name, api)
                self.__apis__[class_name] = api
1109827
def _register_file_server(self, app):
        
        if isinstance(self.driver, local.LocalStorageDriver) \
                and self.config["serve_files"]:
            server_url = self.config["serve_files_url"].strip("/").strip()
            if server_url:
                url = "/%s/<path:object_name>" % server_url

                @app.route(url, endpoint=SERVER_ENDPOINT)
                def files_server(object_name):
                    obj = self.get(object_name)
                    if obj is not None:
                        dl = flask_request.args.get("dl")
                        name = flask_request.args.get("name", obj.name)

                        if get_file_extension(name) != obj.extension:
                            name += ".%s" % obj.extension

                        _url = obj.get_cdn_url()
                        return send_file(_url,
                                         as_attachment=True if dl else False,
                                         attachment_filename=name,
                                         conditional=True)
                    else:
                        abort(404)
            else:
                warnings.warn("Flask-Cloudy can't serve files. 'STORAGE_SERVER_FILES_URL' is not set")
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
647286
def dispatch_request(self):
        """"""

        req = _request_ctx_stack.top.request
        app = current_app

        # Return flask's default options response. See issue #40
        if req.method == "OPTIONS":
            return app.make_default_options_response()

        if req.routing_exception is not None:
            app.raise_routing_exception(req)

        # The routing rule has some handy attributes to extract how Flask found
        # this endpoint
        rule = req.url_rule

        # Wrap the real view_func
        view_func = self.wrap_view_func(
            app, rule, req, app.view_functions[rule.endpoint], req.view_args
        )

        return view_func(**req.view_args)
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")
1362892
def _get_service_bindings(self, service_name):
        
        instance = self.get_instance(service_name)
        return self.api.get(instance['service_bindings_url'])
1338538
def assign_routes(self, app):
        """"""
        for grp in self.filters:
            for f in self.filters[grp]:
                if f.route_func:
                    f.register_route(app)

        for c in self.charts:
            if c.route_func:
                c.register_route(app)
527160
def serve_doc(app, url):
    
    @app.route(url, doc=False)
    def index(env, req):
        ret = ''
        for d in env['doc']:
            ret += 'URL: {url}, supported methods: {methods}{doc}\n'.format(**d)
        return ret
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]
1315750
def start_flask_service(self):
        
        app = Flask(__name__)
        self.app = app

        @app.route('/')
        def home():
            return 'Elephas'

        @app.route('/parameters', methods=['GET'])
        def handle_get_parameters():
            if self.mode == 'asynchronous':
                self.lock.acquire_read()
            self.pickled_weights = pickle.dumps(self.weights, -1)
            pickled_weights = self.pickled_weights
            if self.mode == 'asynchronous':
                self.lock.release()
            return pickled_weights

        @app.route('/update', methods=['POST'])
        def handle_update_parameters():
            delta = pickle.loads(request.data)
            if self.mode == 'asynchronous':
                self.lock.acquire_write()

            if not self.master_network.built:
                self.master_network.build()

            # Just apply the gradient
            weights_before = self.weights
            self.weights = subtract_params(weights_before, delta)

            if self.mode == 'asynchronous':
                self.lock.release()
            return 'Update done'

        master_url = determine_master(self.port)
        host = master_url.split(':')[0]
        self.app.run(host=host, debug=self.debug, port=self.port,
                     threaded=self.threaded, use_reloader=self.use_reloader)
841769
def init_app(self, app):
        
        host = app.config.get('STATS_HOSTNAME', 'localhost')
        port = app.config.get('STATS_PORT', 8125)
        base_key = app.config.get('STATS_BASE_KEY', app.name)

        client = _StatsClient(
            host=host,
            port=port,
            prefix=base_key,
        )

        app.before_request(client.flask_time_start)
        app.after_request(client.flask_time_end)

        if not hasattr(app, 'extensions'):
            app.extensions = {}
        app.extensions.setdefault('stats', {})
        app.extensions['stats'][self] = client

        return client
91573
def request_context(app, request):
    
    vars = {}
    if request.view_args is not None:
        vars.update(request.view_args)
    vars.update({
        "request": request,
        "GET": AttrDict(request.args.to_dict()),
        "POST" : AttrDict(request.form.to_dict()),
        "app": app,
        "config": app.config,
        "session": session,
        "g": g,
        "now": datetime.datetime.now,
        "utcnow": datetime.datetime.utcnow,
        "today": datetime.date.today})
    context = Context(vars)
    context.vars["current_context"] = context
    return context