Serve predictions as an API endpoint.
972570
def serve(self, host='127.0.0.1', port=5000):
        """"""
        from meinheld import server, middleware
        # self.app.run(host=host, port=port)
        server.listen((host, port))
        server.run(middleware.WebSocketMiddleware(self.app))
1372821
function Api(spec, options) {
  if (!(this instanceof Api)) {
    return new Api(spec, options);
  }

  if (typeof spec !== 'object') {
    throw new Error('api spec must be an object');
  }

  options = options || {};

  // path alias for both resourcePath and doc path
  if (spec.path) {
    if (!spec.resourcePath) spec.resourcePath = spec.path;
    if (!options.path) options.path = spec.path;
    delete spec.path;
  }

  // allow user to pass description in spec
  if (spec.description) {
    if (!options.description) options.description = spec.description;
    delete spec.description;
  }

  // user resourcePath for doc path if not set
  if (!options.path && spec.resourcePath) {
    options.path = spec.resourcePath;
  }

  debug('create api %s', spec.resourcePath, spec);

  this.env = new Environment();

  this.spec = spec;
  this.list = [];
  this.options = options;

  this.middleware = {};
  this.models = {};
  this.nicknames = {};
  this.resources = {};
}
836400
def api(name, url, token, **kwargs):
    """"""
    return Client(token).api(name, url, **kwargs)
397988
def put(self, endpoint: str, **kwargs) -> dict:
        """"""

        return self._request('PUT', endpoint, **kwargs)
650003
def post(self, endpoint: str, **kwargs) -> dict:
        """"""

        return self._request('POST', endpoint, **kwargs)
301600
def call_on_each_endpoint(self, callback):
        

        if 'paths' not in self.swagger_dict:
            return

        for path, d in list(self.swagger_dict['paths'].items()):
            for method, op_spec in list(d.items()):
                data = EndpointData(path, method)

                # Which server method handles this endpoint?
                if 'x-bind-server' not in op_spec:
                    if 'x-no-bind-server' in op_spec:
                        # That route should not be auto-generated
                        log.info("Skipping generation of %s %s" % (method, path))
                        continue
                    else:
                        raise Exception("Swagger api defines no x-bind-server for %s %s" % (method, path))
                data.handler_server = op_spec['x-bind-server']

                # Make sure that endpoint only produces 'application/json'
                if 'produces' not in op_spec:
                    raise Exception("Swagger api has no 'produces' section for %s %s" % (method, path))
                if len(op_spec['produces']) != 1:
                    raise Exception("Expecting only one type under 'produces' for %s %s" % (method, path))
                if op_spec['produces'][0] == 'application/json':
                    data.produces_json = True
                elif op_spec['produces'][0] == 'text/html':
                    data.produces_html = True
                else:
                    raise Exception("Only 'application/json' or 'text/html' are supported. See %s %s" % (method, path))

                # Which client method handles this endpoint?
                if 'x-bind-client' in op_spec:
                    data.handler_client = op_spec['x-bind-client']

                # Should we decorate the server handler?
                if 'x-decorate-server' in op_spec:
                    data.decorate_server = op_spec['x-decorate-server']

                # Should we manipulate the requests parameters?
                if 'x-decorate-request' in op_spec:
                    data.decorate_request = op_spec['x-decorate-request']

                # Generate a bravado-core operation object
                data.operation = Operation.from_spec(self.spec, path, method, op_spec)

                # Figure out how parameters are passed: one json in body? one or
                # more values in query?
                if 'parameters' in op_spec:
                    params = op_spec['parameters']
                    for p in params:
                        if p['in'] == 'body':
                            data.param_in_body = True
                        if p['in'] == 'query':
                            data.param_in_query = True
                        if p['in'] == 'path':
                            data.param_in_path = True

                    if data.param_in_path:
                        # Substitute {...} with <...> in path, to make a Flask friendly path
                        data.path = data.path.replace('{', '<').replace('}', '>')

                    if data.param_in_body and data.param_in_query:
                        raise Exception("Cannot support params in both body and param (%s %s)" % (method, path))

                else:
                    data.no_params = True

                callback(data)
1183440
def api_call(endpoint, args, payload):
    
    headers = {'content-type': 'application/json; ; charset=utf-8'}
    url = 'https://{}/{}'.format(args['--server'], endpoint)
    attempt = 0
    resp = None

    while True:
        try:
            attempt += 1
            resp = requests.post(
                url, data=json.dumps(payload), headers=headers,
                verify=args['--cacert']
            )
            resp.raise_for_status()
            break
        except (socket_timeout, requests.Timeout,
                requests.ConnectionError, requests.URLRequired) as ex:
            abort('{}'.format(ex))
        except requests.HTTPError as ex:
            warn('Requests HTTP error: {}'.format(ex))
            if attempt >= 5:
                abort('Too many HTTP errors.')
    if resp is not None:
        try:
            return resp.json()
        except ValueError:
            abort('Unexpected response from server:\n\n{}'.format(resp.text))
    else:
        abort("Couldn't POST to Red October")
