How to use the httpx.Response function in httpx

To help you get started, weā€™ve selected a few httpx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github encode / httpx / tests / models / test_responses.py View on Github external
def test_response_non_text_encoding():
    """
    Default to apparent encoding for non-text content-type headers.
    """
    headers = {"Content-Type": "image/png"}
    response = httpx.Response(200, content=b"xyz", headers=headers, request=REQUEST)
    assert response.text == "xyz"
    assert response.encoding == "ascii"
github iGeeky / open-account / test / pycore / http_client.py View on Github external
log.info("REQUEST [ %s ] timeout: %s", req_debug, timeout_str)

    res = Response({"status": 500, "body":  None, "headers": NewHeaders()})
    server_ip = ""
    begin = time.time()
    req = {}
    try:
        client:httpx.Client = httpx.Client(verify=False, timeout=timeout)
        if method == "PUT" or method == "POST" or method == "DELETE":
            resp:httpx.Response = client.request(method=method, url=url, data=body, params=args, headers=headers)
        else:
            resp:httpx.Response = client.request(method=method, url=url, params=args, headers=headers)
    except Exception as e:
        msg = 'REQUEST [ %s ] failed! err: %s' %(req_debug, e)
        log.error(msg)
        resp = httpx.Response(status_code=500, content='', headers={}, json={})
        res = Response({"status": 500, "body":  str(traceback.format_exc()), "headers": NewHeaders(), "rawResp": resp, "json": {}})
    else:
        status = resp.status_code
        body = resp.content
        res = Response({"status": status, "body": body, "headers": dict(resp.headers.items()), "rawResp": resp, "json": resp.json()})

    duration = time.time()-begin
    res.duration = duration

    if res.status >= 400:
        log.warning("FAIL REQUEST [ %s ] status: %s, duration: %.3f body: %s", req_debug, res.status, duration, res.body)
    else:
        log.info ("REQUEST [ %s ] status: %s, duration: %.3f", req_debug, res.status, duration)
    res.req_debug = req_debug

    return res
github encode / httpx / tests / models / test_responses.py View on Github external
def test_response():
    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)
    assert response.status_code == 200
    assert response.reason_phrase == "OK"
    assert response.text == "Hello, world!"
    assert response.request is REQUEST
    assert response.elapsed == datetime.timedelta(0)
    assert not response.is_error
github encode / httpx / tests / models / test_responses.py View on Github external
def test_json_without_specified_encoding_decode_error():
    data = {"greeting": "hello", "recipient": "world"}
    content = json.dumps(data).encode("utf-32-be")
    headers = {"Content-Type": "application/json"}
    # force incorrect guess from `guess_json_utf` to trigger error
    with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):
        response = httpx.Response(
            200, content=content, headers=headers, request=REQUEST
        )
        with pytest.raises(json.JSONDecodeError):
            response.json()
github lepture / authlib / tests / py3 / utils.py View on Github external
async def send(self, request, verify=None, cert=None, timeout=None):
        if self.assert_func:
            self.assert_func(request)

        return Response(
            self.status_code,
            content=self.body,
            headers=self.headers,
            request=request,
        )
github encode / httpx / tests / test_decoders.py View on Github external
def test_multi():
    body = b"test 123"

    deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
    compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()

    gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
    compressed_body = (
        gzip_compressor.compress(compressed_body) + gzip_compressor.flush()
    )

    headers = [(b"Content-Encoding", b"deflate, gzip")]
    response = httpx.Response(
        200, headers=headers, content=compressed_body, request=REQUEST
    )
    assert response.content == body
github encode / httpx / tests / client / test_redirects.py View on Github external
count = int(params.get("count", "0")[0])
            redirect_count = count - 1
            code = codes.SEE_OTHER if count else codes.OK
            location = "/multiple_redirects"
            if redirect_count:
                location += "?count=" + str(redirect_count)
            headers = {"location": location} if count else {}
            return Response(code, headers=headers, request=request)

        if request.url.path == "/redirect_loop":
            headers = {"location": "/redirect_loop"}
            return Response(codes.SEE_OTHER, headers=headers, request=request)

        elif request.url.path == "/cross_domain":
            headers = {"location": "https://example.org/cross_domain_target"}
            return Response(codes.SEE_OTHER, headers=headers, request=request)

        elif request.url.path == "/cross_domain_target":
            headers = dict(request.headers.items())
            content = json.dumps({"headers": headers}).encode()
            return Response(codes.OK, content=content, request=request)

        elif request.url.path == "/redirect_body":
            headers = {"location": "/redirect_body_target"}
            return Response(codes.PERMANENT_REDIRECT, headers=headers, request=request)

        elif request.url.path == "/redirect_no_body":
            content = b"".join([part async for part in request.stream])
            headers = {"location": "/redirect_body_target"}
            return Response(codes.SEE_OTHER, headers=headers, request=request)

        elif request.url.path == "/redirect_body_target":
github encode / httpx / tests / models / test_responses.py View on Github external
async def test_bytes_interface():
    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)

    content = b""
    async for part in response.aiter_bytes():
        content += part
    assert content == b"Hello, world!"
github encode / httpx / tests / client / test_headers.py View on Github external
async def send(
        self,
        request: Request,
        verify: VerifyTypes = None,
        cert: CertTypes = None,
        timeout: TimeoutTypes = None,
    ) -> Response:
        if request.url.path.startswith("/echo_headers"):
            request_headers = dict(request.headers.items())
            body = json.dumps({"headers": request_headers}).encode()
            return Response(200, content=body, request=request)