示例#1
0
def pesquisa_especie(especie=None):
    especies = Especie.find_pesquisa(especie)

    cabeca = txml.Element('especies')

    for (idespecie, especie, genero, habitat, coordenadas, notas, detalhes, nomecomum, codigo, validacao,
         datacriacao) in especies:
            element = txml.SubElement(cabeca, 'c_especie')
            elemento1 = txml.SubElement(element,'idespecie')
            elemento2 = txml.SubElement(element,'especie')
            elemento3 = txml.SubElement(element,'nomecomum')
            elemento4 = txml.SubElement(element,'habitat')

            elemento1.text = "{}".format(idespecie)
            elemento2.text = "{}".format(especie)
            elemento3.text = "{}".format(nomecomum)
            elemento4.text = "{}".format(habitat)

    my_xml = txml.tostring(cabeca)

    b = Response()
    b.set_data(my_xml)
    b.status = "200"
    b.get_json(force=False, silent=True, cache=True)
    b.mimetype = "application/xml"
    return b.get_data()
示例#2
0
def delete_reino(idreino):
    reino = Reino.find_by_id(idreino)
    if reino is not None:
        Reino.delete(idreino)

    b = Response()
    b.set_data("apagado id= {}".format(idreino))
    b.status = "200"
    b.get_json(force=False, silent=True, cache=True)
    b.mimetype = "application/xml"
    return b.get_data()
示例#3
0
def args(response: Response):
    data = response.get_json()
    if data:
        items = data['items'].copy()
        _filter: str = request.args.get('filter')
        _filter_title: str = request.args.get('filter_title')
        _filter_description: str = request.args.get('filter_description')
        limit: int = request.args.get('limit', type=int)

        if _filter:
            items.extend(filter_all(_filter, items))

        if _filter_title:
            items.extend(filter_title(_filter_title, items))

        if _filter_description:
            items.extend(filter_description(_filter_description, items))

        if limit:
            items = items[:limit]

        data['items'] = items
        response.data = json.dumps(data)

    return response
示例#4
0
    def assert_user_resp(self, expect: Expect, resp: Response,
                         expected: EqualDataMixin,
                         http_status: Union[
                             HTTPStatus, range] = HTTPStatus.OK,
                         msg: str = None):
        """
        Assert user response is equal.
        :param expect:      Expected result; one of Expect.SUCCESS or
                            Expect.FAILURE
        :param resp:        response body
        :param expected:    expected entity
        :param http_status: expected HTTPStatus or range of status codes
        :param msg:         assert error message
        """
        if msg is None:
            msg = ""

        self.assertTrue(resp.is_json)
        resp_body = resp.get_json()

        if expect == Expect.SUCCESS:
            self.assert_ok(resp.status_code)
            self.assert_success_response(resp_body)
            self.assert_body_entry(resp_body, RESULT_ONE_USER, MatchParam.EQUAL,
                                   value=expected)
        else:
            if isinstance(http_status, HTTPStatus):
                self.assert_response_status_code(http_status,
                                                 resp.status_code, msg=msg)

            self.assertTrue(resp.is_json)
            self.assert_error_response(resp_body, http_status, '',
                                       MatchParam.IGNORE, msg=msg)
示例#5
0
 def acquire_from_json(self, resp: Response):
     _json = resp.get_json()
     self.id = _json['id']
     self.email = _json['email']
     self.firstname = _json['firstname']
     self.lastname = _json['lastname']
     _stories = _json['stories']
     for st in _stories:
         self.stories.append(st)
示例#6
0
	def after_request(self, response: Response) -> Response:
		g.use.status_code = response.status_code

		g.use.response['content_length'] = response.content_length
		g.use.response['mimetype'] = response.mimetype
		g.use.response['headers'] = response.headers
		g.use.response['body'] = response.get_json()

		return response
