Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Link header (RFC8288) parsing #2955

Merged
merged 6 commits into from
Apr 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/2948.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added and links property for ClientResponse object
31 changes: 31 additions & 0 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,37 @@ def history(self):
"""A sequence of of responses, if redirects occurred."""
return self._history

@property
def links(self):
links_str = ", ".join(self.headers.getall("link", []))

links = MultiDict()

if not links_str:
return MultiDictProxy(links)

for val in re.split(r",(?=\s*<)", links_str):
url, params = re.match(r"\s*<(.*)>(.*)", val).groups()
params = params.split(";")[1:]

link = MultiDict()

for param in params:
key, _, value, _ = re.match(
r"^\s*(\S*)\s*=\s*(['\"]?)(.*?)(\2)\s*$",
param, re.M
).groups()

link.add(key, value)

key = link.get("rel", url)

link.add("url", self.url.join(URL(url)))

links.add(key, MultiDictProxy(link))

return MultiDictProxy(links)

async def start(self, connection, read_until_eof=False):
"""Start response processing."""
self._closed = False
Expand Down
10 changes: 10 additions & 0 deletions docs/client_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1097,6 +1097,16 @@ Response object
Unmodified HTTP headers of response as unconverted bytes, a sequence of
``(key, value)`` pairs.

.. attribute:: links

Link HTTP header parsed into a :class:`~multidict.MultiDictProxy`.

For each link, key is link param `rel` when it exists, or link url as
:class:`str` otherwise, and value is :class:`~multidict.MultiDictProxy`
of link params and url at key `url` as :class:`~yarl.URL` instance.

.. versionadded:: 3.2

.. attribute:: content_type

Read-only property with *content* part of *Content-Type* header.
Expand Down
157 changes: 157 additions & 0 deletions tests/test_client_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from unittest import mock

import pytest
from multidict import CIMultiDict
from yarl import URL

import aiohttp
Expand Down Expand Up @@ -1033,3 +1034,159 @@ def test_response_real_url(loop, session):
session=session)
assert response.url == url.with_fragment(None)
assert response.real_url == url


def test_response_links_comma_separated(loop, session):
url = URL('http://def-cl-resp.org/')
response = ClientResponse('get', url,
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
auto_decompress=True,
traces=[],
loop=loop,
session=session)
response.headers = CIMultiDict([
(
"Link",
('<http://example.com/page/1.html>; rel=next, '
'<http://example.com/>; rel=home')
)
])
assert (
response.links ==
{'next':
{'url': URL('http://example.com/page/1.html'),
'rel': 'next'},
'home':
{'url': URL('http://example.com/'),
'rel': 'home'}
}
)


def test_response_links_multiple_headers(loop, session):
url = URL('http://def-cl-resp.org/')
response = ClientResponse('get', url,
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
auto_decompress=True,
traces=[],
loop=loop,
session=session)
response.headers = CIMultiDict([
(
"Link",
'<http://example.com/page/1.html>; rel=next'
),
(
"Link",
'<http://example.com/>; rel=home'
)
])
assert (
response.links ==
{'next':
{'url': URL('http://example.com/page/1.html'),
'rel': 'next'},
'home':
{'url': URL('http://example.com/'),
'rel': 'home'}
}
)


def test_response_links_no_rel(loop, session):
url = URL('http://def-cl-resp.org/')
response = ClientResponse('get', url,
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
auto_decompress=True,
traces=[],
loop=loop,
session=session)
response.headers = CIMultiDict([
(
"Link",
'<http://example.com/>'
)
])
assert (
response.links ==
{
'http://example.com/':
{'url': URL('http://example.com/')}
}
)


def test_response_links_quoted(loop, session):
url = URL('http://def-cl-resp.org/')
response = ClientResponse('get', url,
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
auto_decompress=True,
traces=[],
loop=loop,
session=session)
response.headers = CIMultiDict([
(
"Link",
'<http://example.com/>; rel="home-page"'
),
])
assert (
response.links ==
{'home-page':
{'url': URL('http://example.com/'),
'rel': 'home-page'}
}
)


def test_response_links_relative(loop, session):
url = URL('http://def-cl-resp.org/')
response = ClientResponse('get', url,
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
auto_decompress=True,
traces=[],
loop=loop,
session=session)
response.headers = CIMultiDict([
(
"Link",
'</relative/path>; rel=rel'
),
])
assert (
response.links ==
{'rel':
{'url': URL('http://def-cl-resp.org/relative/path'),
'rel': 'rel'}
}
)


def test_response_links_empty(loop, session):
url = URL('http://def-cl-resp.org/')
response = ClientResponse('get', url,
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
auto_decompress=True,
traces=[],
loop=loop,
session=session)
response.headers = CIMultiDict()
assert response.links == {}