Make a schema for a "standard" server response.
    Standard server responses have 'status': True
    and possibly 'indexing': True set.
761816
def json_response_schema( expected_object_schema ):
    
    schema = {
        'type': 'object',
        'properties': {
            'status': {
                'type': 'boolean',
            },
            'indexing': {
                'type': 'boolean',
            },
            'lastblock': {
                'anyOf': [
                    {
                        'type': 'integer',
                        'minimum': 0,
                    },
                    {
                        'type': 'null',
                    },
                ],
            },
        },
        'required': [
            'status',
            'indexing',
            'lastblock'
        ],
    }

    # fold in the given object schema
    schema['properties'].update( expected_object_schema['properties'] )
    schema['required'] = list(set( schema['required'] + expected_object_schema['required'] ))

    return schema
1012855
def build_response(content, code=200):
    """"""
    response = make_response( jsonify(content), content['code'] )
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = \
            'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    return response
31732
def creating_schema_and_index(self, models, func):
        
        waiting_models = []
        self.base_thread.do_with_submit(func, models, waiting_models, threads=self.threads)
        if waiting_models:
            print("WAITING MODELS ARE CHECKING...")
            self.creating_schema_and_index(waiting_models, func)
1236961
def json_response(self, status=200, data={}, headers={}):
        '''
          
        '''
        mimetype = 'application/json'

        header_dict = {}
        for k, v in headers.items():
            header_dict[k] = v

        return Response(
            json.dumps(data),
            status=status,
            mimetype=mimetype,
            headers=header_dict)
1320958
def community_responsify(schema_class, mimetype):
    
    def view(data, code=200, headers=None, links_item_factory=None,
             page=None, urlkwargs=None, links_pagination_factory=None):
        """Generate the response object."""
        if isinstance(data, Community):
            last_modified = data.updated
            response_data = schema_class(
                context=dict(item_links_factory=links_item_factory)
            ).dump(data).data
        else:
            last_modified = None
            response_data = schema_class(
                context=dict(
                    total=data.query.count(),
                    item_links_factory=links_item_factory,
                    page=page,
                    urlkwargs=urlkwargs,
                    pagination_links_factory=links_pagination_factory)
            ).dump(data.items, many=True).data

        response = current_app.response_class(
            json.dumps(response_data, **_format_args()),
            mimetype=mimetype)
        response.status_code = code

        if last_modified:
            response.last_modified = last_modified

        if headers is not None:
            response.headers.extend(headers)
        return response
    return view
1350786
def _set_index(self, schema, name, fields, **index_options):
        
        query_str = "CREATE {}INDEX IF NOT EXISTS '{}_{}' ON {} ({})".format(
            'UNIQUE ' if index_options.get('unique', False) else '',
            schema,
            name,
            self._normalize_table_name(schema),
            ', '.join((self._normalize_name(f) for f in fields))
        )

        return self._query(query_str, ignore_result=True, **index_options)
1253509
def _response(status, body=nil, headers={})
      body = [body].compact
      headers = headers.merge("Content-Type" => "application/json")
      Rack::Response.new(body, status, headers).finish
    end
878920
def record_schemas(
        fn, wrapper, location, request_schema=None, response_schema=None):
    """"""
    # have we already been decorated by an acceptable api call?
    has_acceptable = hasattr(fn, '_acceptable_metadata')

    if request_schema is not None:
        # preserve schema for later use
        wrapper._request_schema = wrapper._request_schema = request_schema
        wrapper._request_schema_location = location
        if has_acceptable:
            fn._acceptable_metadata._request_schema = request_schema
            fn._acceptable_metadata._request_schema_location = location

    if response_schema is not None:
        # preserve schema for later use
        wrapper._response_schema = wrapper._response_schema = response_schema
        wrapper._response_schema_location = location
        if has_acceptable:
            fn._acceptable_metadata._response_schema = response_schema
            fn._acceptable_metadata._response_schema_location = location
10791
function createResponse(request, response, body){
  return {
    statusCode: response.statusCode,
    statusText: response.statusMessage,
    headers: response.headers,
    originalUrl: request.url,
    effectiveUrl: request.url,
    redirected: false,
    requestMethod: request.method,
    requestHeaders: request.headers,
    body: body,
    retries: 0,
    throttled: false
  };
}
816994
def __CreateVoidResponseType(self, method_description):
        """"""
        schema = {}
        method_name = self.__names.ClassName(
            method_description['id'], separator='.')
        schema['id'] = self.__names.ClassName('%sResponse' % method_name)
        schema['type'] = 'object'
        schema['description'] = 'An empty %s response.' % method_name
        self.__message_registry.AddDescriptorFromSchema(schema['id'], schema)
        return schema['id']
581340
def resolve_schema_in_request_body(self, request_body):
        
        content = request_body["content"]
        for content_type in content:
            schema = content[content_type]["schema"]
            content[content_type]["schema"] = self.openapi.resolve_schema_dict(schema)
