Skip to content
Myr

Added links property to BaseResponse (#211)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Added docstring and better typing for parsed_header_links * Added docstring and better typing for links property Added tests for it too * Added --diff to black check to see where CI fails Relaxed travis build on master only * Fixed black issue removing a \t * Put noxfile and travis.yml as they were before

authored by euri10 · committed by Seth Michael Larson · parent df8874b · Browse files · 4 files+98 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+98 added−1 removed

  • tests:+45 added−1 removed
  • other:+53 added−0 removed

4 files+98 added−1 removed

modified:httpx/models.py+15 added
32 unmodified lines
33 guess_json_utf,34 is_known_encoding,35 normalize_header_key,36 normalize_header_value,37 parse_header_links,38 str_query_param,39)4041PrimitiveData = typing.Optional[typing.Union[str, int, float, bool]]
794 unmodified lines
836 self._cookies = Cookies()837 self._cookies.extract_cookies(self)838 return self._cookies839840 @property841 def links(self) -> typing.Dict[typing.Optional[str], typing.Dict[str, str]]:842 """843 Returns the parsed header links of the response, if any844 """845 header = self.headers.get("link")846 ldict = {}847 if header:848 links = parse_header_links(header)849 for link in links:850 key = link.get("rel") or link.get("url")851 ldict[key] = link852 return ldict853854 def __repr__(self) -> str:855 return f"<Response [{self.status_code} {self.reason_phrase}]>"856857
353 unmodified lines
modified:httpx/utils.py+38 added
1import codecs2import netrc3import os4import re5import typing6from pathlib import Path78
93 unmodified lines
102 return None103104 netrc_info = netrc.netrc(str(netrc_path))105 return netrc_info.authenticators(host) # type: ignore106107108def parse_header_links(value: str) -> typing.List[typing.Dict[str, str]]:109 """110 Returns a list of parsed link headers, for more info see:111 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link112 The generic syntax of those is:113 Link: < uri-reference >; param1=value1; param2="value2"114 So for instance:115 Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'116 would return117 [118 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},119 {"url": "http://.../back.jpeg"},120 ]121 :param value: HTTP Link entity-header field122 :return: list of parsed link headers123 """124 links: typing.List[typing.Dict[str, str]] = []125 replace_chars = " '\""126 value = value.strip(replace_chars)127 if not value:128 return links129 for val in re.split(", *<", value):130 try:131 url, params = val.split(";", 1)132 except ValueError:133 url, params = val, ""134 link = {"url": url.strip("<> '\"")}135 for param in params.split(";"):136 try:137 key, value = param.split("=")138 except ValueError:139 break140 link[key.strip(replace_chars)] = value.strip(replace_chars)141 links.append(link)142 return links
modified:tests/models/test_responses.py+21 added
288 unmodified lines
289 with pytest.raises(json.JSONDecodeError):290 response.json()291292293@pytest.mark.parametrize(294 "headers, expected",295 [296 (297 {"Link": "<https://example.com>; rel='preload'"},298 {"preload": {"rel": "preload", "url": "https://example.com"}},299 ),300 (301 {"Link": '</hub>; rel="hub", </resource>; rel="self"'},302 {303 "hub": {"url": "/hub", "rel": "hub"},304 "self": {"url": "/resource", "rel": "self"},305 },306 ),307 ],308)309def test_link_headers(headers, expected):310 response = httpx.Response(200, content=None, headers=headers)311 assert response.links == expected312313314@pytest.mark.asyncio315async def test_stream_text():316 async def iterator():317 yield b"Hello, world!"
9 unmodified lines
modified:tests/test_utils.py+24 added-1 removed
1import os23import pytest45from httpx.utils import get_netrc_login, guess_json_utf5from httpx.utils import get_netrc_login, guess_json_utf, parse_header_links678@pytest.mark.parametrize(9 "encoding",
53 unmodified lines
63 "example-username",64 None,65 "example-password",66 )676869@pytest.mark.parametrize(70 "value, expected",71 (72 (73 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',74 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],75 ),76 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),77 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),78 (79 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',80 [81 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},82 {"url": "http://.../back.jpeg"},83 ],84 ),85 ("", []),86 ),87)88def test_parse_header_links(value, expected):89 assert parse_header_links(value) == expected