示例#7
0
def safellyGetFlaskResponseJson(response: Response):
    jsonBody = None
    try:
        jsonBody = response.get_json(force=True)
    except Exception as exception:
        jsonBody = {}
        log.log(
            safellyGetFlaskResponseJson,
            f'Not possible to get response body. Returning {jsonBody} by default',
            exception=exception)
    return jsonBody
示例#8
0
    def validate_error_response(self, resp: flask.Response,
                                error: t.Union[errors.BaseError,
                                               t.Type[Exception]]):
        def assertEqual(x, y):
            assert x == y

        def assertDictEqual(x, y):
            assert str(x) == str(y)

        assertEqual = self.assertEqual if hasattr(
            self, 'assertEqual') else assertEqual
        assertDictEqual = self.assertDictEqual if hasattr(
            self, 'assertDictEqual') else assertDictEqual

        if inspect.isclass(error):
            assertEqual(error.__qualname__,
                        resp.get_json().get('error').get('type'))
        else:
            assertEqual(error.status_code, resp.status_code)
            assertDictEqual(errors.format_error_content(error),
                            resp.get_json())
示例#9
0
def flask_validate_response(
    request: flask.Request, response: flask.Response
) -> ValidationResult:
    response_data = response.get_json(force=True, silent=True)
    op_name = _api_operation_for_request(request)
    doc_type = _response_schema_types.get(op_name)
    # Only do response validation if it is a successful response status
    if doc_type is not None and (200 <= response.status_code < 299):
        validation_request = ValidationRequest(
            provider_doc_type=doc_type, request_data=response_data
        )
        return request_validator(validation_request)
    else:
        return ValidationResult(errors=[], error_msg=None)
示例#10
0
 def _log_response(response: Response):  # pylint: disable=unused-variable
     data = "INVALID"
     try:
         data = response.get_json() if response.data else "EMPTY"
     except Exception:
         LOGGER.error("Exception while reading json of response.")
     LOGGER.info(
         "Responding to request %s %s: %s - Body: %s",
         request.method,
         request.full_path,
         response.status_code,
         data,
     )
     return response
示例#11
0
    def redact_response(self, method:str, response:Response):
        ''' Redact a response payload bbased on the provided schema '''

        data = response.get_json()
        if method in self.schema:
            method_schema = self.schema[method].copy()
            redactions = method_schema.get('redact', [])

            for redaction in redactions:
                redaction_path = redaction.split('.')
                self._redact(redaction, redaction_path, data)

        response.set_data(dumps(data))
        return response
示例#12
0
 def log_request(r: Response) -> Response:
     latency_ms = (time.perf_counter() - g.start) * 1000
     rl = RequestLogEntry(
         r.status_code,
         request.method,
         request.path,
         request.args,
         None if not log_payloads else request.get_json(silent=True),
         None if not log_payloads else r.get_json(silent=True),
         request.remote_addr,
         request.headers.get("X-Forwarded-For"),
         latency_ms,
         r.headers.get("X-Cache-Hit", "0") == "1",
     )
     logging.getLogger("request").info(asdict(rl))
     return r
示例#13
0
    def assert_role_resp(self,
                         expected: EqualDataMixin,
                         resp: Response,
                         msg: str = None):
        """
        Assert roles list responses are equal.
        """
        if msg is None:
            msg = ""

        self.assert_ok(resp.status_code)

        self.assertTrue(resp.is_json)
        resp_body = resp.get_json()

        self.assert_success_response(resp_body)
        self.assert_body_entry(resp_body,
                               RESULT_ONE_ROLE,
                               MatchParam.EQUAL,
                               value=expected)
示例#14
0
    def assert_roles_list_resp(self,
                               expected: list[EqualDataMixin],
                               resp: Response,
                               msg: str = None):
        """
        Assert roles list responses are equal.
        """
        if msg is None:
            msg = ""

        self.assert_ok(resp.status_code)

        self.assertTrue(resp.is_json)
        resp_body = resp.get_json()

        self.assert_success_response(resp_body)
        self.assert_body_entry(resp_body, RESULT_LIST_ROLES, MatchParam.IGNORE)
        resp_roles = resp_body[RESULT_LIST_ROLES]

        self.assert_roles_list(expected, resp_roles, msg=msg)