124617
function buildResponse(data) {
    var response = {};
    response.totalItems = data.length;
    response.itemsPerPage = itemsPerPage;
    response.totalPages = itemsPerPage === null ? 1 : Math.ceil(data.length / itemsPerPage);
    response.currentPage = itemsPerPage === null ? 1 : currentPage;
    response.data = itemsPerPage === null ? data : data.slice(itemsPerPage * (currentPage - 1), itemsPerPage);

    return response;
}
351040
def schema(self):
        
        attrs = self.attrs.copy()
        parts = ["CREATE", "TABLE", self.name, "(%s," % self.hash_key.schema]
        del attrs[self.hash_key.name]
        if self.range_key:
            parts.append(self.range_key.schema + ",")
            del attrs[self.range_key.name]
        if attrs:
            attr_def = ", ".join([attr.schema for attr in itervalues(attrs)])
            parts.append(attr_def + ",")

        parts.append(
            "THROUGHPUT (%d, %d))" % (self.read_throughput, self.write_throughput)
        )
        parts.extend([g.schema for g in itervalues(self.global_indexes)])
        return " ".join(parts) + ";"
288278
async def parse_response(response: ClientResponse, schema: dict) -> Any:
    
    try:
        data = await response.json()
        response.close()
        if schema is not None:
            jsonschema.validate(data, schema)
        return data
    except (TypeError, json.decoder.JSONDecodeError) as e:
        raise jsonschema.ValidationError("Could not parse json : {0}".format(str(e)))
553600
def oaiserver(sets, records):
    """"""
    from invenio_db import db
    from invenio_oaiserver.models import OAISet
    from invenio_records.api import Record

    # create a OAI Set
    with db.session.begin_nested():
        for i in range(sets):
            db.session.add(OAISet(
                spec='test{0}'.format(i),
                name='Test{0}'.format(i),
                description='test desc {0}'.format(i),
                search_pattern='title_statement.title:Test{0}'.format(i),
            ))

    # create a record
    schema = {
        'type': 'object',
        'properties': {
            'title_statement': {
                'type': 'object',
                'properties': {
                    'title': {
                        'type': 'string',
                    },
                },
            },
            'field': {'type': 'boolean'},
        },
    }

    with app.app_context():
        indexer = RecordIndexer()
        with db.session.begin_nested():
            for i in range(records):
                record_id = uuid.uuid4()
                data = {
                    'title_statement': {'title': 'Test{0}'.format(i)},
                    '$schema': schema,
                }
                recid_minter(record_id, data)
                oaiid_minter(record_id, data)
                record = Record.create(data, id_=record_id)
                indexer.index(record)

        db.session.commit()
987552
def swagger_schema(self, request):
        """"""
        if self.parent is None:
            return {}

        spec = APISpec(
            self.parent.name, self.parent.cfg.get('VERSION', ''),
            plugins=['apispec.ext.marshmallow'], basePatch=self.prefix
        )

        for paths, handler in self.handlers.items():
            spec.add_tag({
                'name': handler.name,
                'description': utils.dedent(handler.__doc__ or ''),
            })
            for path in paths:
                operations = {}
                for http_method in handler.methods:
                    method = getattr(handler, http_method.lower())
                    operation = OrderedDict({
                        'tags': [handler.name],
                        'summary': method.__doc__,
                        'produces': ['application/json'],
                        'responses': {200: {'schema': {'$ref': {'#/definitions/' + handler.name}}}}
                    })
                    operation.update(utils.load_yaml_from_docstring(method.__doc__) or {})
                    operations[http_method.lower()] = operation

                spec.add_path(self.prefix + path, operations=operations)

            if getattr(handler, 'Schema', None):
                kwargs = {}
                if getattr(handler.meta, 'model', None):
                    kwargs['description'] = utils.dedent(handler.meta.model.__doc__ or '')
                spec.definition(handler.name, schema=handler.Schema, **kwargs)

        return deepcopy(spec.to_dict())
1003175
def _BuildResponse(self,
                     status,
                     rendered_data,
                     method_name=None,
                     headers=None,
                     content_length=None,
                     token=None,
                     no_audit_log=False):
    """"""

    # To avoid IE content sniffing problems, escape the tags. Otherwise somebody
    # may send a link with malicious payload that will be opened in IE (which
    # does content sniffing and doesn't respect Content-Disposition header) and
    # IE will treat the document as html and executre arbitrary JS that was
    # passed with the payload.
    str_data = json.Dump(
        rendered_data, encoder=JSONEncoderWithRDFPrimitivesSupport)
    # XSSI protection and tags escaping
    rendered_data = ")]}'\n" + str_data.replace("<", r"\u003c").replace(
        ">", r"\u003e")

    response = werkzeug_wrappers.Response(
        rendered_data,
        status=status,
        content_type="application/json; charset=utf-8")
    response.headers[
        "Content-Disposition"] = "attachment; filename=response.json"
    response.headers["X-Content-Type-Options"] = "nosniff"

    if token and token.reason:
      response.headers["X-GRR-Reason"] = utils.SmartStr(token.reason)
    if method_name:
      response.headers["X-API-Method"] = method_name
    if no_audit_log:
      response.headers["X-No-Log"] = "True"

    for key, value in iteritems(headers or {}):
      response.headers[key] = value

    if content_length is not None:
      response.content_length = content_length

    return response