Skip to content

Commit

Permalink
handle custom content types
Browse files Browse the repository at this point in the history
  • Loading branch information
wuan committed Dec 6, 2017
1 parent feaf021 commit 1794690
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES/2594.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixes content type check in client by ignoring content type parameters like encoding etc.
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Alexey Popravka
Alexey Stepanov
Amin Etesamian
Amy Boyle
Andreas Würl
Andrei Ursulenko
Andrej Antonov
Andrew Leech
Expand Down
7 changes: 5 additions & 2 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,8 +795,11 @@ async def json(self, *, encoding=None, loads=json.loads,
await self.read()

if content_type:
ctype = self.headers.get(hdrs.CONTENT_TYPE, '').lower()
if content_type not in ctype:
ctype_header = self.headers.get(hdrs.CONTENT_TYPE, '')
ctype = helpers.strip_mimetype_parameters(ctype_header.lower())

if helpers.strip_mimetype_parameters(
content_type.lower()) not in ctype:
raise ContentTypeError(
self.request_info,
self.history,
Expand Down
4 changes: 4 additions & 0 deletions aiohttp/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,10 @@ def parse_mimetype(mimetype):
parameters=params)


def strip_mimetype_parameters(mimetype):
return mimetype.split(";")[0]


def guess_filename(obj, default=None):
name = getattr(obj, 'name', None)
if name and isinstance(name, str) and name[0] != '<' and name[-1] != '>':
Expand Down
20 changes: 20 additions & 0 deletions tests/test_client_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,26 @@ def side_effect(*args, **kwargs):
assert response._connection is None


async def test_json_custom(loop, session):
response = ClientResponse('get', URL('http://def-cl-resp.org'))
response._post_init(loop, session)

def side_effect(*args, **kwargs):
fut = loop.create_future()
fut.set_result('{"тест": "пройден"}'.encode('cp1251'))
return fut

response.headers = {
'Content-Type': 'application/vnd.aiohttp-test+json;charset=cp1251'}
content = response.content = mock.Mock()
content.read.side_effect = side_effect

res = await response.json(
content_type='application/vnd.aiohttp-test+json; charset=utf-8')
assert res == {'тест': 'пройден'}
assert response._connection is None


async def test_json_custom_loader(loop, session):
response = ClientResponse('get', URL('http://def-cl-resp.org'))
response._post_init(loop, session)
Expand Down

0 comments on commit 1794690

Please sign in to comment.