102532
def fetch(cls, id, api_key=None, endpoint=None, add_headers=None,
              **kwargs):
        
        if endpoint is None:
            endpoint = cls.get_endpoint()

        inst = cls(api_key=api_key)
        parse_key = cls.sanitize_ep(endpoint).split("/")[-1]
        endpoint = '/'.join((endpoint, id))
        data = cls._parse(inst.request('GET',
                                       endpoint=endpoint,
                                       add_headers=add_headers,
                                       query_params=kwargs),
                          key=parse_key)
        inst._set(data)
        return inst
68335
def setup_endpoints(provider):
    """"""
    app_routing = {}
    endpoints = [
        AuthorizationEndpoint(
            pyoidcMiddleware(provider.authorization_endpoint)),
        TokenEndpoint(
            pyoidcMiddleware(provider.token_endpoint)),
        UserinfoEndpoint(
            pyoidcMiddleware(provider.userinfo_endpoint)),
        RegistrationEndpoint(
            pyoidcMiddleware(provider.registration_endpoint)),
        EndSessionEndpoint(
            pyoidcMiddleware(provider.endsession_endpoint))
    ]

    for ep in endpoints:
        app_routing["/{}".format(ep.etype)] = ep

    return app_routing
458168
def fetch(params, endpoint_path = 'previews')
      options = prepare_request(params)
      response = default_connection(BASE_URL, params.debug)
                   .post do |req|
                    req.url("/v2/#{endpoint_path}/")
                     req.body = JSON.generate(options)
                   end

      parse(response.body)
    end
1258982
def __call_api(self, path, params=None, api_url=FORECAST_URL):
        
        if not params:
            params = dict()
        payload = {'key': self.api_key}
        payload.update(params)
        url = "%s/%s" % (api_url, path)

        # Add a timeout to the request.
        # The value of 1 second is based on attempting 100 connections to
        # datapoint and taking ten times the mean connection time (rounded up).
        # Could expose to users in the functions which need to call the api.
        #req = requests.get(url, params=payload, timeout=1)
        # The wrapper function __retry_session returns a requests.Session
        # object. This has a .get() function like requests.get(), so the use
        # doesn't change here.

        sess = self.__retry_session()
        req = sess.get(url, params=payload, timeout=1)

        try:
            data = req.json()
        except ValueError:
            raise APIException("DataPoint has not returned any data, this could be due to an incorrect API key")
        self.call_response = data
        if req.status_code != 200:
            msg = [data[m] for m in ("message", "error_message", "status") \
                      if m in data][0]
            raise Exception(msg)
        return data
1254561
def get(self, endpoint: str, **kwargs) -> dict:
        """"""

        return self._request('GET', endpoint, **kwargs)
1330440
def endpoint(url, method="GET", expected_status=200):
    
    def dec(obj):
        obj.ENDPOINT = url
        obj.METHOD = method
        obj.EXPECTED_STATUS = expected_status
        return obj

    return dec
863017
def to_model(self):
        """"""
        e = ApiPool().current_server_api.model.Error(
            status=self.status,
            error=self.code.upper(),
            error_description=str(self),
        )
        if self.error_id:
            e.error_id = self.error_id
        if self.user_message:
            e.user_message = self.user_message
        if self.error_caught:
            e.error_caught = pformat(self.error_caught)
        return e
1301559
def predictions_iter(self):
        
        for fname in self.forecast_names:
            yield self.predictions.get(col_names=fname)
230334
def _get_results_from_api(identifiers, endpoints, api_key, api_secret):
    """"""

    if api_key is not None and api_secret is not None:
        client = housecanary.ApiClient(api_key, api_secret)
    else:
        client = housecanary.ApiClient()

    wrapper = getattr(client, endpoints[0].split('/')[0])

    if len(endpoints) > 1:
        # use component_mget to request multiple endpoints in one call
        return wrapper.component_mget(identifiers, endpoints)
    else:
        return wrapper.fetch_identifier_component(endpoints[0], identifiers)
620035
def generate_endpoint_classes(db, generate_pks=False):
    """"""
    seen_classes = set()
    for cls in current_app.class_references.values():
        seen_classes.add(cls.__tablename__)
    with app.app_context():
        db.metadata.reflect(bind=db.engine)
        for name, table in db.metadata.tables.items():
            if not name in seen_classes:
                seen_classes.add(name)
                if not table.primary_key and generate_pks:
                    cls = add_pk_if_required(db, table, name)
                else:
                    cls = type(
                        str(name),
                        (sandman_model, db.Model),
                        {'__tablename__': name})
                register(cls)