示例#15
0
def upload():
    dico = {}
    dico['metadata'] = {}
    output_dir = os.path.join(os.getcwd(),'output_dir/')
    if request.method == 'POST':
        file = request.files['file']
        f_name = request.files["file"].filename
        doc = Document(file, f_name)
        #aiguille l'extraction des métadonnées dépendant de l'extension du document
        _data = doc.refersTo() 
        if 'error' not in list(_data.keys()):
            content = ""
            for key, value in _data.items():
                if key != "content":
                    dico['metadata'][key] = value
                else:
                    dico[key] = value
            dico['metadata']['mime_type'] = request.files["file"].content_type
        else:
            #resp = json.dumps(file_content['error'], ensure_ascii=False) 
            resp = jsonify({'message' : file_content['error']})
            resp.status_code = 400
            return resp
        try:
            #bucket_name = 'boto3-etienne'
            new_file = f_name.split('.')[0] +'.json'

            s3 = boto3.client('s3')
            response = jsonify(dico)
            response.status_code = 200
            s3.upload_fileobj(BytesIO(json.dumps(Response.get_json(response), sort_keys=True, indent=2).encode('utf-8')), bucket_name, new_file)

        except:
            print("Can't write json to S3")
        
        return jsonify(dico)
        #return json.dumps(dico, ensure_ascii=False).encode('utf8')
    else:
        resp = jsonify({'message' : 'Cette méthode ne peut être exécuté que par un POST'})
        resp.status_code = 405
        return resp
示例#16
0
    def assert_users_list_resp(self, expect: Expect, resp: Response,
                               expected: list[EqualDataMixin],
                               http_status: Union[
                                   HTTPStatus, range] = HTTPStatus.OK,
                               msg: str = None):
        """
        Assert users list responses are equal.
        :param expect:      Expected result; one of Expect.SUCCESS or
                            Expect.FAILURE
        :param resp:        response body
        :param expected:    expected list
        :param http_status: expected HTTPStatus or range of status codes
        :param msg:         assert error message
        """
        if msg is None:
            msg = ""

        self.assertTrue(resp.is_json)
        resp_body = resp.get_json()

        if expect == Expect.SUCCESS:
            self.assert_ok(resp.status_code)

            self.assert_success_response(resp_body)
            self.assert_body_entry(resp_body, RESULT_LIST_USERS,
                                   MatchParam.IGNORE)
            resp_users = resp_body[RESULT_LIST_USERS]

            self.assert_users_list(expected, resp_users, msg=msg)
        else:
            if isinstance(http_status, HTTPStatus):
                self.assert_response_status_code(http_status,
                                                 resp.status_code, msg=msg)

            self.assertTrue(resp.is_json)
            self.assert_error_response(resp_body, http_status, '',
                                       MatchParam.IGNORE, msg=msg)
示例#17
0
 def validate_error_response(self, resp: flask.Response,
                             error: errors.BaseError):
     if hasattr(self, 'assertEqual') and hasattr(self, 'assertDictEqual'):
         self.assertEqual(error.status_code, resp.status_code)
         self.assertDictEqual(errors.format_error_content(error),
                              resp.get_json())
示例#18
0
 def after_request(resp: Response) -> Response:
     if isinstance(resp.get_json(), dict):
         # use replace not json.load/dumps for speed
         resp.data = resp.data.replace(b'{', bytes('{\n"request_id":"%s",' % get_request_id(), 'utf-8'), 1)
     return resp
示例#19
0
文件: _test_helper.py 项目: so1n/pait
 def _get_json(resp: Response) -> dict:
     return resp.get_json()