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

Content-Disposition fast access in ClientResponse #2455

Merged
merged 2 commits into from
Nov 7, 2017
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/2455.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Content-Disposition fast access in ClientResponse
20 changes: 18 additions & 2 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,17 @@
from collections import namedtuple
from hashlib import md5, sha1, sha256
from http.cookies import CookieError, Morsel, SimpleCookie
from types import MappingProxyType

from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy
from yarl import URL

from . import hdrs, helpers, http, payload
from . import hdrs, helpers, http, multipart, payload
from .client_exceptions import (ClientConnectionError, ClientOSError,
ClientResponseError, ContentTypeError,
InvalidURL)
from .formdata import FormData
from .helpers import HeadersMixin, TimerNoop, noop
from .helpers import HeadersMixin, TimerNoop, noop, reify
from .http import SERVER_SOFTWARE, HttpVersion10, HttpVersion11, PayloadWriter
from .log import client_logger
from .streams import FlowControlStreamReader
Expand All @@ -33,6 +34,10 @@
__all__ = ('ClientRequest', 'ClientResponse', 'RequestInfo')


ContentDisposition = collections.namedtuple(
'ContentDisposition', ('type', 'parameters', 'filename'))


RequestInfo = collections.namedtuple(
'RequestInfo', ('url', 'method', 'headers'))

Expand Down Expand Up @@ -527,6 +532,7 @@ def __init__(self, method, url, *,
self._request_info = request_info
self._timer = timer if timer is not None else TimerNoop()
self._auto_decompress = auto_decompress
self._cache = {} # reqired for @reify method decorator

@property
def url(self):
Expand All @@ -550,6 +556,16 @@ def _headers(self):
def request_info(self):
return self._request_info

@reify
def content_disposition(self):
raw = self._headers.get(hdrs.CONTENT_DISPOSITION)
if raw is None:
return None
disposition_type, params = multipart.parse_content_disposition(raw)
params = MappingProxyType(params)
filename = multipart.content_disposition_filename(params)
return ContentDisposition(disposition_type, params, filename)

def _post_init(self, loop, session):
self._loop = loop
self._session = session # store a reference to session #1985
Expand Down
24 changes: 23 additions & 1 deletion docs/client_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1109,13 +1109,20 @@ Response object

.. attribute:: charset

Read-only property that specifies the *encoding* for the request's BODY.
Read-only property that specifies the *encoding* for the request's BODY.

The value is parsed from the *Content-Type* HTTP header.

Returns :class:`str` like ``'utf-8'`` or ``None`` if no *Content-Type*
header present in HTTP headers or it has no charset information.

.. attribute:: content_disposition

Read-only property that specified the *Content-Disposition* HTTP header.

Instance of :class:`ContentDisposition` or ``None`` if no *Content-Disposition*
header present in HTTP headers.

.. attribute:: history

A :class:`~collections.abc.Sequence` of :class:`ClientResponse`
Expand Down Expand Up @@ -1589,6 +1596,21 @@ All exceptions are available as members of *aiohttp* module.

Invalid URL, :class:`yarl.URL` instance.

.. class:: ContentDisposition

Represent Content-Disposition header

.. attribute:: value

A :class:`str` instance. Value of Content-Disposition header itself, e.g. ``attachment``.

.. attribute:: filename

A :class:`str` instance. Content filename extracted from parameters. May be ``None``.

.. attribute:: parameters

Read-only mapping contains all parameters.

Response errors
^^^^^^^^^^^^^^^
Expand Down
36 changes: 36 additions & 0 deletions tests/test_client_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,42 @@ def test_charset_no_charset():
assert response.charset is None


def test_content_disposition_full():
response = ClientResponse('get', URL('http://def-cl-resp.org'))
response.headers = {'Content-Disposition':
'attachment; filename="archive.tar.gz"; foo=bar'}

assert 'attachment' == response.content_disposition.type
assert 'bar' == response.content_disposition.parameters["foo"]
assert 'archive.tar.gz' == response.content_disposition.filename
with pytest.raises(TypeError):
response.content_disposition.parameters["foo"] = "baz"


def test_content_disposition_no_parameters():
response = ClientResponse('get', URL('http://def-cl-resp.org'))
response.headers = {'Content-Disposition': 'attachment'}

assert 'attachment' == response.content_disposition.type
assert response.content_disposition.filename is None
assert {} == response.content_disposition.parameters


def test_content_disposition_no_header():
response = ClientResponse('get', URL('http://def-cl-resp.org'))
response.headers = {}

assert response.content_disposition is None


def test_content_disposition_cache():
response = ClientResponse('get', URL('http://def-cl-resp.org'))
response.headers = {'Content-Disposition': 'attachment'}
cd = response.content_disposition
ClientResponse.headers = {'Content-Disposition': 'spam'}
assert cd is response.content_disposition


def test_response_request_info():
url = 'http://def-cl-resp.org'
headers = {'Content-Type': 'application/json;charset=cp1251'}
Expand Down