diff options
| author | Piotr Ożarowski <piotr@debian.org> | 2016-07-28 23:32:19 +0200 |
|---|---|---|
| committer | git-ubuntu importer <ubuntu-devel-discuss@lists.ubuntu.com> | 2016-07-29 10:19:30 +0000 |
| commit | f9353b46c0ff9198dff57cdfd639a50693f12a1e (patch) | |
| tree | 6ccec5999a604c01575b1e80247ee27da9fc43fd | |
| parent | 47ced8171bdb48ff1f72277e61a067de22453f3f (diff) | |
| parent | be1a4719556e163fe2f43d790fe93b1320b1703b (diff) | |
0.22.4-1 (patches applied)applied/0.22.4-1applied/ubuntu/yakkety-proposedapplied/ubuntu/yakkety-develapplied/ubuntu/yakkety
Imported using git-ubuntu import.
114 files changed, 8110 insertions, 21928 deletions
diff --git a/CHANGES.txt b/CHANGES.txt index 84d44de..9b5862e 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,11 +1,125 @@ CHANGES ======= -0.20.2 (01-07-2015) --------------------- +0.22.3 (07-26-2016) +------------------- -- Enable use of `await` for a class based view #717 +- Do not filter cookies if unsafe flag provided #1005 -- Check address family to fill wsgi env properly #718 -- Fix memory leak in headers processing (thanks to Marco Paolini) #723 +0.22.2 (07-23-2016) +------------------- + +- Suppress CancelledError when Timeout raises TimeoutError #970 + +- Don't expose `aiohttp.__version__` + +- Add unsafe parameter to CookieJar #968 + +- Use unsafe cookie jar in test client tools + +- Expose aiohttp.CookieJar name + + +0.22.1 (07-16-2016) +------------------- + +- Large cookie expiration/max-age doesn't break an event loop from now + (fixes #967) + + +0.22.0 (07-15-2016) +------------------- + +- Fix bug in serving static directory #803 + +- Fix command line arg parsing #797 + +- Fix a documentation chapter about cookie usage #790 + +- Handle empty body with gzipped encoding #758 + +- Support 451 Unavailable For Legal Reasons http status #697 + +- Fix Cookie share example and few small typos in docs #817 + +- UrlDispatcher.add_route with partial coroutine handler #814 + +- Optional support for aiodns #728 + +- Add ServiceRestart and TryAgainLater websocket close codes #828 + +- Fix prompt message for `web.run_app` #832 + +- Allow to pass None as a timeout value to disable timeout logic #834 + +- Fix leak of connection slot during connection erro #835 + +- Gunicorn worker with uvloop support `aiohttp.worker.GunicornUVLoopWebWorker` #878 + +- Don't send body in response to HEAD request #838 + +- Skip the preamble in MultipartReader #881 + +- Implement BasicAuth decode classmethod. #744 + +- Don't crash logger when transport is None #889 + +- Use a create_future compatibility wrapper instead of creating + Futures directly #896 + +- Add test utilities to aiohttp #902 + +- Improve Request.__repr__ #875 + +- Skip DNS resolving if provided host is already an ip address #874 + +- Add headers to ClientSession.ws_connect #785 + +- Document that server can send pre-compressed data #906 + +- Don't add Content-Encoding and Transfer-Encoding if no body #891 + +- Add json() convenience methods to websocket message objects #897 + +- Add client_resp.raise_for_status() #908 + +- Implement cookie filter #799 + +- Include an example of middleware to handle error pages #909 + +- Fix error handling in StaticFileMixin #856 + +- Add mocked request helper #900 + +- Fix empty ALLOW Response header for cls based View #929 + +- Respect CONNECT method to implement a proxy server #847 + +- Add pytest_plugin #914 + +- Add tutorial + +- Add backlog option to support more than 128 (default value in + "create_server" function) concurrent connections #892 + +- Allow configuration of header size limits #912 + +- Separate sending file logic from StaticRoute dispatcher #901 + +- Drop deprecated share_cookies connector option (BACKWARD INCOMPATIBLE) + +- Drop deprecated support for tuple as auth paramter. + Use aiohttp.BasicAuth instead (BACKWARD INCOMPATIBLE) + +- Remove deprecated `request.payload` property, use `content` instead. + (BACKWARD INCOMPATIBLE) + +- Drop all mentions about api changes in documentaion for versions + older than 0.16 + +- Allow to override default cookie jar #963 + +- Add manylinux wheel builds + +- Dup a socket for sendfile usage #964 diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index b6d680e..e1a9a00 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -5,19 +5,23 @@ A. Jesse Jiryu Davis Alejandro Gómez Alex Khomchenko Alex Lisovoy +Alex Key Alexander Bayandin Alexander Karpinsky Alexander Malev Alexander Shorin Alexander Travov Alexey Popravka +Amy Boyle Andrei Ursulenko Andrej Antonov Andrew Svetlov +Andrii Soldatenko Anton Kasyanov Arthur Darcet Ben Bader Benedikt Reinartz +Brett Cannon Brian C. Lane Boris Feld Carl George @@ -25,11 +29,13 @@ Chien-Wei Huang Chih-Yuan Chen Chris Laws Chris Moore +Daniel García Daniel Nelson David Michael Brown Dima Veselov Dimitar Dimitrov Dmytro Kuznetsov +Dustin J. Mitchell Elizabeth Leddy Erich Healy Eugene Chernyshov @@ -41,6 +47,7 @@ Greg Holt Hugo Herter Igor Pavlov Ingmar Steen +Jacob Champion Jaesung Lee Jashandeep Sohi Jeroen van der Heijden @@ -53,6 +60,8 @@ Kirill Klenov Kirill Malovitsa Kyrylo Perevozchikov Lars P. Søndergaard +Louis-Philippe Huberdeau +Lubomir Gelo Ludovic Gasc Lukasz Marcin Dobrzanski Marco Paolini @@ -61,6 +70,7 @@ Mathias Fröjdman Matthieu Hauglustaine Michael Ihnatenko Mikhail Lukyanchenko +Misha Behersky Morgan Delahaye-Prat Moss Collum Nicolas Braem @@ -72,14 +82,17 @@ Philipp A. Raúl Cumplido "Required Field" <requiredfield256@gmail.com> Robert Lu +Samuel Colvin Sebastian Hanula Sebastian Hüther Sergey Ninua Sergey Skripnick Simon Kennedy +Sin-Woo Bang Stanislas Plum Stanislav Prokop Stephen Granade +Steven Seguin Sviatoslav Bulbakha Taras Voinarovskyi Tolga Tezel @@ -93,5 +106,9 @@ Vladimir Rutsky Vladimir Shulyak Vladimir Zakharov W. Trevor King +Willem de Groot Yannick Koechlin -Коренберг Марк +Yury Selivanov +Yusuke Tsutsumi +Марк Коренберг +Семён Марьясин @@ -8,8 +8,8 @@ flake: .install-deps # python setup.py check -rms flake8 aiohttp if python -c "import sys; sys.exit(sys.version_info < (3,5))"; then \ - flake8 examples tests; \ - fi + flake8 examples tests; \ + fi .develop: .install-deps $(shell find aiohttp -type f) @@ -26,13 +26,13 @@ cov cover coverage: tox cov-dev: .develop - py.test --cov=aiohttp --cov-report=term --cov-report=html tests + py.test --cov=aiohttp --cov-report=term --cov-report=html tests @echo "open file://`pwd`/coverage/index.html" cov-dev-full: .develop - AIOHTTP_NO_EXTENSIONS=1 py.test --cov=aiohttp --cov-append tests - PYTHONASYNCIODEBUG=1 py.test --cov=aiohttp --cov-append tests - py.test --cov=aiohttp --cov-report=term --cov-report=html tests + AIOHTTP_NO_EXTENSIONS=1 py.test --cov=aiohttp --cov-append tests + PYTHONASYNCIODEBUG=1 py.test --cov=aiohttp --cov-append tests + py.test --cov=aiohttp --cov-report=term --cov-report=html tests @echo "open file://`pwd`/coverage/index.html" clean: @@ -54,6 +54,10 @@ clean: rm -f aiohttp/_multidict.c rm -f aiohttp/_multidict.*.so rm -f aiohttp/_multidict.*.pyd + rm -f aiohttp/_websocket.html + rm -f aiohttp/_websocket.c + rm -f aiohttp/_websocket.*.so + rm -f aiohttp/_websocket.*.pyd rm -rf .tox doc: @@ -1,6 +1,6 @@ Metadata-Version: 1.1 Name: aiohttp -Version: 0.20.2 +Version: 0.22.4 Summary: http client/server for asyncio Home-page: https://github.com/KeepSafe/aiohttp/ Author: Andrew Svetlov @@ -46,24 +46,17 @@ Description: http client/server for asyncio import aiohttp import asyncio - async def get_body(client, url): - async with client.get(url) as response: - return await response.read() + async def fetch(session, url): + with aiohttp.Timeout(10): + async with session.get(url) as response: + return await response.text() if __name__ == '__main__': loop = asyncio.get_event_loop() - client = aiohttp.ClientSession(loop=loop) - raw_html = loop.run_until_complete(get_body(client, 'http://python.org')) - print(raw_html) - client.close() - - - If you want to use timeouts for aiohttp client please use standard - asyncio approach: - - .. code-block:: python - - yield from asyncio.wait_for(client.get(url), 10) + with aiohttp.ClientSession(loop=loop) as session: + html = loop.run_until_complete( + fetch(session, 'http://python.org')) + print(html) Server @@ -73,7 +66,6 @@ Description: http client/server for asyncio .. code-block:: python - import asyncio from aiohttp import web async def handle(request): @@ -96,19 +88,11 @@ Description: http client/server for asyncio return ws - async def init(loop): - app = web.Application(loop=loop) - app.router.add_route('GET', '/echo', wshandler) - app.router.add_route('GET', '/{name}', handle) - - srv = await loop.create_server(app.make_handler(), - '127.0.0.1', 8080) - print("Server started at http://127.0.0.1:8080") - return srv + app = web.Application() + app.router.add_route('GET', '/echo', wshandler) + app.router.add_route('GET', '/{name}', handle) - loop = asyncio.get_event_loop() - loop.run_until_complete(init(loop)) - loop.run_forever() + web.run_app(app) Note: examples are written for Python 3.5+ and utilize PEP-492 aka @@ -127,7 +111,7 @@ Description: http client/server for asyncio Documentation ------------- - http://aiohttp.readthedocs.org/ + https://aiohttp.readthedocs.io/ Discussion list --------------- @@ -166,14 +150,128 @@ Description: http client/server for asyncio CHANGES ======= - 0.20.2 (01-07-2015) - -------------------- + 0.22.3 (07-26-2016) + ------------------- + + - Do not filter cookies if unsafe flag provided #1005 + + + 0.22.2 (07-23-2016) + ------------------- + + - Suppress CancelledError when Timeout raises TimeoutError #970 + + - Don't expose `aiohttp.__version__` + + - Add unsafe parameter to CookieJar #968 + + - Use unsafe cookie jar in test client tools + + - Expose aiohttp.CookieJar name + + + 0.22.1 (07-16-2016) + ------------------- + + - Large cookie expiration/max-age doesn't break an event loop from now + (fixes #967) + + + 0.22.0 (07-15-2016) + ------------------- + + - Fix bug in serving static directory #803 + + - Fix command line arg parsing #797 + + - Fix a documentation chapter about cookie usage #790 + + - Handle empty body with gzipped encoding #758 + + - Support 451 Unavailable For Legal Reasons http status #697 + + - Fix Cookie share example and few small typos in docs #817 + + - UrlDispatcher.add_route with partial coroutine handler #814 + + - Optional support for aiodns #728 + + - Add ServiceRestart and TryAgainLater websocket close codes #828 + + - Fix prompt message for `web.run_app` #832 + + - Allow to pass None as a timeout value to disable timeout logic #834 + + - Fix leak of connection slot during connection erro #835 + + - Gunicorn worker with uvloop support `aiohttp.worker.GunicornUVLoopWebWorker` #878 + + - Don't send body in response to HEAD request #838 + + - Skip the preamble in MultipartReader #881 + + - Implement BasicAuth decode classmethod. #744 + + - Don't crash logger when transport is None #889 + + - Use a create_future compatibility wrapper instead of creating + Futures directly #896 + + - Add test utilities to aiohttp #902 + + - Improve Request.__repr__ #875 + + - Skip DNS resolving if provided host is already an ip address #874 + + - Add headers to ClientSession.ws_connect #785 + + - Document that server can send pre-compressed data #906 + + - Don't add Content-Encoding and Transfer-Encoding if no body #891 + + - Add json() convenience methods to websocket message objects #897 + + - Add client_resp.raise_for_status() #908 + + - Implement cookie filter #799 + + - Include an example of middleware to handle error pages #909 + + - Fix error handling in StaticFileMixin #856 + + - Add mocked request helper #900 + + - Fix empty ALLOW Response header for cls based View #929 + + - Respect CONNECT method to implement a proxy server #847 + + - Add pytest_plugin #914 + + - Add tutorial + + - Add backlog option to support more than 128 (default value in + "create_server" function) concurrent connections #892 + + - Allow configuration of header size limits #912 + + - Separate sending file logic from StaticRoute dispatcher #901 + + - Drop deprecated share_cookies connector option (BACKWARD INCOMPATIBLE) + + - Drop deprecated support for tuple as auth paramter. + Use aiohttp.BasicAuth instead (BACKWARD INCOMPATIBLE) + + - Remove deprecated `request.payload` property, use `content` instead. + (BACKWARD INCOMPATIBLE) + + - Drop all mentions about api changes in documentaion for versions + older than 0.16 - - Enable use of `await` for a class based view #717 + - Allow to override default cookie jar #963 - - Check address family to fill wsgi env properly #718 + - Add manylinux wheel builds - - Fix memory leak in headers processing (thanks to Marco Paolini) #723 + - Dup a socket for sendfile usage #964 Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Intended Audience :: Developers @@ -38,24 +38,17 @@ To retrieve something from the web: import aiohttp import asyncio - async def get_body(client, url): - async with client.get(url) as response: - return await response.read() + async def fetch(session, url): + with aiohttp.Timeout(10): + async with session.get(url) as response: + return await response.text() if __name__ == '__main__': loop = asyncio.get_event_loop() - client = aiohttp.ClientSession(loop=loop) - raw_html = loop.run_until_complete(get_body(client, 'http://python.org')) - print(raw_html) - client.close() - - -If you want to use timeouts for aiohttp client please use standard -asyncio approach: - -.. code-block:: python - - yield from asyncio.wait_for(client.get(url), 10) + with aiohttp.ClientSession(loop=loop) as session: + html = loop.run_until_complete( + fetch(session, 'http://python.org')) + print(html) Server @@ -65,7 +58,6 @@ This is simple usage example: .. code-block:: python - import asyncio from aiohttp import web async def handle(request): @@ -88,19 +80,11 @@ This is simple usage example: return ws - async def init(loop): - app = web.Application(loop=loop) - app.router.add_route('GET', '/echo', wshandler) - app.router.add_route('GET', '/{name}', handle) - - srv = await loop.create_server(app.make_handler(), - '127.0.0.1', 8080) - print("Server started at http://127.0.0.1:8080") - return srv + app = web.Application() + app.router.add_route('GET', '/echo', wshandler) + app.router.add_route('GET', '/{name}', handle) - loop = asyncio.get_event_loop() - loop.run_until_complete(init(loop)) - loop.run_forever() + web.run_app(app) Note: examples are written for Python 3.5+ and utilize PEP-492 aka @@ -119,7 +103,7 @@ shoud be replaced by:: Documentation ------------- -http://aiohttp.readthedocs.org/ +https://aiohttp.readthedocs.io/ Discussion list --------------- diff --git a/aiohttp.egg-info/PKG-INFO b/aiohttp.egg-info/PKG-INFO index f3e2d0e..0d205d3 100644 --- a/aiohttp.egg-info/PKG-INFO +++ b/aiohttp.egg-info/PKG-INFO @@ -1,6 +1,6 @@ Metadata-Version: 1.1 Name: aiohttp -Version: 0.20.2 +Version: 0.22.4 Summary: http client/server for asyncio Home-page: https://github.com/KeepSafe/aiohttp/ Author: Andrew Svetlov @@ -46,24 +46,17 @@ Description: http client/server for asyncio import aiohttp import asyncio - async def get_body(client, url): - async with client.get(url) as response: - return await response.read() + async def fetch(session, url): + with aiohttp.Timeout(10): + async with session.get(url) as response: + return await response.text() if __name__ == '__main__': loop = asyncio.get_event_loop() - client = aiohttp.ClientSession(loop=loop) - raw_html = loop.run_until_complete(get_body(client, 'http://python.org')) - print(raw_html) - client.close() - - - If you want to use timeouts for aiohttp client please use standard - asyncio approach: - - .. code-block:: python - - yield from asyncio.wait_for(client.get(url), 10) + with aiohttp.ClientSession(loop=loop) as session: + html = loop.run_until_complete( + fetch(session, 'http://python.org')) + print(html) Server @@ -73,7 +66,6 @@ Description: http client/server for asyncio .. code-block:: python - import asyncio from aiohttp import web async def handle(request): @@ -96,19 +88,11 @@ Description: http client/server for asyncio return ws - async def init(loop): - app = web.Application(loop=loop) - app.router.add_route('GET', '/echo', wshandler) - app.router.add_route('GET', '/{name}', handle) - - srv = await loop.create_server(app.make_handler(), - '127.0.0.1', 8080) - print("Server started at http://127.0.0.1:8080") - return srv + app = web.Application() + app.router.add_route('GET', '/echo', wshandler) + app.router.add_route('GET', '/{name}', handle) - loop = asyncio.get_event_loop() - loop.run_until_complete(init(loop)) - loop.run_forever() + web.run_app(app) Note: examples are written for Python 3.5+ and utilize PEP-492 aka @@ -127,7 +111,7 @@ Description: http client/server for asyncio Documentation ------------- - http://aiohttp.readthedocs.org/ + https://aiohttp.readthedocs.io/ Discussion list --------------- @@ -166,14 +150,128 @@ Description: http client/server for asyncio CHANGES ======= - 0.20.2 (01-07-2015) - -------------------- + 0.22.3 (07-26-2016) + ------------------- + + - Do not filter cookies if unsafe flag provided #1005 + + + 0.22.2 (07-23-2016) + ------------------- + + - Suppress CancelledError when Timeout raises TimeoutError #970 + + - Don't expose `aiohttp.__version__` + + - Add unsafe parameter to CookieJar #968 + + - Use unsafe cookie jar in test client tools + + - Expose aiohttp.CookieJar name + + + 0.22.1 (07-16-2016) + ------------------- + + - Large cookie expiration/max-age doesn't break an event loop from now + (fixes #967) + + + 0.22.0 (07-15-2016) + ------------------- + + - Fix bug in serving static directory #803 + + - Fix command line arg parsing #797 + + - Fix a documentation chapter about cookie usage #790 + + - Handle empty body with gzipped encoding #758 + + - Support 451 Unavailable For Legal Reasons http status #697 + + - Fix Cookie share example and few small typos in docs #817 + + - UrlDispatcher.add_route with partial coroutine handler #814 + + - Optional support for aiodns #728 + + - Add ServiceRestart and TryAgainLater websocket close codes #828 + + - Fix prompt message for `web.run_app` #832 + + - Allow to pass None as a timeout value to disable timeout logic #834 + + - Fix leak of connection slot during connection erro #835 + + - Gunicorn worker with uvloop support `aiohttp.worker.GunicornUVLoopWebWorker` #878 + + - Don't send body in response to HEAD request #838 + + - Skip the preamble in MultipartReader #881 + + - Implement BasicAuth decode classmethod. #744 + + - Don't crash logger when transport is None #889 + + - Use a create_future compatibility wrapper instead of creating + Futures directly #896 + + - Add test utilities to aiohttp #902 + + - Improve Request.__repr__ #875 + + - Skip DNS resolving if provided host is already an ip address #874 + + - Add headers to ClientSession.ws_connect #785 + + - Document that server can send pre-compressed data #906 + + - Don't add Content-Encoding and Transfer-Encoding if no body #891 + + - Add json() convenience methods to websocket message objects #897 + + - Add client_resp.raise_for_status() #908 + + - Implement cookie filter #799 + + - Include an example of middleware to handle error pages #909 + + - Fix error handling in StaticFileMixin #856 + + - Add mocked request helper #900 + + - Fix empty ALLOW Response header for cls based View #929 + + - Respect CONNECT method to implement a proxy server #847 + + - Add pytest_plugin #914 + + - Add tutorial + + - Add backlog option to support more than 128 (default value in + "create_server" function) concurrent connections #892 + + - Allow configuration of header size limits #912 + + - Separate sending file logic from StaticRoute dispatcher #901 + + - Drop deprecated share_cookies connector option (BACKWARD INCOMPATIBLE) + + - Drop deprecated support for tuple as auth paramter. + Use aiohttp.BasicAuth instead (BACKWARD INCOMPATIBLE) + + - Remove deprecated `request.payload` property, use `content` instead. + (BACKWARD INCOMPATIBLE) + + - Drop all mentions about api changes in documentaion for versions + older than 0.16 - - Enable use of `await` for a class based view #717 + - Allow to override default cookie jar #963 - - Check address family to fill wsgi env properly #718 + - Add manylinux wheel builds - - Fix memory leak in headers processing (thanks to Marco Paolini) #723 + - Dup a socket for sendfile usage #964 Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Intended Audience :: Developers diff --git a/aiohttp.egg-info/SOURCES.txt b/aiohttp.egg-info/SOURCES.txt index d55cc08..6aea001 100644 --- a/aiohttp.egg-info/SOURCES.txt +++ b/aiohttp.egg-info/SOURCES.txt @@ -7,8 +7,6 @@ README.rst setup.cfg setup.py aiohttp/__init__.py -aiohttp/_multidict.c -aiohttp/_multidict.pyx aiohttp/_websocket.c aiohttp/_websocket.pyx aiohttp/abc.py @@ -16,13 +14,15 @@ aiohttp/client.py aiohttp/client_reqrep.py aiohttp/connector.py aiohttp/errors.py +aiohttp/file_sender.py aiohttp/hdrs.py aiohttp/helpers.py aiohttp/log.py -aiohttp/multidict.py aiohttp/multipart.py aiohttp/parsers.py aiohttp/protocol.py +aiohttp/pytest_plugin.py +aiohttp/resolver.py aiohttp/server.py aiohttp/signals.py aiohttp/streams.py @@ -39,29 +39,30 @@ aiohttp/wsgi.py aiohttp.egg-info/PKG-INFO aiohttp.egg-info/SOURCES.txt aiohttp.egg-info/dependency_links.txt -aiohttp.egg-info/pbr.json aiohttp.egg-info/requires.txt aiohttp.egg-info/top_level.txt docs/Makefile +docs/abc.rst docs/aiohttp-icon.ico docs/aiohttp-icon.svg -docs/aiohttp_doctools.py docs/api.rst docs/changes.rst docs/client.rst docs/client_reference.rst docs/conf.py docs/contributing.rst +docs/faq.rst docs/glossary.rst docs/gunicorn.rst docs/index.rst docs/logging.rst docs/make.bat -docs/multidict.rst docs/multipart.rst -docs/python33.rst +docs/new_router.rst docs/server.rst docs/spelling_wordlist.txt +docs/testing.rst +docs/tutorial.rst docs/web.rst docs/web_reference.rst docs/_static/aiohttp-icon-128x128.png @@ -69,6 +70,7 @@ docs/_static/aiohttp-icon-32x32.png docs/_static/aiohttp-icon-64x64.png docs/_static/aiohttp-icon-96x96.png examples/basic_srv.py +examples/cli_app.py examples/client_auth.py examples/client_json.py examples/crawl.py @@ -103,28 +105,35 @@ tests/test_errors.py tests/test_flowcontrol_streams.py tests/test_helpers.py tests/test_http_parser.py -tests/test_multidict.py tests/test_multipart.py tests/test_parser_buffer.py tests/test_protocol.py tests/test_proxy_connector.py +tests/test_pytest_plugin.py +tests/test_resolver.py +tests/test_run_app.py tests/test_server.py tests/test_signals.py tests/test_stream_parser.py tests/test_stream_protocol.py tests/test_stream_writer.py tests/test_streams.py +tests/test_test_utils.py tests/test_timeout.py tests/test_urldispatch.py tests/test_web_application.py +tests/test_web_cli.py tests/test_web_exceptions.py tests/test_web_functional.py tests/test_web_middleware.py tests/test_web_request.py tests/test_web_request_handler.py tests/test_web_response.py +tests/test_web_urldispatcher.py tests/test_web_websocket.py tests/test_web_websocket_functional.py +tests/test_web_websocket_functional_oldstyle.py +tests/test_websendfile.py tests/test_websocket_client.py tests/test_websocket_client_functional.py tests/test_websocket_handshake.py diff --git a/aiohttp.egg-info/pbr.json b/aiohttp.egg-info/pbr.json deleted file mode 100644 index b79d6eb..0000000 --- a/aiohttp.egg-info/pbr.json +++ /dev/null @@ -1 +0,0 @@ -{"git_version": "bf5f5ca", "is_release": false}
\ No newline at end of file diff --git a/aiohttp.egg-info/requires.txt b/aiohttp.egg-info/requires.txt index 79236f2..62c059e 100644 --- a/aiohttp.egg-info/requires.txt +++ b/aiohttp.egg-info/requires.txt @@ -1 +1,2 @@ chardet +multidict>=1.1.0,<2 diff --git a/aiohttp/__init__.py b/aiohttp/__init__.py index fb05bb0..87662e2 100644 --- a/aiohttp/__init__.py +++ b/aiohttp/__init__.py @@ -1,8 +1,11 @@ -# This relies on each of the submodules having an __all__ variable. +__version__ = '0.22.4' -__version__ = '0.20.2' +# Deprecated, keep it here for a while for backward compatibility. +import multidict # noqa +# This relies on each of the submodules having an __all__ variable. +from multidict import * # noqa from . import hdrs # noqa from .protocol import * # noqa from .connector import * # noqa @@ -12,20 +15,20 @@ from .errors import * # noqa from .helpers import * # noqa from .parsers import * # noqa from .streams import * # noqa -from .multidict import * # noqa from .multipart import * # noqa from .websocket_client import * # noqa +from .file_sender import FileSender # noqa -__all__ = (client.__all__ + - client_reqrep.__all__ + - errors.__all__ + - helpers.__all__ + - parsers.__all__ + - protocol.__all__ + - connector.__all__ + - streams.__all__ + - multidict.__all__ + - multipart.__all__ + - websocket_client.__all__ + - ('hdrs', '__version__')) +__all__ = (client.__all__ + # noqa + client_reqrep.__all__ + # noqa + errors.__all__ + # noqa + helpers.__all__ + # noqa + parsers.__all__ + # noqa + protocol.__all__ + # noqa + connector.__all__ + # noqa + streams.__all__ + # noqa + multidict.__all__ + # noqa + multipart.__all__ + # noqa + websocket_client.__all__ + # noqa + ('hdrs', 'FileSender')) diff --git a/aiohttp/_multidict.c b/aiohttp/_multidict.c deleted file mode 100644 index 23a97a1..0000000 --- a/aiohttp/_multidict.c +++ /dev/null @@ -1,17283 +0,0 @@ -/* Generated by Cython 0.23.4 */ - -/* BEGIN: Cython Metadata -{ - "distutils": {} -} -END: Cython Metadata */ - -#define PY_SSIZE_T_CLEAN -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) - #error Cython requires Python 2.6+ or Python 3.2+. -#else -#define CYTHON_ABI "0_23_4" -#include <stddef.h> -#ifndef offsetof -#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION -#define CYTHON_COMPILING_IN_PYPY 1 -#define CYTHON_COMPILING_IN_CPYTHON 0 -#else -#define CYTHON_COMPILING_IN_PYPY 0 -#define CYTHON_COMPILING_IN_CPYTHON 1 -#endif -#if !defined(CYTHON_USE_PYLONG_INTERNALS) && CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x02070000 -#define CYTHON_USE_PYLONG_INTERNALS 1 -#endif -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) -#define Py_OptimizeFlag 0 -#endif -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyType_Type -#endif -#ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 -#endif -#ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) -#else - #define CYTHON_PEP393_ENABLED 0 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) -#endif -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) - #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) -#endif -#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY - #ifndef PyUnicode_InternFromString - #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) - #endif -#endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) -#else - #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif -#if PY_VERSION_HEX >= 0x030500B1 -#define __Pyx_PyAsyncMethodsStruct PyAsyncMethods -#define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) -#elif CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -typedef struct { - unaryfunc am_await; - unaryfunc am_aiter; - unaryfunc am_anext; -} __Pyx_PyAsyncMethodsStruct; -#define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) -#else -#define __Pyx_PyType_AsAsync(obj) NULL -#endif -#ifndef CYTHON_RESTRICT - #if defined(__GNUC__) - #define CYTHON_RESTRICT __restrict__ - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - #define CYTHON_RESTRICT __restrict - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_RESTRICT restrict - #else - #define CYTHON_RESTRICT - #endif -#endif -#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) - -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -#if defined(WIN32) || defined(MS_WINDOWS) - #define _USE_MATH_DEFINES -#endif -#include <math.h> -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#define __PYX_HAVE__aiohttp___multidict -#define __PYX_HAVE_API__aiohttp___multidict -#ifdef _OPENMP -#include <omp.h> -#endif /* _OPENMP */ - -#ifdef PYREX_WITHOUT_ASSERTIONS -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -#ifndef CYTHON_NCP_UNUSED -# if CYTHON_COMPILING_IN_CPYTHON -# define CYTHON_NCP_UNUSED -# else -# define CYTHON_NCP_UNUSED CYTHON_UNUSED -# endif -#endif -typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_uchar_cast(c) ((unsigned char)c) -#define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ - (sizeof(type) < sizeof(Py_ssize_t)) ||\ - (sizeof(type) > sizeof(Py_ssize_t) &&\ - likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX) &&\ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ - v == (type)PY_SSIZE_T_MIN))) ||\ - (sizeof(type) == sizeof(Py_ssize_t) &&\ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX))) ) -#if defined (__cplusplus) && __cplusplus >= 201103L - #include <cstdlib> - #define __Pyx_sst_abs(value) std::abs(value) -#elif SIZEOF_INT >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) abs(value) -#elif SIZEOF_LONG >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) labs(value) -#elif defined (_MSC_VER) && defined (_M_X64) - #define __Pyx_sst_abs(value) _abs64(value) -#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define __Pyx_sst_abs(value) llabs(value) -#elif defined (__GNUC__) - #define __Pyx_sst_abs(value) __builtin_llabs(value) -#else - #define __Pyx_sst_abs(value) ((value<0) ? -value : value) -#endif -static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) -#if PY_MAJOR_VERSION < 3 -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) -{ - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} -#else -#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen -#endif -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) -#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -#define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -#if CYTHON_COMPILING_IN_CPYTHON -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -/* Test for GCC > 2.95 */ -#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) -#else /* !__GNUC__ or GCC < 2.95 */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ - -static PyObject *__pyx_m; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - - -static const char *__pyx_f[] = { - "aiohttp/_multidict.pyx", -}; - -/*--- Type declarations ---*/ -struct __pyx_obj_7aiohttp_10_multidict__Pair; -struct __pyx_obj_7aiohttp_10_multidict__Base; -struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy; -struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy; -struct __pyx_obj_7aiohttp_10_multidict_MultiDict; -struct __pyx_obj_7aiohttp_10_multidict_CIMultiDict; -struct __pyx_obj_7aiohttp_10_multidict__ViewBase; -struct __pyx_obj_7aiohttp_10_multidict__ViewBaseSet; -struct __pyx_obj_7aiohttp_10_multidict__ItemsIter; -struct __pyx_obj_7aiohttp_10_multidict__ItemsView; -struct __pyx_obj_7aiohttp_10_multidict__ValuesIter; -struct __pyx_obj_7aiohttp_10_multidict__ValuesView; -struct __pyx_obj_7aiohttp_10_multidict__KeysIter; -struct __pyx_obj_7aiohttp_10_multidict__KeysView; -struct __pyx_defaults; -typedef struct __pyx_defaults __pyx_defaults; -struct __pyx_defaults { - PyObject *__pyx_arg_encoding; -}; - -/* "aiohttp/_multidict.pyx":47 - * - * - * cdef class _Pair: # <<<<<<<<<<<<<< - * cdef object _key - * cdef object _value - */ -struct __pyx_obj_7aiohttp_10_multidict__Pair { - PyObject_HEAD - PyObject *_key; - PyObject *_value; -}; - - -/* "aiohttp/_multidict.pyx":66 - * return left._key != right._key and left._value != right._value - * - * cdef class _Base: # <<<<<<<<<<<<<< - * - * cdef list _items - */ -struct __pyx_obj_7aiohttp_10_multidict__Base { - PyObject_HEAD - struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *__pyx_vtab; - PyObject *_items; - PyObject *_upstr; - PyObject *marker; -}; - - -/* "aiohttp/_multidict.pyx":194 - * - * - * cdef class MultiDictProxy(_Base): # <<<<<<<<<<<<<< - * - * def __init__(self, arg): - */ -struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy { - struct __pyx_obj_7aiohttp_10_multidict__Base __pyx_base; -}; - - -/* "aiohttp/_multidict.pyx":213 - * - * - * cdef class CIMultiDictProxy(MultiDictProxy): # <<<<<<<<<<<<<< - * - * def __init__(self, arg): - */ -struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy { - struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy __pyx_base; -}; - - -/* "aiohttp/_multidict.pyx":238 - * - * - * cdef class MultiDict(_Base): # <<<<<<<<<<<<<< - * """An ordered dictionary that can have multiple values for each key.""" - * - */ -struct __pyx_obj_7aiohttp_10_multidict_MultiDict { - struct __pyx_obj_7aiohttp_10_multidict__Base __pyx_base; -}; - - -/* "aiohttp/_multidict.pyx":408 - * - * - * cdef class CIMultiDict(MultiDict): # <<<<<<<<<<<<<< - * """An ordered dictionary that can have multiple values for each key.""" - * - */ -struct __pyx_obj_7aiohttp_10_multidict_CIMultiDict { - struct __pyx_obj_7aiohttp_10_multidict_MultiDict __pyx_base; -}; - - -/* "aiohttp/_multidict.pyx":421 - * - * - * cdef class _ViewBase: # <<<<<<<<<<<<<< - * - * cdef list _items - */ -struct __pyx_obj_7aiohttp_10_multidict__ViewBase { - PyObject_HEAD - PyObject *_items; -}; - - -/* "aiohttp/_multidict.pyx":432 - * - * - * cdef class _ViewBaseSet(_ViewBase): # <<<<<<<<<<<<<< - * - * def __richcmp__(self, other, op): - */ -struct __pyx_obj_7aiohttp_10_multidict__ViewBaseSet { - struct __pyx_obj_7aiohttp_10_multidict__ViewBase __pyx_base; -}; - - -/* "aiohttp/_multidict.pyx":497 - * - * - * cdef class _ItemsIter: # <<<<<<<<<<<<<< - * cdef list _items - * cdef int _current - */ -struct __pyx_obj_7aiohttp_10_multidict__ItemsIter { - PyObject_HEAD - PyObject *_items; - int _current; - int _len; -}; - - -/* "aiohttp/_multidict.pyx":518 - * - * - * cdef class _ItemsView(_ViewBaseSet): # <<<<<<<<<<<<<< - * - * def isdisjoint(self, other): - */ -struct __pyx_obj_7aiohttp_10_multidict__ItemsView { - struct __pyx_obj_7aiohttp_10_multidict__ViewBaseSet __pyx_base; -}; - - -/* "aiohttp/_multidict.pyx":553 - * - * - * cdef class _ValuesIter: # <<<<<<<<<<<<<< - * cdef list _items - * cdef int _current - */ -struct __pyx_obj_7aiohttp_10_multidict__ValuesIter { - PyObject_HEAD - PyObject *_items; - int _current; - int _len; -}; - - -/* "aiohttp/_multidict.pyx":574 - * - * - * cdef class _ValuesView(_ViewBase): # <<<<<<<<<<<<<< - * - * def __contains__(self, value): - */ -struct __pyx_obj_7aiohttp_10_multidict__ValuesView { - struct __pyx_obj_7aiohttp_10_multidict__ViewBase __pyx_base; -}; - - -/* "aiohttp/_multidict.pyx":600 - * - * - * cdef class _KeysIter: # <<<<<<<<<<<<<< - * cdef list _items - * cdef int _current - */ -struct __pyx_obj_7aiohttp_10_multidict__KeysIter { - PyObject_HEAD - PyObject *_items; - int _current; - int _len; -}; - - -/* "aiohttp/_multidict.pyx":621 - * - * - * cdef class _KeysView(_ViewBaseSet): # <<<<<<<<<<<<<< - * - * def isdisjoint(self, other): - */ -struct __pyx_obj_7aiohttp_10_multidict__KeysView { - struct __pyx_obj_7aiohttp_10_multidict__ViewBaseSet __pyx_base; -}; - - - -/* "aiohttp/_multidict.pyx":66 - * return left._key != right._key and left._value != right._value - * - * cdef class _Base: # <<<<<<<<<<<<<< - * - * cdef list _items - */ - -struct __pyx_vtabstruct_7aiohttp_10_multidict__Base { - PyObject *(*_upper)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *); - PyObject *(*_getall)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *, PyObject *); - PyObject *(*_getone)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *, PyObject *); - PyObject *(*_contains)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *); - PyObject *(*keys)(struct __pyx_obj_7aiohttp_10_multidict__Base *, int __pyx_skip_dispatch); - PyObject *(*_eq_to_mapping)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *); -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *__pyx_vtabptr_7aiohttp_10_multidict__Base; - - -/* "aiohttp/_multidict.pyx":194 - * - * - * cdef class MultiDictProxy(_Base): # <<<<<<<<<<<<<< - * - * def __init__(self, arg): - */ - -struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDictProxy { - struct __pyx_vtabstruct_7aiohttp_10_multidict__Base __pyx_base; -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDictProxy *__pyx_vtabptr_7aiohttp_10_multidict_MultiDictProxy; - - -/* "aiohttp/_multidict.pyx":213 - * - * - * cdef class CIMultiDictProxy(MultiDictProxy): # <<<<<<<<<<<<<< - * - * def __init__(self, arg): - */ - -struct __pyx_vtabstruct_7aiohttp_10_multidict_CIMultiDictProxy { - struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDictProxy __pyx_base; -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict_CIMultiDictProxy *__pyx_vtabptr_7aiohttp_10_multidict_CIMultiDictProxy; - - -/* "aiohttp/_multidict.pyx":238 - * - * - * cdef class MultiDict(_Base): # <<<<<<<<<<<<<< - * """An ordered dictionary that can have multiple values for each key.""" - * - */ - -struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict { - struct __pyx_vtabstruct_7aiohttp_10_multidict__Base __pyx_base; - PyObject *(*_extend)(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *, PyObject *, PyObject *, PyObject *, int); - PyObject *(*_add)(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *, PyObject *, PyObject *); - PyObject *(*_replace)(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *, PyObject *, PyObject *); - PyObject *(*_remove)(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *, PyObject *, int); -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *__pyx_vtabptr_7aiohttp_10_multidict_MultiDict; - - -/* "aiohttp/_multidict.pyx":408 - * - * - * cdef class CIMultiDict(MultiDict): # <<<<<<<<<<<<<< - * """An ordered dictionary that can have multiple values for each key.""" - * - */ - -struct __pyx_vtabstruct_7aiohttp_10_multidict_CIMultiDict { - struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict __pyx_base; -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict_CIMultiDict *__pyx_vtabptr_7aiohttp_10_multidict_CIMultiDict; - -/* --- Runtime support code (head) --- */ -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - if (acquire_gil) {\ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - PyGILState_Release(__pyx_gilstate_save);\ - } else {\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext()\ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif -#define __Pyx_XDECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_XDECREF(tmp);\ - } while (0) -#define __Pyx_DECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_DECREF(tmp);\ - } while (0) -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -static PyObject *__Pyx_GetBuiltinName(PyObject *name); - -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); - -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); - -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); -#else -#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) -#endif - -static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); - -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, long intval, int inplace); -#else -#define __Pyx_PyInt_EqObjC(op1, op2, intval, inplace)\ - PyObject_RichCompare(op1, op2, Py_EQ) - #endif - -static CYTHON_INLINE int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); - -#include <string.h> - -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); - -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); - -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals -#else -#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals -#endif - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - Py_SIZE(list) = len+1; - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) -#endif - -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); - -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -#if PY_MAJOR_VERSION < 3 -#define __Pyx_PyString_Join __Pyx_PyBytes_Join -#define __Pyx_PyBaseString_Join(s, v) (PyUnicode_CheckExact(s) ? PyUnicode_Join(s, v) : __Pyx_PyBytes_Join(s, v)) -#else -#define __Pyx_PyString_Join PyUnicode_Join -#define __Pyx_PyBaseString_Join PyUnicode_Join -#endif -#if CYTHON_COMPILING_IN_CPYTHON - #if PY_MAJOR_VERSION < 3 - #define __Pyx_PyBytes_Join _PyString_Join - #else - #define __Pyx_PyBytes_Join _PyBytes_Join - #endif -#else -static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values); -#endif - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); - -#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ - __Pyx_GetItemInt_Generic(o, to_py_func(i)))) -#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); - -static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); - -typedef struct { - PyObject *type; - PyObject **method_name; - PyCFunction func; - PyObject *method; - int flag; -} __Pyx_CachedCFunction; - -static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_CallUnboundCMethod0(cfunc, self)\ - ((likely((cfunc)->func)) ?\ - (likely((cfunc)->flag == METH_NOARGS) ? (*((cfunc)->func))(self, NULL) :\ - (likely((cfunc)->flag == (METH_VARARGS | METH_KEYWORDS)) ? ((*(PyCFunctionWithKeywords)(cfunc)->func)(self, __pyx_empty_tuple, NULL)) :\ - ((cfunc)->flag == METH_VARARGS ? (*((cfunc)->func))(self, __pyx_empty_tuple) : __Pyx__CallUnboundCMethod0(cfunc, self)))) :\ - __Pyx__CallUnboundCMethod0(cfunc, self)) -#else -#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) -#endif - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -static CYTHON_INLINE int __Pyx_IterFinish(void); - -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); - -#define __Pyx_DelItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_DelItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound) :\ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) :\ - __Pyx_DelItem_Generic(o, to_py_func(i)))) -static CYTHON_INLINE int __Pyx_DelItem_Generic(PyObject *o, PyObject *j); -static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound); - -static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); - -static PyObject* __Pyx__PyObject_PopNewIndex(PyObject* L, PyObject* py_ix); -static PyObject* __Pyx__PyObject_PopIndex(PyObject* L, PyObject* py_ix); -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyList_PopIndex(PyObject* L, PyObject* py_ix, Py_ssize_t ix); -#define __Pyx_PyObject_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) (\ - (likely(PyList_CheckExact(L) && __Pyx_fits_Py_ssize_t(ix, type, is_signed))) ?\ - __Pyx__PyList_PopIndex(L, py_ix, ix) : (\ - (unlikely(py_ix == Py_None)) ? __Pyx__PyObject_PopNewIndex(L, to_py_func(ix)) :\ - __Pyx__PyObject_PopIndex(L, py_ix))) -#define __Pyx_PyList_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) (\ - __Pyx_fits_Py_ssize_t(ix, type, is_signed) ?\ - __Pyx__PyList_PopIndex(L, py_ix, ix) : (\ - (unlikely(py_ix == Py_None)) ? __Pyx__PyObject_PopNewIndex(L, to_py_func(ix)) :\ - __Pyx__PyObject_PopIndex(L, py_ix))) -#else -#define __Pyx_PyList_PopIndex(L, py_ix, ix, is_signed, type, to_py_func)\ - __Pyx_PyObject_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) -#define __Pyx_PyObject_PopIndex(L, py_ix, ix, is_signed, type, to_py_func) (\ - (unlikely(py_ix == Py_None)) ? __Pyx__PyObject_PopNewIndex(L, to_py_func(ix)) :\ - __Pyx__PyObject_PopIndex(L, py_ix)) -#endif - -static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); - -static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { - int result = PySequence_Contains(seq, item); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - -static int __Pyx_SetVtable(PyObject *dict, void *vtable); - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases); - -static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); - -#define __Pyx_CyFunction_USED 1 -#include <structmember.h> -#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 -#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 -#define __Pyx_CYFUNCTION_CCLASS 0x04 -#define __Pyx_CyFunction_GetClosure(f)\ - (((__pyx_CyFunctionObject *) (f))->func_closure) -#define __Pyx_CyFunction_GetClassObj(f)\ - (((__pyx_CyFunctionObject *) (f))->func_classobj) -#define __Pyx_CyFunction_Defaults(type, f)\ - ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) -#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ - ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) -typedef struct { - PyCFunctionObject func; -#if PY_VERSION_HEX < 0x030500A0 - PyObject *func_weakreflist; -#endif - PyObject *func_dict; - PyObject *func_name; - PyObject *func_qualname; - PyObject *func_doc; - PyObject *func_globals; - PyObject *func_code; - PyObject *func_closure; - PyObject *func_classobj; - void *defaults; - int defaults_pyobjects; - int flags; - PyObject *defaults_tuple; - PyObject *defaults_kwdict; - PyObject *(*defaults_getter)(PyObject *); - PyObject *func_annotations; -} __pyx_CyFunctionObject; -static PyTypeObject *__pyx_CyFunctionType = 0; -#define __Pyx_CyFunction_NewEx(ml, flags, qualname, self, module, globals, code)\ - __Pyx_CyFunction_New(__pyx_CyFunctionType, ml, flags, qualname, self, module, globals, code) -static PyObject *__Pyx_CyFunction_New(PyTypeObject *, PyMethodDef *ml, - int flags, PyObject* qualname, - PyObject *self, - PyObject *module, PyObject *globals, - PyObject* code); -static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, - size_t size, - int pyobjects); -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, - PyObject *tuple); -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, - PyObject *dict); -static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, - PyObject *dict); -static int __pyx_CyFunction_init(void); - -static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *qualname, - PyObject *mkw, PyObject *modname, PyObject *doc); -static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, - PyObject *mkw, int calculate_metaclass, int allow_py2_metaclass); - -typedef struct { - int code_line; - PyCodeObject* code_object; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); - -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); - -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -static int __Pyx_check_binary_version(void); - -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__upper(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_s); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__getall(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__getone(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__contains(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base_keys(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, int __pyx_skip_dispatch); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__eq_to_mapping(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_other); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_16CIMultiDictProxy__upper(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *__pyx_v_self, PyObject *__pyx_v_s); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_9MultiDict__extend(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, PyObject *__pyx_v_name, int __pyx_v_do_add); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_9MultiDict__add(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_9MultiDict__replace(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_9MultiDict__remove(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, int __pyx_v_raise_key_error); /* proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_11CIMultiDict__upper(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDict *__pyx_v_self, PyObject *__pyx_v_s); /* proto*/ - -/* Module declarations from 'aiohttp._multidict' */ -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__Pair = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__Base = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict_MultiDictProxy = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict_CIMultiDictProxy = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict_MultiDict = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict_CIMultiDict = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__ViewBase = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__ViewBaseSet = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__ItemsIter = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__ItemsView = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__ValuesIter = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__ValuesView = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__KeysIter = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_10_multidict__KeysView = 0; -static PyObject *__pyx_f_7aiohttp_10_multidict__eq(PyObject *, PyObject *); /*proto*/ -#define __Pyx_MODULE_NAME "aiohttp._multidict" -int __pyx_module_is_main_aiohttp___multidict = 0; - -/* Implementation of 'aiohttp._multidict' */ -static PyObject *__pyx_builtin_object; -static PyObject *__pyx_builtin_memoryview; -static PyObject *__pyx_builtin_NotImplemented; -static PyObject *__pyx_builtin_KeyError; -static PyObject *__pyx_builtin_TypeError; -static PyObject *__pyx_builtin_range; -static PyObject *__pyx_builtin_StopIteration; -static char __pyx_k_[] = ""; -static char __pyx_k_r[] = "'{}': {!r}"; -static char __pyx_k__4[] = ", "; -static char __pyx_k__5[] = "<{}({})>"; -static char __pyx_k__8[] = "{}({})"; -static char __pyx_k_Set[] = "Set"; -static char __pyx_k_abc[] = "abc"; -static char __pyx_k_arg[] = "arg"; -static char __pyx_k_cls[] = "cls"; -static char __pyx_k_doc[] = "__doc__"; -static char __pyx_k_get[] = "get"; -static char __pyx_k_key[] = "key"; -static char __pyx_k_new[] = "__new__"; -static char __pyx_k_pop[] = "pop"; -static char __pyx_k_r_2[] = "{!r}"; -static char __pyx_k_r_r[] = "{!r}: {!r}"; -static char __pyx_k_sys[] = "sys"; -static char __pyx_k_val[] = "val"; -static char __pyx_k_join[] = "join"; -static char __pyx_k_keys[] = "keys"; -static char __pyx_k_main[] = "__main__"; -static char __pyx_k_name[] = "__name__"; -static char __pyx_k_self[] = "self"; -static char __pyx_k_test[] = "__test__"; -static char __pyx_k_class[] = "__class__"; -static char __pyx_k_clear[] = "clear"; -static char __pyx_k_items[] = "items"; -static char __pyx_k_range[] = "range"; -static char __pyx_k_upper[] = "upper"; -static char __pyx_k_upstr[] = "upstr"; -static char __pyx_k_value[] = "value"; -static char __pyx_k_errors[] = "errors"; -static char __pyx_k_extend[] = "extend"; -static char __pyx_k_format[] = "format"; -static char __pyx_k_import[] = "__import__"; -static char __pyx_k_marker[] = "_marker"; -static char __pyx_k_module[] = "__module__"; -static char __pyx_k_object[] = "object"; -static char __pyx_k_strict[] = "strict"; -static char __pyx_k_update[] = "update"; -static char __pyx_k_Mapping[] = "Mapping"; -static char __pyx_k_default[] = "default"; -static char __pyx_k_prepare[] = "__prepare__"; -static char __pyx_k_Iterable[] = "Iterable"; -static char __pyx_k_KeyError[] = "KeyError"; -static char __pyx_k_KeysView[] = "KeysView"; -static char __pyx_k_encoding[] = "encoding"; -static char __pyx_k_operator[] = "operator"; -static char __pyx_k_qualname[] = "__qualname__"; -static char __pyx_k_register[] = "register"; -static char __pyx_k_ItemsView[] = "ItemsView"; -static char __pyx_k_TypeError[] = "TypeError"; -static char __pyx_k_metaclass[] = "__metaclass__"; -static char __pyx_k_ValuesView[] = "ValuesView"; -static char __pyx_k_itemgetter[] = "itemgetter"; -static char __pyx_k_memoryview[] = "memoryview"; -static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; -static char __pyx_k_collections[] = "collections"; -static char __pyx_k_upstr___new[] = "upstr.__new__"; -static char __pyx_k_upstr_upper[] = "upstr.upper"; -static char __pyx_k_StopIteration[] = "StopIteration"; -static char __pyx_k_MutableMapping[] = "MutableMapping"; -static char __pyx_k_NotImplemented[] = "NotImplemented"; -static char __pyx_k_Key_not_found_r[] = "Key not found: %r"; -static char __pyx_k_collections_abc[] = "collections.abc"; -static char __pyx_k_empty_multidict[] = "empty multidict"; -static char __pyx_k_aiohttp__multidict[] = "aiohttp._multidict"; -static char __pyx_k_getdefaultencoding[] = "getdefaultencoding"; -static char __pyx_k_Case_insensitive_str[] = "Case insensitive str."; -static char __pyx_k_home_andrew_projects_aiohttp_ai[] = "/home/andrew/projects/aiohttp/aiohttp/_multidict.pyx"; -static char __pyx_k_takes_at_most_1_positional_argu[] = "{} takes at most 1 positional argument ({} given)"; -static char __pyx_k_takes_either_dict_or_list_of_ke[] = "{} takes either dict or list of (key, value) tuples"; -static char __pyx_k_CIMultiDictProxy_requires_CIMult[] = "CIMultiDictProxy requires CIMultiDict instance, not {}"; -static char __pyx_k_MultiDictProxy_requires_MultiDic[] = "MultiDictProxy requires MultiDict instance, not {}"; -static PyObject *__pyx_kp_s_; -static PyObject *__pyx_kp_s_CIMultiDictProxy_requires_CIMult; -static PyObject *__pyx_kp_s_Case_insensitive_str; -static PyObject *__pyx_n_s_ItemsView; -static PyObject *__pyx_n_s_Iterable; -static PyObject *__pyx_n_s_KeyError; -static PyObject *__pyx_kp_s_Key_not_found_r; -static PyObject *__pyx_n_s_KeysView; -static PyObject *__pyx_n_s_Mapping; -static PyObject *__pyx_kp_s_MultiDictProxy_requires_MultiDic; -static PyObject *__pyx_n_s_MutableMapping; -static PyObject *__pyx_n_s_NotImplemented; -static PyObject *__pyx_n_s_Set; -static PyObject *__pyx_n_s_StopIteration; -static PyObject *__pyx_n_s_TypeError; -static PyObject *__pyx_n_s_ValuesView; -static PyObject *__pyx_kp_s__4; -static PyObject *__pyx_kp_s__5; -static PyObject *__pyx_kp_s__8; -static PyObject *__pyx_n_s_abc; -static PyObject *__pyx_n_s_aiohttp__multidict; -static PyObject *__pyx_n_s_arg; -static PyObject *__pyx_n_s_class; -static PyObject *__pyx_n_s_clear; -static PyObject *__pyx_n_s_cls; -static PyObject *__pyx_n_s_collections; -static PyObject *__pyx_n_s_collections_abc; -static PyObject *__pyx_n_s_default; -static PyObject *__pyx_n_s_doc; -static PyObject *__pyx_kp_s_empty_multidict; -static PyObject *__pyx_n_s_encoding; -static PyObject *__pyx_n_s_errors; -static PyObject *__pyx_n_s_extend; -static PyObject *__pyx_n_s_format; -static PyObject *__pyx_n_s_get; -static PyObject *__pyx_n_s_getdefaultencoding; -static PyObject *__pyx_kp_s_home_andrew_projects_aiohttp_ai; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_s_itemgetter; -static PyObject *__pyx_n_s_items; -static PyObject *__pyx_n_s_join; -static PyObject *__pyx_n_s_key; -static PyObject *__pyx_n_s_keys; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_marker; -static PyObject *__pyx_n_s_memoryview; -static PyObject *__pyx_n_s_metaclass; -static PyObject *__pyx_n_s_module; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_n_s_new; -static PyObject *__pyx_n_s_object; -static PyObject *__pyx_n_s_operator; -static PyObject *__pyx_n_s_pop; -static PyObject *__pyx_n_s_prepare; -static PyObject *__pyx_n_s_pyx_vtable; -static PyObject *__pyx_n_s_qualname; -static PyObject *__pyx_kp_s_r; -static PyObject *__pyx_kp_s_r_2; -static PyObject *__pyx_kp_s_r_r; -static PyObject *__pyx_n_s_range; -static PyObject *__pyx_n_s_register; -static PyObject *__pyx_n_s_self; -static PyObject *__pyx_n_s_strict; -static PyObject *__pyx_n_s_sys; -static PyObject *__pyx_kp_s_takes_at_most_1_positional_argu; -static PyObject *__pyx_kp_s_takes_either_dict_or_list_of_ke; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_n_s_update; -static PyObject *__pyx_n_s_upper; -static PyObject *__pyx_n_s_upstr; -static PyObject *__pyx_n_s_upstr___new; -static PyObject *__pyx_n_s_upstr_upper; -static PyObject *__pyx_n_s_val; -static PyObject *__pyx_n_s_value; -static PyObject *__pyx_pf_7aiohttp_10_multidict_5upstr_4__defaults__(CYTHON_UNUSED PyObject *__pyx_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5upstr___new__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_cls, PyObject *__pyx_v_val, PyObject *__pyx_v_encoding, PyObject *__pyx_v_errors); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5upstr_2upper(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_5_Pair___cinit__(struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Pair_2__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, PyObject *__pyx_v_op); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_5_Base___cinit__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_2getall(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_4getone(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_6__getitem__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_8get(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_5_Base_10__contains__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_12__iter__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self); /* proto */ -static Py_ssize_t __pyx_pf_7aiohttp_10_multidict_5_Base_14__len__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_16keys(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_18items(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_20values(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_22__repr__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_24__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, PyObject *__pyx_v_op); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_14MultiDictProxy___init__(struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy *__pyx_v_self, PyObject *__pyx_v_arg); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_14MultiDictProxy_2copy(struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy *__pyx_v_self); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_16CIMultiDictProxy___init__(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *__pyx_v_self, PyObject *__pyx_v_arg); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_16CIMultiDictProxy_2copy(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *__pyx_v_self); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_9MultiDict___init__(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_2add(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_4copy(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_6extend(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_8clear(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_9MultiDict_10__setitem__(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_9MultiDict_12__delitem__(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_14setdefault(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_16pop(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_18popitem(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_20update(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_9_ViewBase___cinit__(struct __pyx_obj_7aiohttp_10_multidict__ViewBase *__pyx_v_self, PyObject *__pyx_v_items); /* proto */ -static Py_ssize_t __pyx_pf_7aiohttp_10_multidict_9_ViewBase_2__len__(struct __pyx_obj_7aiohttp_10_multidict__ViewBase *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet___richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, PyObject *__pyx_v_op); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_2__and__(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_4__or__(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_6__sub__(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_8__xor__(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_10_ItemsIter___cinit__(struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *__pyx_v_self, PyObject *__pyx_v_items); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsIter_2__iter__(struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsIter_4__next__(struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsView_isdisjoint(struct __pyx_obj_7aiohttp_10_multidict__ItemsView *__pyx_v_self, PyObject *__pyx_v_other); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_10_ItemsView_2__contains__(struct __pyx_obj_7aiohttp_10_multidict__ItemsView *__pyx_v_self, PyObject *__pyx_v_i); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsView_4__iter__(struct __pyx_obj_7aiohttp_10_multidict__ItemsView *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsView_6__repr__(struct __pyx_obj_7aiohttp_10_multidict__ItemsView *__pyx_v_self); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_11_ValuesIter___cinit__(struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *__pyx_v_self, PyObject *__pyx_v_items); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_11_ValuesIter_2__iter__(struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_11_ValuesIter_4__next__(struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *__pyx_v_self); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_11_ValuesView___contains__(struct __pyx_obj_7aiohttp_10_multidict__ValuesView *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_11_ValuesView_2__iter__(struct __pyx_obj_7aiohttp_10_multidict__ValuesView *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_11_ValuesView_4__repr__(struct __pyx_obj_7aiohttp_10_multidict__ValuesView *__pyx_v_self); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_9_KeysIter___cinit__(struct __pyx_obj_7aiohttp_10_multidict__KeysIter *__pyx_v_self, PyObject *__pyx_v_items); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysIter_2__iter__(struct __pyx_obj_7aiohttp_10_multidict__KeysIter *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysIter_4__next__(struct __pyx_obj_7aiohttp_10_multidict__KeysIter *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysView_isdisjoint(struct __pyx_obj_7aiohttp_10_multidict__KeysView *__pyx_v_self, PyObject *__pyx_v_other); /* proto */ -static int __pyx_pf_7aiohttp_10_multidict_9_KeysView_2__contains__(struct __pyx_obj_7aiohttp_10_multidict__KeysView *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysView_4__iter__(struct __pyx_obj_7aiohttp_10_multidict__KeysView *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysView_6__repr__(struct __pyx_obj_7aiohttp_10_multidict__KeysView *__pyx_v_self); /* proto */ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__Pair(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__Base(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict_MultiDictProxy(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict_CIMultiDictProxy(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict_MultiDict(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict_CIMultiDict(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ViewBase(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ViewBaseSet(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ItemsIter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ItemsView(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ValuesIter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ValuesView(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__KeysIter(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__KeysView(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items = {0, &__pyx_n_s_items, 0, 0, 0}; -static PyObject *__pyx_int_0; -static PyObject *__pyx_int_1; -static PyObject *__pyx_int_2; -static PyObject *__pyx_int_3; -static PyObject *__pyx_int_4; -static PyObject *__pyx_int_5; -static PyObject *__pyx_k__2; -static PyObject *__pyx_k__3; -static PyObject *__pyx_k__6; -static PyObject *__pyx_tuple__7; -static PyObject *__pyx_tuple__9; -static PyObject *__pyx_tuple__11; -static PyObject *__pyx_codeobj__10; -static PyObject *__pyx_codeobj__12; - -/* "aiohttp/_multidict.pyx":14 - * """Case insensitive str.""" - * - * def __new__(cls, val='', # <<<<<<<<<<<<<< - * encoding=sys.getdefaultencoding(), errors='strict'): - * if isinstance(val, (bytes, bytearray, memoryview)): - */ - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5upstr_4__defaults__(CYTHON_UNUSED PyObject *__pyx_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__defaults__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject*)__pyx_kp_s_)); - __Pyx_GIVEREF(((PyObject*)__pyx_kp_s_)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject*)__pyx_kp_s_)); - __Pyx_INCREF(__Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_self)->__pyx_arg_encoding); - __Pyx_GIVEREF(__Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_self)->__pyx_arg_encoding); - PyTuple_SET_ITEM(__pyx_t_1, 1, __Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_self)->__pyx_arg_encoding); - __Pyx_INCREF(((PyObject*)__pyx_n_s_strict)); - __Pyx_GIVEREF(((PyObject*)__pyx_n_s_strict)); - PyTuple_SET_ITEM(__pyx_t_1, 2, ((PyObject*)__pyx_n_s_strict)); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_2, 1, Py_None); - __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict.upstr.__defaults__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5upstr_1__new__(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7aiohttp_10_multidict_5upstr_1__new__ = {"__new__", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_5upstr_1__new__, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_7aiohttp_10_multidict_5upstr_1__new__(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_cls = 0; - PyObject *__pyx_v_val = 0; - PyObject *__pyx_v_encoding = 0; - PyObject *__pyx_v_errors = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__new__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_cls,&__pyx_n_s_val,&__pyx_n_s_encoding,&__pyx_n_s_errors,0}; - PyObject* values[4] = {0,0,0,0}; - __pyx_defaults *__pyx_dynamic_args = __Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_self); - values[1] = ((PyObject *)((PyObject*)__pyx_kp_s_)); - values[2] = __pyx_dynamic_args->__pyx_arg_encoding; - values[3] = ((PyObject *)((PyObject*)__pyx_n_s_strict)); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_cls)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_val); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_encoding); - if (value) { values[2] = value; kw_args--; } - } - case 3: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_errors); - if (value) { values[3] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__new__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_cls = values[0]; - __pyx_v_val = values[1]; - __pyx_v_encoding = values[2]; - __pyx_v_errors = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__new__", 0, 1, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict.upstr.__new__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5upstr___new__(__pyx_self, __pyx_v_cls, __pyx_v_val, __pyx_v_encoding, __pyx_v_errors); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5upstr___new__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_cls, PyObject *__pyx_v_val, PyObject *__pyx_v_encoding, PyObject *__pyx_v_errors) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - Py_ssize_t __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__new__", 0); - __Pyx_INCREF(__pyx_v_val); - - /* "aiohttp/_multidict.pyx":16 - * def __new__(cls, val='', - * encoding=sys.getdefaultencoding(), errors='strict'): - * if isinstance(val, (bytes, bytearray, memoryview)): # <<<<<<<<<<<<<< - * val = str(val, encoding, errors) - * elif isinstance(val, str): - */ - __Pyx_INCREF(__pyx_builtin_memoryview); - __pyx_t_1 = __pyx_builtin_memoryview; - __pyx_t_3 = PyBytes_Check(__pyx_v_val); - __pyx_t_4 = (__pyx_t_3 != 0); - if (!__pyx_t_4) { - } else { - __pyx_t_2 = __pyx_t_4; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_4 = PyByteArray_Check(__pyx_v_val); - __pyx_t_3 = (__pyx_t_4 != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_3 = PyObject_IsInstance(__pyx_v_val, __pyx_t_1); - __pyx_t_4 = (__pyx_t_3 != 0); - __pyx_t_2 = __pyx_t_4; - __pyx_L4_bool_binop_done:; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_4 = (__pyx_t_2 != 0); - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":17 - * encoding=sys.getdefaultencoding(), errors='strict'): - * if isinstance(val, (bytes, bytearray, memoryview)): - * val = str(val, encoding, errors) # <<<<<<<<<<<<<< - * elif isinstance(val, str): - * pass - */ - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_val); - __Pyx_GIVEREF(__pyx_v_val); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_val); - __Pyx_INCREF(__pyx_v_encoding); - __Pyx_GIVEREF(__pyx_v_encoding); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_encoding); - __Pyx_INCREF(__pyx_v_errors); - __Pyx_GIVEREF(__pyx_v_errors); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_errors); - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)(&PyString_Type)), __pyx_t_1, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF_SET(__pyx_v_val, __pyx_t_5); - __pyx_t_5 = 0; - - /* "aiohttp/_multidict.pyx":16 - * def __new__(cls, val='', - * encoding=sys.getdefaultencoding(), errors='strict'): - * if isinstance(val, (bytes, bytearray, memoryview)): # <<<<<<<<<<<<<< - * val = str(val, encoding, errors) - * elif isinstance(val, str): - */ - goto __pyx_L3; - } - - /* "aiohttp/_multidict.pyx":18 - * if isinstance(val, (bytes, bytearray, memoryview)): - * val = str(val, encoding, errors) - * elif isinstance(val, str): # <<<<<<<<<<<<<< - * pass - * else: - */ - __pyx_t_4 = PyString_Check(__pyx_v_val); - __pyx_t_2 = (__pyx_t_4 != 0); - if (__pyx_t_2) { - goto __pyx_L3; - } - - /* "aiohttp/_multidict.pyx":21 - * pass - * else: - * val = str(val) # <<<<<<<<<<<<<< - * val = val.upper() - * return str.__new__(cls, val) - */ - /*else*/ { - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_val); - __Pyx_GIVEREF(__pyx_v_val); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_val); - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)(&PyString_Type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF_SET(__pyx_v_val, __pyx_t_1); - __pyx_t_1 = 0; - } - __pyx_L3:; - - /* "aiohttp/_multidict.pyx":22 - * else: - * val = str(val) - * val = val.upper() # <<<<<<<<<<<<<< - * return str.__new__(cls, val) - * - */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_val, __pyx_n_s_upper); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_5))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_5, function); - } - } - if (__pyx_t_6) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_5); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF_SET(__pyx_v_val, __pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":23 - * val = str(val) - * val = val.upper() - * return str.__new__(cls, val) # <<<<<<<<<<<<<< - * - * def upper(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(((PyObject *)(&PyString_Type)), __pyx_n_s_new); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - __pyx_t_7 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_5))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_5, function); - __pyx_t_7 = 1; - } - } - __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_6) { - __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_6); __pyx_t_6 = NULL; - } - __Pyx_INCREF(__pyx_v_cls); - __Pyx_GIVEREF(__pyx_v_cls); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_v_cls); - __Pyx_INCREF(__pyx_v_val); - __Pyx_GIVEREF(__pyx_v_val); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_val); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_8, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":14 - * """Case insensitive str.""" - * - * def __new__(cls, val='', # <<<<<<<<<<<<<< - * encoding=sys.getdefaultencoding(), errors='strict'): - * if isinstance(val, (bytes, bytearray, memoryview)): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("aiohttp._multidict.upstr.__new__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_val); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":25 - * return str.__new__(cls, val) - * - * def upper(self): # <<<<<<<<<<<<<< - * return self - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5upstr_3upper(PyObject *__pyx_self, PyObject *__pyx_v_self); /*proto*/ -static PyMethodDef __pyx_mdef_7aiohttp_10_multidict_5upstr_3upper = {"upper", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_5upstr_3upper, METH_O, 0}; -static PyObject *__pyx_pw_7aiohttp_10_multidict_5upstr_3upper(PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("upper (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5upstr_2upper(__pyx_self, ((PyObject *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5upstr_2upper(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("upper", 0); - - /* "aiohttp/_multidict.pyx":26 - * - * def upper(self): - * return self # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self); - __pyx_r = __pyx_v_self; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":25 - * return str.__new__(cls, val) - * - * def upper(self): # <<<<<<<<<<<<<< - * return self - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":29 - * - * - * cdef _eq(self, other): # <<<<<<<<<<<<<< - * cdef _Base typed_self - * cdef _Base typed_other - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict__eq(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - int __pyx_v_is_left_base; - int __pyx_v_is_right_base; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_eq", 0); - - /* "aiohttp/_multidict.pyx":34 - * cdef int is_left_base, is_right_base - * - * is_left_base = isinstance(self, _Base) # <<<<<<<<<<<<<< - * is_right_base = isinstance(other, _Base) - * - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_self, __pyx_ptype_7aiohttp_10_multidict__Base); - __pyx_v_is_left_base = __pyx_t_1; - - /* "aiohttp/_multidict.pyx":35 - * - * is_left_base = isinstance(self, _Base) - * is_right_base = isinstance(other, _Base) # <<<<<<<<<<<<<< - * - * if is_left_base and is_right_base: - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_other, __pyx_ptype_7aiohttp_10_multidict__Base); - __pyx_v_is_right_base = __pyx_t_1; - - /* "aiohttp/_multidict.pyx":37 - * is_right_base = isinstance(other, _Base) - * - * if is_left_base and is_right_base: # <<<<<<<<<<<<<< - * return (<_Base>self)._items == (<_Base>other)._items - * elif is_left_base and isinstance(other, abc.Mapping): - */ - __pyx_t_2 = (__pyx_v_is_left_base != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_2 = (__pyx_v_is_right_base != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":38 - * - * if is_left_base and is_right_base: - * return (<_Base>self)._items == (<_Base>other)._items # <<<<<<<<<<<<<< - * elif is_left_base and isinstance(other, abc.Mapping): - * return (<_Base>self)._eq_to_mapping(other) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyObject_RichCompare(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self)->_items, ((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_other)->_items, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":37 - * is_right_base = isinstance(other, _Base) - * - * if is_left_base and is_right_base: # <<<<<<<<<<<<<< - * return (<_Base>self)._items == (<_Base>other)._items - * elif is_left_base and isinstance(other, abc.Mapping): - */ - } - - /* "aiohttp/_multidict.pyx":39 - * if is_left_base and is_right_base: - * return (<_Base>self)._items == (<_Base>other)._items - * elif is_left_base and isinstance(other, abc.Mapping): # <<<<<<<<<<<<<< - * return (<_Base>self)._eq_to_mapping(other) - * elif is_right_base and isinstance(self, abc.Mapping): - */ - __pyx_t_2 = (__pyx_v_is_left_base != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_abc); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_Mapping); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_2 = PyObject_IsInstance(__pyx_v_other, __pyx_t_4); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 39; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = (__pyx_t_2 != 0); - __pyx_t_1 = __pyx_t_5; - __pyx_L6_bool_binop_done:; - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":40 - * return (<_Base>self)._items == (<_Base>other)._items - * elif is_left_base and isinstance(other, abc.Mapping): - * return (<_Base>self)._eq_to_mapping(other) # <<<<<<<<<<<<<< - * elif is_right_base and isinstance(self, abc.Mapping): - * return (<_Base>other)._eq_to_mapping(self) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self)->__pyx_vtab)->_eq_to_mapping(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_other); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 40; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":39 - * if is_left_base and is_right_base: - * return (<_Base>self)._items == (<_Base>other)._items - * elif is_left_base and isinstance(other, abc.Mapping): # <<<<<<<<<<<<<< - * return (<_Base>self)._eq_to_mapping(other) - * elif is_right_base and isinstance(self, abc.Mapping): - */ - } - - /* "aiohttp/_multidict.pyx":41 - * elif is_left_base and isinstance(other, abc.Mapping): - * return (<_Base>self)._eq_to_mapping(other) - * elif is_right_base and isinstance(self, abc.Mapping): # <<<<<<<<<<<<<< - * return (<_Base>other)._eq_to_mapping(self) - * else: - */ - __pyx_t_5 = (__pyx_v_is_right_base != 0); - if (__pyx_t_5) { - } else { - __pyx_t_1 = __pyx_t_5; - goto __pyx_L8_bool_binop_done; - } - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_abc); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_Mapping); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = PyObject_IsInstance(__pyx_v_self, __pyx_t_3); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 41; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_2 = (__pyx_t_5 != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L8_bool_binop_done:; - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":42 - * return (<_Base>self)._eq_to_mapping(other) - * elif is_right_base and isinstance(self, abc.Mapping): - * return (<_Base>other)._eq_to_mapping(self) # <<<<<<<<<<<<<< - * else: - * return NotImplemented - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_other)->__pyx_vtab)->_eq_to_mapping(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_other), __pyx_v_self); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":41 - * elif is_left_base and isinstance(other, abc.Mapping): - * return (<_Base>self)._eq_to_mapping(other) - * elif is_right_base and isinstance(self, abc.Mapping): # <<<<<<<<<<<<<< - * return (<_Base>other)._eq_to_mapping(self) - * else: - */ - } - - /* "aiohttp/_multidict.pyx":44 - * return (<_Base>other)._eq_to_mapping(self) - * else: - * return NotImplemented # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - } - - /* "aiohttp/_multidict.pyx":29 - * - * - * cdef _eq(self, other): # <<<<<<<<<<<<<< - * cdef _Base typed_self - * cdef _Base typed_other - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._multidict._eq", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":51 - * cdef object _value - * - * def __cinit__(self, key, value): # <<<<<<<<<<<<<< - * self._key = key - * self._value = value - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_5_Pair_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_5_Pair_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_key = 0; - PyObject *__pyx_v_value = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_key,&__pyx_n_s_value,0}; - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_key)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_value)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_key = values[0]; - __pyx_v_value = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._Pair.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Pair___cinit__(((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_v_self), __pyx_v_key, __pyx_v_value); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_5_Pair___cinit__(struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "aiohttp/_multidict.pyx":52 - * - * def __cinit__(self, key, value): - * self._key = key # <<<<<<<<<<<<<< - * self._value = value - * - */ - __Pyx_INCREF(__pyx_v_key); - __Pyx_GIVEREF(__pyx_v_key); - __Pyx_GOTREF(__pyx_v_self->_key); - __Pyx_DECREF(__pyx_v_self->_key); - __pyx_v_self->_key = __pyx_v_key; - - /* "aiohttp/_multidict.pyx":53 - * def __cinit__(self, key, value): - * self._key = key - * self._value = value # <<<<<<<<<<<<<< - * - * def __richcmp__(self, other, op): - */ - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - __Pyx_GOTREF(__pyx_v_self->_value); - __Pyx_DECREF(__pyx_v_self->_value); - __pyx_v_self->_value = __pyx_v_value; - - /* "aiohttp/_multidict.pyx":51 - * cdef object _value - * - * def __cinit__(self, key, value): # <<<<<<<<<<<<<< - * self._key = key - * self._value = value - */ - - /* function exit code */ - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":55 - * self._value = value - * - * def __richcmp__(self, other, op): # <<<<<<<<<<<<<< - * cdef _Pair left, right - * if not isinstance(self, _Pair) or not isinstance(other, _Pair): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Pair_3__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, int __pyx_arg_op); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Pair_3__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, int __pyx_arg_op) { - PyObject *__pyx_v_op = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__richcmp__ (wrapper)", 0); - __pyx_v_op = __Pyx_PyInt_From_int(__pyx_arg_op); if (unlikely(!__pyx_v_op)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __Pyx_GOTREF(__pyx_v_op); - goto __pyx_L4_argument_unpacking_done; - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._Pair.__richcmp__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Pair_2__richcmp__(((PyObject *)__pyx_v_self), ((PyObject *)__pyx_v_other), ((PyObject *)__pyx_v_op)); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_op); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Pair_2__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, PyObject *__pyx_v_op) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_left = 0; - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_right = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__richcmp__", 0); - - /* "aiohttp/_multidict.pyx":57 - * def __richcmp__(self, other, op): - * cdef _Pair left, right - * if not isinstance(self, _Pair) or not isinstance(other, _Pair): # <<<<<<<<<<<<<< - * return NotImplemented - * left = <_Pair>self - */ - __pyx_t_2 = __Pyx_TypeCheck(__pyx_v_self, __pyx_ptype_7aiohttp_10_multidict__Pair); - __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_1 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_3 = __Pyx_TypeCheck(__pyx_v_other, __pyx_ptype_7aiohttp_10_multidict__Pair); - __pyx_t_2 = ((!(__pyx_t_3 != 0)) != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":58 - * cdef _Pair left, right - * if not isinstance(self, _Pair) or not isinstance(other, _Pair): - * return NotImplemented # <<<<<<<<<<<<<< - * left = <_Pair>self - * right = <_Pair>other - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":57 - * def __richcmp__(self, other, op): - * cdef _Pair left, right - * if not isinstance(self, _Pair) or not isinstance(other, _Pair): # <<<<<<<<<<<<<< - * return NotImplemented - * left = <_Pair>self - */ - } - - /* "aiohttp/_multidict.pyx":59 - * if not isinstance(self, _Pair) or not isinstance(other, _Pair): - * return NotImplemented - * left = <_Pair>self # <<<<<<<<<<<<<< - * right = <_Pair>other - * if op == 2: # == - */ - __pyx_t_4 = __pyx_v_self; - __Pyx_INCREF(__pyx_t_4); - __pyx_v_left = ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":60 - * return NotImplemented - * left = <_Pair>self - * right = <_Pair>other # <<<<<<<<<<<<<< - * if op == 2: # == - * return left._key == right._key and left._value == right._value - */ - __pyx_t_4 = __pyx_v_other; - __Pyx_INCREF(__pyx_t_4); - __pyx_v_right = ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":61 - * left = <_Pair>self - * right = <_Pair>other - * if op == 2: # == # <<<<<<<<<<<<<< - * return left._key == right._key and left._value == right._value - * elif op == 3: # != - */ - __pyx_t_4 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_2, 2, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 61; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":62 - * right = <_Pair>other - * if op == 2: # == - * return left._key == right._key and left._value == right._value # <<<<<<<<<<<<<< - * elif op == 3: # != - * return left._key != right._key and left._value != right._value - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_left->_key, __pyx_v_right->_key, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_1) { - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else { - __Pyx_INCREF(__pyx_t_5); - __pyx_t_4 = __pyx_t_5; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L7_bool_binop_done; - } - __pyx_t_5 = PyObject_RichCompare(__pyx_v_left->_value, __pyx_v_right->_value, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_INCREF(__pyx_t_5); - __pyx_t_4 = __pyx_t_5; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_L7_bool_binop_done:; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":61 - * left = <_Pair>self - * right = <_Pair>other - * if op == 2: # == # <<<<<<<<<<<<<< - * return left._key == right._key and left._value == right._value - * elif op == 3: # != - */ - } - - /* "aiohttp/_multidict.pyx":63 - * if op == 2: # == - * return left._key == right._key and left._value == right._value - * elif op == 3: # != # <<<<<<<<<<<<<< - * return left._key != right._key and left._value != right._value - * - */ - __pyx_t_4 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_3, 3, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":64 - * return left._key == right._key and left._value == right._value - * elif op == 3: # != - * return left._key != right._key and left._value != right._value # <<<<<<<<<<<<<< - * - * cdef class _Base: - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = PyObject_RichCompare(__pyx_v_left->_key, __pyx_v_right->_key, Py_NE); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_1) { - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else { - __Pyx_INCREF(__pyx_t_5); - __pyx_t_4 = __pyx_t_5; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_5 = PyObject_RichCompare(__pyx_v_left->_value, __pyx_v_right->_value, Py_NE); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 64; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_INCREF(__pyx_t_5); - __pyx_t_4 = __pyx_t_5; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_L9_bool_binop_done:; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":63 - * if op == 2: # == - * return left._key == right._key and left._value == right._value - * elif op == 3: # != # <<<<<<<<<<<<<< - * return left._key != right._key and left._value != right._value - * - */ - } - - /* "aiohttp/_multidict.pyx":55 - * self._value = value - * - * def __richcmp__(self, other, op): # <<<<<<<<<<<<<< - * cdef _Pair left, right - * if not isinstance(self, _Pair) or not isinstance(other, _Pair): - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("aiohttp._multidict._Pair.__richcmp__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_left); - __Pyx_XDECREF((PyObject *)__pyx_v_right); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":72 - * cdef object marker - * - * def __cinit__(self): # <<<<<<<<<<<<<< - * self._upstr = upstr - * self.marker = _marker - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_5_Base_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_5_Base_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} - if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base___cinit__(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_5_Base___cinit__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "aiohttp/_multidict.pyx":73 - * - * def __cinit__(self): - * self._upstr = upstr # <<<<<<<<<<<<<< - * self.marker = _marker - * - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_upstr); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->_upstr); - __Pyx_DECREF(__pyx_v_self->_upstr); - __pyx_v_self->_upstr = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":74 - * def __cinit__(self): - * self._upstr = upstr - * self.marker = _marker # <<<<<<<<<<<<<< - * - * cdef str _upper(self, s): - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_marker); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->marker); - __Pyx_DECREF(__pyx_v_self->marker); - __pyx_v_self->marker = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":72 - * cdef object marker - * - * def __cinit__(self): # <<<<<<<<<<<<<< - * self._upstr = upstr - * self.marker = _marker - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict._Base.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":76 - * self.marker = _marker - * - * cdef str _upper(self, s): # <<<<<<<<<<<<<< - * if type(s) is self._upstr: - * return <str>s - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__upper(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_s) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_upper", 0); - - /* "aiohttp/_multidict.pyx":77 - * - * cdef str _upper(self, s): - * if type(s) is self._upstr: # <<<<<<<<<<<<<< - * return <str>s - * return s - */ - __pyx_t_1 = (((PyObject *)Py_TYPE(__pyx_v_s)) == __pyx_v_self->_upstr); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":78 - * cdef str _upper(self, s): - * if type(s) is self._upstr: - * return <str>s # <<<<<<<<<<<<<< - * return s - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject*)__pyx_v_s)); - __pyx_r = ((PyObject*)__pyx_v_s); - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":77 - * - * cdef str _upper(self, s): - * if type(s) is self._upstr: # <<<<<<<<<<<<<< - * return <str>s - * return s - */ - } - - /* "aiohttp/_multidict.pyx":79 - * if type(s) is self._upstr: - * return <str>s - * return s # <<<<<<<<<<<<<< - * - * def getall(self, key, default=_marker): - */ - __Pyx_XDECREF(__pyx_r); - if (!(likely(PyString_CheckExact(__pyx_v_s))||((__pyx_v_s) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(__pyx_v_s)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_INCREF(__pyx_v_s); - __pyx_r = ((PyObject*)__pyx_v_s); - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":76 - * self.marker = _marker - * - * cdef str _upper(self, s): # <<<<<<<<<<<<<< - * if type(s) is self._upstr: - * return <str>s - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_AddTraceback("aiohttp._multidict._Base._upper", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":81 - * return s - * - * def getall(self, key, default=_marker): # <<<<<<<<<<<<<< - * """Return a list of all values matching the key.""" - * return self._getall(self._upper(key), default) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_3getall(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_5_Base_2getall[] = "Return a list of all values matching the key."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_3getall(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_key = 0; - PyObject *__pyx_v_default = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("getall (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_key,&__pyx_n_s_default,0}; - PyObject* values[2] = {0,0}; - values[1] = __pyx_k__2; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_key)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_default); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "getall") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_key = values[0]; - __pyx_v_default = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("getall", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._Base.getall", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_2getall(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_key, __pyx_v_default); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_2getall(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("getall", 0); - - /* "aiohttp/_multidict.pyx":83 - * def getall(self, key, default=_marker): - * """Return a list of all values matching the key.""" - * return self._getall(self._upper(key), default) # <<<<<<<<<<<<<< - * - * cdef _getall(self, str key, default): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_upper(__pyx_v_self, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_getall(__pyx_v_self, ((PyObject*)__pyx_t_1), __pyx_v_default); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 83; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":81 - * return s - * - * def getall(self, key, default=_marker): # <<<<<<<<<<<<<< - * """Return a list of all values matching the key.""" - * return self._getall(self._upper(key), default) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._Base.getall", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":85 - * return self._getall(self._upper(key), default) - * - * cdef _getall(self, str key, default): # <<<<<<<<<<<<<< - * cdef list res - * cdef _Pair item - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__getall(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default) { - PyObject *__pyx_v_res = 0; - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_getall", 0); - __Pyx_INCREF(__pyx_v_key); - - /* "aiohttp/_multidict.pyx":88 - * cdef list res - * cdef _Pair item - * key = self._upper(key) # <<<<<<<<<<<<<< - * res = [] - * for i in self._items: - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_upper(__pyx_v_self, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_1)); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":89 - * cdef _Pair item - * key = self._upper(key) - * res = [] # <<<<<<<<<<<<<< - * for i in self._items: - * item = <_Pair>i - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_res = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":90 - * key = self._upper(key) - * res = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == key: - */ - if (unlikely(__pyx_v_self->_items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->_items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":91 - * res = [] - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * if item._key == key: - * res.append(item._value) - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":92 - * for i in self._items: - * item = <_Pair>i - * if item._key == key: # <<<<<<<<<<<<<< - * res.append(item._value) - * if res: - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_item->_key, __pyx_v_key, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 92; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":93 - * item = <_Pair>i - * if item._key == key: - * res.append(item._value) # <<<<<<<<<<<<<< - * if res: - * return res - */ - __pyx_t_3 = __pyx_v_item->_value; - __Pyx_INCREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyList_Append(__pyx_v_res, __pyx_t_3); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":92 - * for i in self._items: - * item = <_Pair>i - * if item._key == key: # <<<<<<<<<<<<<< - * res.append(item._value) - * if res: - */ - } - - /* "aiohttp/_multidict.pyx":90 - * key = self._upper(key) - * res = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == key: - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":94 - * if item._key == key: - * res.append(item._value) - * if res: # <<<<<<<<<<<<<< - * return res - * if not res and default is not self.marker: - */ - __pyx_t_4 = (__pyx_v_res != Py_None) && (PyList_GET_SIZE(__pyx_v_res) != 0); - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":95 - * res.append(item._value) - * if res: - * return res # <<<<<<<<<<<<<< - * if not res and default is not self.marker: - * return default - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_res); - __pyx_r = __pyx_v_res; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":94 - * if item._key == key: - * res.append(item._value) - * if res: # <<<<<<<<<<<<<< - * return res - * if not res and default is not self.marker: - */ - } - - /* "aiohttp/_multidict.pyx":96 - * if res: - * return res - * if not res and default is not self.marker: # <<<<<<<<<<<<<< - * return default - * raise KeyError('Key not found: %r' % key) - */ - __pyx_t_6 = (__pyx_v_res != Py_None) && (PyList_GET_SIZE(__pyx_v_res) != 0); - __pyx_t_7 = ((!__pyx_t_6) != 0); - if (__pyx_t_7) { - } else { - __pyx_t_4 = __pyx_t_7; - goto __pyx_L8_bool_binop_done; - } - __pyx_t_7 = (__pyx_v_default != __pyx_v_self->marker); - __pyx_t_6 = (__pyx_t_7 != 0); - __pyx_t_4 = __pyx_t_6; - __pyx_L8_bool_binop_done:; - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":97 - * return res - * if not res and default is not self.marker: - * return default # <<<<<<<<<<<<<< - * raise KeyError('Key not found: %r' % key) - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_default); - __pyx_r = __pyx_v_default; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":96 - * if res: - * return res - * if not res and default is not self.marker: # <<<<<<<<<<<<<< - * return default - * raise KeyError('Key not found: %r' % key) - */ - } - - /* "aiohttp/_multidict.pyx":98 - * if not res and default is not self.marker: - * return default - * raise KeyError('Key not found: %r' % key) # <<<<<<<<<<<<<< - * - * def getone(self, key, default=_marker): - */ - __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_Key_not_found_r, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_KeyError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":85 - * return self._getall(self._upper(key), default) - * - * cdef _getall(self, str key, default): # <<<<<<<<<<<<<< - * cdef list res - * cdef _Pair item - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._Base._getall", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_res); - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_key); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":100 - * raise KeyError('Key not found: %r' % key) - * - * def getone(self, key, default=_marker): # <<<<<<<<<<<<<< - * """Get first value matching the key.""" - * return self._getone(self._upper(key), default) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_5getone(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_5_Base_4getone[] = "Get first value matching the key."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_5getone(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_key = 0; - PyObject *__pyx_v_default = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("getone (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_key,&__pyx_n_s_default,0}; - PyObject* values[2] = {0,0}; - values[1] = __pyx_k__3; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_key)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_default); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "getone") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_key = values[0]; - __pyx_v_default = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("getone", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._Base.getone", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_4getone(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_key, __pyx_v_default); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_4getone(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("getone", 0); - - /* "aiohttp/_multidict.pyx":102 - * def getone(self, key, default=_marker): - * """Get first value matching the key.""" - * return self._getone(self._upper(key), default) # <<<<<<<<<<<<<< - * - * cdef _getone(self, str key, default): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_upper(__pyx_v_self, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_getone(__pyx_v_self, ((PyObject*)__pyx_t_1), __pyx_v_default); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 102; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":100 - * raise KeyError('Key not found: %r' % key) - * - * def getone(self, key, default=_marker): # <<<<<<<<<<<<<< - * """Get first value matching the key.""" - * return self._getone(self._upper(key), default) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._Base.getone", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":104 - * return self._getone(self._upper(key), default) - * - * cdef _getone(self, str key, default): # <<<<<<<<<<<<<< - * cdef _Pair item - * key = self._upper(key) - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__getone(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_getone", 0); - __Pyx_INCREF(__pyx_v_key); - - /* "aiohttp/_multidict.pyx":106 - * cdef _getone(self, str key, default): - * cdef _Pair item - * key = self._upper(key) # <<<<<<<<<<<<<< - * for i in self._items: - * item = <_Pair>i - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_upper(__pyx_v_self, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 106; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_1)); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":107 - * cdef _Pair item - * key = self._upper(key) - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == key: - */ - if (unlikely(__pyx_v_self->_items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->_items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 107; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":108 - * key = self._upper(key) - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * if item._key == key: - * return item._value - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":109 - * for i in self._items: - * item = <_Pair>i - * if item._key == key: # <<<<<<<<<<<<<< - * return item._value - * if default is not self.marker: - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_item->_key, __pyx_v_key, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":110 - * item = <_Pair>i - * if item._key == key: - * return item._value # <<<<<<<<<<<<<< - * if default is not self.marker: - * return default - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_item->_value); - __pyx_r = __pyx_v_item->_value; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":109 - * for i in self._items: - * item = <_Pair>i - * if item._key == key: # <<<<<<<<<<<<<< - * return item._value - * if default is not self.marker: - */ - } - - /* "aiohttp/_multidict.pyx":107 - * cdef _Pair item - * key = self._upper(key) - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == key: - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":111 - * if item._key == key: - * return item._value - * if default is not self.marker: # <<<<<<<<<<<<<< - * return default - * raise KeyError('Key not found: %r' % key) - */ - __pyx_t_4 = (__pyx_v_default != __pyx_v_self->marker); - __pyx_t_5 = (__pyx_t_4 != 0); - if (__pyx_t_5) { - - /* "aiohttp/_multidict.pyx":112 - * return item._value - * if default is not self.marker: - * return default # <<<<<<<<<<<<<< - * raise KeyError('Key not found: %r' % key) - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_default); - __pyx_r = __pyx_v_default; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":111 - * if item._key == key: - * return item._value - * if default is not self.marker: # <<<<<<<<<<<<<< - * return default - * raise KeyError('Key not found: %r' % key) - */ - } - - /* "aiohttp/_multidict.pyx":113 - * if default is not self.marker: - * return default - * raise KeyError('Key not found: %r' % key) # <<<<<<<<<<<<<< - * - * # Mapping interface # - */ - __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_Key_not_found_r, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_KeyError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":104 - * return self._getone(self._upper(key), default) - * - * cdef _getone(self, str key, default): # <<<<<<<<<<<<<< - * cdef _Pair item - * key = self._upper(key) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._Base._getone", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_key); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":117 - * # Mapping interface # - * - * def __getitem__(self, key): # <<<<<<<<<<<<<< - * return self._getone(self._upper(key), self.marker) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_7__getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_7__getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_6__getitem__(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), ((PyObject *)__pyx_v_key)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_6__getitem__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getitem__", 0); - - /* "aiohttp/_multidict.pyx":118 - * - * def __getitem__(self, key): - * return self._getone(self._upper(key), self.marker) # <<<<<<<<<<<<<< - * - * def get(self, key, default=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_upper(__pyx_v_self, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __pyx_v_self->marker; - __Pyx_INCREF(__pyx_t_2); - __pyx_t_3 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_getone(__pyx_v_self, ((PyObject*)__pyx_t_1), __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":117 - * # Mapping interface # - * - * def __getitem__(self, key): # <<<<<<<<<<<<<< - * return self._getone(self._upper(key), self.marker) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._Base.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":120 - * return self._getone(self._upper(key), self.marker) - * - * def get(self, key, default=None): # <<<<<<<<<<<<<< - * """Get first value matching the key. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_9get(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_5_Base_8get[] = "Get first value matching the key.\n\n The method is alias for .getone().\n "; -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_9get(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_key = 0; - PyObject *__pyx_v_default = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("get (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_key,&__pyx_n_s_default,0}; - PyObject* values[2] = {0,0}; - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_key)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_default); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "get") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_key = values[0]; - __pyx_v_default = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("get", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._Base.get", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_8get(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_key, __pyx_v_default); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_8get(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get", 0); - - /* "aiohttp/_multidict.pyx":125 - * The method is alias for .getone(). - * """ - * return self._getone(self._upper(key), default) # <<<<<<<<<<<<<< - * - * def __contains__(self, key): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_upper(__pyx_v_self, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_getone(__pyx_v_self, ((PyObject*)__pyx_t_1), __pyx_v_default); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":120 - * return self._getone(self._upper(key), self.marker) - * - * def get(self, key, default=None): # <<<<<<<<<<<<<< - * """Get first value matching the key. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._Base.get", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":127 - * return self._getone(self._upper(key), default) - * - * def __contains__(self, key): # <<<<<<<<<<<<<< - * return self._contains(self._upper(key)) - * - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_5_Base_11__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_key); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_5_Base_11__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_key) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__contains__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_10__contains__(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), ((PyObject *)__pyx_v_key)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_5_Base_10__contains__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__contains__", 0); - - /* "aiohttp/_multidict.pyx":128 - * - * def __contains__(self, key): - * return self._contains(self._upper(key)) # <<<<<<<<<<<<<< - * - * cdef _contains(self, str key): - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_upper(__pyx_v_self, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_contains(__pyx_v_self, ((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":127 - * return self._getone(self._upper(key), default) - * - * def __contains__(self, key): # <<<<<<<<<<<<<< - * return self._contains(self._upper(key)) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._Base.__contains__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":130 - * return self._contains(self._upper(key)) - * - * cdef _contains(self, str key): # <<<<<<<<<<<<<< - * cdef _Pair item - * key = self._upper(key) - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__contains(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_key) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_contains", 0); - __Pyx_INCREF(__pyx_v_key); - - /* "aiohttp/_multidict.pyx":132 - * cdef _contains(self, str key): - * cdef _Pair item - * key = self._upper(key) # <<<<<<<<<<<<<< - * for i in self._items: - * item = <_Pair>i - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->_upper(__pyx_v_self, __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_1)); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":133 - * cdef _Pair item - * key = self._upper(key) - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == key: - */ - if (unlikely(__pyx_v_self->_items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->_items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":134 - * key = self._upper(key) - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * if item._key == key: - * return True - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":135 - * for i in self._items: - * item = <_Pair>i - * if item._key == key: # <<<<<<<<<<<<<< - * return True - * return False - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_item->_key, __pyx_v_key, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":136 - * item = <_Pair>i - * if item._key == key: - * return True # <<<<<<<<<<<<<< - * return False - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_True); - __pyx_r = Py_True; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":135 - * for i in self._items: - * item = <_Pair>i - * if item._key == key: # <<<<<<<<<<<<<< - * return True - * return False - */ - } - - /* "aiohttp/_multidict.pyx":133 - * cdef _Pair item - * key = self._upper(key) - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == key: - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":137 - * if item._key == key: - * return True - * return False # <<<<<<<<<<<<<< - * - * def __iter__(self): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":130 - * return self._contains(self._upper(key)) - * - * cdef _contains(self, str key): # <<<<<<<<<<<<<< - * cdef _Pair item - * key = self._upper(key) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._Base._contains", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_key); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":139 - * return False - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return iter(self.keys()) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_13__iter__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_13__iter__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_12__iter__(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_12__iter__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__iter__", 0); - - /* "aiohttp/_multidict.pyx":140 - * - * def __iter__(self): - * return iter(self.keys()) # <<<<<<<<<<<<<< - * - * def __len__(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->keys(__pyx_v_self, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 140; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":139 - * return False - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return iter(self.keys()) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._Base.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":142 - * return iter(self.keys()) - * - * def __len__(self): # <<<<<<<<<<<<<< - * return len(self._items) - * - */ - -/* Python wrapper */ -static Py_ssize_t __pyx_pw_7aiohttp_10_multidict_5_Base_15__len__(PyObject *__pyx_v_self); /*proto*/ -static Py_ssize_t __pyx_pw_7aiohttp_10_multidict_5_Base_15__len__(PyObject *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_14__len__(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static Py_ssize_t __pyx_pf_7aiohttp_10_multidict_5_Base_14__len__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__len__", 0); - - /* "aiohttp/_multidict.pyx":143 - * - * def __len__(self): - * return len(self._items) # <<<<<<<<<<<<<< - * - * cpdef keys(self): - */ - __pyx_t_1 = __pyx_v_self->_items; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = PyList_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":142 - * return iter(self.keys()) - * - * def __len__(self): # <<<<<<<<<<<<<< - * return len(self._items) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict._Base.__len__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":145 - * return len(self._items) - * - * cpdef keys(self): # <<<<<<<<<<<<<< - * """Return a new view of the dictionary's keys.""" - * return _KeysView.__new__(_KeysView, self._items) - */ - -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_17keys(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base_keys(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, int __pyx_skip_dispatch) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("keys", 0); - /* Check if called by wrapper */ - if (unlikely(__pyx_skip_dispatch)) ; - /* Check if overridden in Python */ - else if (unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0)) { - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_keys); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!PyCFunction_Check(__pyx_t_1) || (PyCFunction_GET_FUNCTION(__pyx_t_1) != (PyCFunction)__pyx_pw_7aiohttp_10_multidict_5_Base_17keys)) { - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_t_1); - __pyx_t_3 = __pyx_t_1; __pyx_t_4 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - if (__pyx_t_4) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else { - __pyx_t_2 = __Pyx_PyObject_CallNoArg(__pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - - /* "aiohttp/_multidict.pyx":147 - * cpdef keys(self): - * """Return a new view of the dictionary's keys.""" - * return _KeysView.__new__(_KeysView, self._items) # <<<<<<<<<<<<<< - * - * def items(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->_items); - __Pyx_GIVEREF(__pyx_v_self->_items); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->_items); - __pyx_t_2 = __pyx_tp_new_7aiohttp_10_multidict__KeysView(((PyTypeObject *)__pyx_ptype_7aiohttp_10_multidict__KeysView), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":145 - * return len(self._items) - * - * cpdef keys(self): # <<<<<<<<<<<<<< - * """Return a new view of the dictionary's keys.""" - * return _KeysView.__new__(_KeysView, self._items) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._multidict._Base.keys", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_17keys(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_5_Base_16keys[] = "Return a new view of the dictionary's keys."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_17keys(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("keys (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_16keys(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_16keys(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("keys", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_f_7aiohttp_10_multidict_5_Base_keys(__pyx_v_self, 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict._Base.keys", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":149 - * return _KeysView.__new__(_KeysView, self._items) - * - * def items(self): # <<<<<<<<<<<<<< - * """Return a new view of the dictionary's items *(key, value) pairs).""" - * return _ItemsView.__new__(_ItemsView, self._items) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_19items(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_5_Base_18items[] = "Return a new view of the dictionary's items *(key, value) pairs)."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_19items(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("items (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_18items(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_18items(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("items", 0); - - /* "aiohttp/_multidict.pyx":151 - * def items(self): - * """Return a new view of the dictionary's items *(key, value) pairs).""" - * return _ItemsView.__new__(_ItemsView, self._items) # <<<<<<<<<<<<<< - * - * def values(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->_items); - __Pyx_GIVEREF(__pyx_v_self->_items); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->_items); - __pyx_t_2 = __pyx_tp_new_7aiohttp_10_multidict__ItemsView(((PyTypeObject *)__pyx_ptype_7aiohttp_10_multidict__ItemsView), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":149 - * return _KeysView.__new__(_KeysView, self._items) - * - * def items(self): # <<<<<<<<<<<<<< - * """Return a new view of the dictionary's items *(key, value) pairs).""" - * return _ItemsView.__new__(_ItemsView, self._items) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._Base.items", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":153 - * return _ItemsView.__new__(_ItemsView, self._items) - * - * def values(self): # <<<<<<<<<<<<<< - * """Return a new view of the dictionary's values.""" - * return _ValuesView.__new__(_ValuesView, self._items) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_21values(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_5_Base_20values[] = "Return a new view of the dictionary's values."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_21values(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("values (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_20values(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_20values(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("values", 0); - - /* "aiohttp/_multidict.pyx":155 - * def values(self): - * """Return a new view of the dictionary's values.""" - * return _ValuesView.__new__(_ValuesView, self._items) # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->_items); - __Pyx_GIVEREF(__pyx_v_self->_items); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->_items); - __pyx_t_2 = __pyx_tp_new_7aiohttp_10_multidict__ValuesView(((PyTypeObject *)__pyx_ptype_7aiohttp_10_multidict__ValuesView), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":153 - * return _ItemsView.__new__(_ItemsView, self._items) - * - * def values(self): # <<<<<<<<<<<<<< - * """Return a new view of the dictionary's values.""" - * return _ValuesView.__new__(_ValuesView, self._items) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._Base.values", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":157 - * return _ValuesView.__new__(_ValuesView, self._items) - * - * def __repr__(self): # <<<<<<<<<<<<<< - * cdef _Pair item - * lst = [] - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_23__repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_23__repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_22__repr__(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_22__repr__(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_lst = NULL; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_body = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - Py_ssize_t __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "aiohttp/_multidict.pyx":159 - * def __repr__(self): - * cdef _Pair item - * lst = [] # <<<<<<<<<<<<<< - * for i in self._items: - * item = <_Pair>i - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_lst = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":160 - * cdef _Pair item - * lst = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * lst.append("'{}': {!r}".format(item._key, item._value)) - */ - if (unlikely(__pyx_v_self->_items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->_items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":161 - * lst = [] - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * lst.append("'{}': {!r}".format(item._key, item._value)) - * body = ', '.join(lst) - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":162 - * for i in self._items: - * item = <_Pair>i - * lst.append("'{}': {!r}".format(item._key, item._value)) # <<<<<<<<<<<<<< - * body = ', '.join(lst) - * return '<{}({})>'.format(self.__class__.__name__, body) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_r, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - __pyx_t_6 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_6 = 1; - } - } - __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_5) { - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); __pyx_t_5 = NULL; - } - __Pyx_INCREF(__pyx_v_item->_key); - __Pyx_GIVEREF(__pyx_v_item->_key); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_item->_key); - __Pyx_INCREF(__pyx_v_item->_value); - __Pyx_GIVEREF(__pyx_v_item->_value); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_item->_value); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_7, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_8 = __Pyx_PyList_Append(__pyx_v_lst, __pyx_t_3); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":160 - * cdef _Pair item - * lst = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * lst.append("'{}': {!r}".format(item._key, item._value)) - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":163 - * item = <_Pair>i - * lst.append("'{}': {!r}".format(item._key, item._value)) - * body = ', '.join(lst) # <<<<<<<<<<<<<< - * return '<{}({})>'.format(self.__class__.__name__, body) - * - */ - __pyx_t_1 = __Pyx_PyString_Join(__pyx_kp_s__4, __pyx_v_lst); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_body = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":164 - * lst.append("'{}': {!r}".format(item._key, item._value)) - * body = ', '.join(lst) - * return '<{}({})>'.format(self.__class__.__name__, body) # <<<<<<<<<<<<<< - * - * cdef _eq_to_mapping(self, other): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s__5, __pyx_n_s_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_name); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - __pyx_t_2 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_2 = 1; - } - } - __pyx_t_5 = PyTuple_New(2+__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_2, __pyx_t_7); - __Pyx_INCREF(__pyx_v_body); - __Pyx_GIVEREF(__pyx_v_body); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_2, __pyx_v_body); - __pyx_t_7 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":157 - * return _ValuesView.__new__(_ValuesView, self._items) - * - * def __repr__(self): # <<<<<<<<<<<<<< - * cdef _Pair item - * lst = [] - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._multidict._Base.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_lst); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_body); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":166 - * return '<{}({})>'.format(self.__class__.__name__, body) - * - * cdef _eq_to_mapping(self, other): # <<<<<<<<<<<<<< - * cdef _Pair item - * left_keys = set(self.keys()) - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_5_Base__eq_to_mapping(struct __pyx_obj_7aiohttp_10_multidict__Base *__pyx_v_self, PyObject *__pyx_v_other) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_left_keys = NULL; - PyObject *__pyx_v_right_keys = NULL; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_nv = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - Py_ssize_t __pyx_t_5; - Py_ssize_t __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_eq_to_mapping", 0); - - /* "aiohttp/_multidict.pyx":168 - * cdef _eq_to_mapping(self, other): - * cdef _Pair item - * left_keys = set(self.keys()) # <<<<<<<<<<<<<< - * right_keys = set(other.keys()) - * if left_keys != right_keys: - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict__Base *)__pyx_v_self->__pyx_vtab)->keys(__pyx_v_self, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySet_New(__pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_left_keys = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":169 - * cdef _Pair item - * left_keys = set(self.keys()) - * right_keys = set(other.keys()) # <<<<<<<<<<<<<< - * if left_keys != right_keys: - * return False - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_other, __pyx_n_s_keys); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - if (__pyx_t_3) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __pyx_t_2 = __Pyx_PyObject_CallNoArg(__pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PySet_New(__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_right_keys = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":170 - * left_keys = set(self.keys()) - * right_keys = set(other.keys()) - * if left_keys != right_keys: # <<<<<<<<<<<<<< - * return False - * if len(self._items) != len(right_keys): - */ - __pyx_t_1 = PyObject_RichCompare(__pyx_v_left_keys, __pyx_v_right_keys, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":171 - * right_keys = set(other.keys()) - * if left_keys != right_keys: - * return False # <<<<<<<<<<<<<< - * if len(self._items) != len(right_keys): - * return False - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":170 - * left_keys = set(self.keys()) - * right_keys = set(other.keys()) - * if left_keys != right_keys: # <<<<<<<<<<<<<< - * return False - * if len(self._items) != len(right_keys): - */ - } - - /* "aiohttp/_multidict.pyx":172 - * if left_keys != right_keys: - * return False - * if len(self._items) != len(right_keys): # <<<<<<<<<<<<<< - * return False - * for i in self._items: - */ - __pyx_t_1 = __pyx_v_self->_items; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_5 = PyList_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = PySet_GET_SIZE(__pyx_v_right_keys); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = ((__pyx_t_5 != __pyx_t_6) != 0); - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":173 - * return False - * if len(self._items) != len(right_keys): - * return False # <<<<<<<<<<<<<< - * for i in self._items: - * item = <_Pair>i - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":172 - * if left_keys != right_keys: - * return False - * if len(self._items) != len(right_keys): # <<<<<<<<<<<<<< - * return False - * for i in self._items: - */ - } - - /* "aiohttp/_multidict.pyx":174 - * if len(self._items) != len(right_keys): - * return False - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * nv = other.get(item._key, self.marker) - */ - if (unlikely(__pyx_v_self->_items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->_items; __Pyx_INCREF(__pyx_t_1); __pyx_t_6 = 0; - for (;;) { - if (__pyx_t_6 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_6); __Pyx_INCREF(__pyx_t_2); __pyx_t_6++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_6); __pyx_t_6++; if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":175 - * return False - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * nv = other.get(item._key, self.marker) - * if item._value != nv: - */ - __pyx_t_2 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_2); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_2)); - __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":176 - * for i in self._items: - * item = <_Pair>i - * nv = other.get(item._key, self.marker) # <<<<<<<<<<<<<< - * if item._value != nv: - * return False - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_other, __pyx_n_s_get); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_7 = NULL; - __pyx_t_5 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_5 = 1; - } - } - __pyx_t_8 = PyTuple_New(2+__pyx_t_5); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_INCREF(__pyx_v_item->_key); - __Pyx_GIVEREF(__pyx_v_item->_key); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_5, __pyx_v_item->_key); - __Pyx_INCREF(__pyx_v_self->marker); - __Pyx_GIVEREF(__pyx_v_self->marker); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_5, __pyx_v_self->marker); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_8, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF_SET(__pyx_v_nv, __pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":177 - * item = <_Pair>i - * nv = other.get(item._key, self.marker) - * if item._value != nv: # <<<<<<<<<<<<<< - * return False - * return True - */ - __pyx_t_2 = PyObject_RichCompare(__pyx_v_item->_value, __pyx_v_nv, Py_NE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":178 - * nv = other.get(item._key, self.marker) - * if item._value != nv: - * return False # <<<<<<<<<<<<<< - * return True - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":177 - * item = <_Pair>i - * nv = other.get(item._key, self.marker) - * if item._value != nv: # <<<<<<<<<<<<<< - * return False - * return True - */ - } - - /* "aiohttp/_multidict.pyx":174 - * if len(self._items) != len(right_keys): - * return False - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * nv = other.get(item._key, self.marker) - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":179 - * if item._value != nv: - * return False - * return True # <<<<<<<<<<<<<< - * - * def __richcmp__(self, other, op): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_True); - __pyx_r = Py_True; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":166 - * return '<{}({})>'.format(self.__class__.__name__, body) - * - * cdef _eq_to_mapping(self, other): # <<<<<<<<<<<<<< - * cdef _Pair item - * left_keys = set(self.keys()) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("aiohttp._multidict._Base._eq_to_mapping", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_left_keys); - __Pyx_XDECREF(__pyx_v_right_keys); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_nv); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":181 - * return True - * - * def __richcmp__(self, other, op): # <<<<<<<<<<<<<< - * if op == 2: # == - * return _eq(self, other) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_25__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, int __pyx_arg_op); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_5_Base_25__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, int __pyx_arg_op) { - PyObject *__pyx_v_op = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__richcmp__ (wrapper)", 0); - __pyx_v_op = __Pyx_PyInt_From_int(__pyx_arg_op); if (unlikely(!__pyx_v_op)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __Pyx_GOTREF(__pyx_v_op); - goto __pyx_L4_argument_unpacking_done; - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._Base.__richcmp__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_5_Base_24__richcmp__(((PyObject *)__pyx_v_self), ((PyObject *)__pyx_v_other), ((PyObject *)__pyx_v_op)); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_op); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_5_Base_24__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, PyObject *__pyx_v_op) { - PyObject *__pyx_v_ret = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__richcmp__", 0); - - /* "aiohttp/_multidict.pyx":182 - * - * def __richcmp__(self, other, op): - * if op == 2: # == # <<<<<<<<<<<<<< - * return _eq(self, other) - * elif op == 3: # != - */ - __pyx_t_1 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_2, 2, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":183 - * def __richcmp__(self, other, op): - * if op == 2: # == - * return _eq(self, other) # <<<<<<<<<<<<<< - * elif op == 3: # != - * ret = _eq(self, other) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_f_7aiohttp_10_multidict__eq(__pyx_v_self, __pyx_v_other); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":182 - * - * def __richcmp__(self, other, op): - * if op == 2: # == # <<<<<<<<<<<<<< - * return _eq(self, other) - * elif op == 3: # != - */ - } - - /* "aiohttp/_multidict.pyx":184 - * if op == 2: # == - * return _eq(self, other) - * elif op == 3: # != # <<<<<<<<<<<<<< - * ret = _eq(self, other) - * if ret is NotImplemented: - */ - __pyx_t_1 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_3, 3, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":185 - * return _eq(self, other) - * elif op == 3: # != - * ret = _eq(self, other) # <<<<<<<<<<<<<< - * if ret is NotImplemented: - * return ret - */ - __pyx_t_1 = __pyx_f_7aiohttp_10_multidict__eq(__pyx_v_self, __pyx_v_other); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_ret = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":186 - * elif op == 3: # != - * ret = _eq(self, other) - * if ret is NotImplemented: # <<<<<<<<<<<<<< - * return ret - * else: - */ - __pyx_t_2 = (__pyx_v_ret == __pyx_builtin_NotImplemented); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":187 - * ret = _eq(self, other) - * if ret is NotImplemented: - * return ret # <<<<<<<<<<<<<< - * else: - * return not ret - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_ret); - __pyx_r = __pyx_v_ret; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":186 - * elif op == 3: # != - * ret = _eq(self, other) - * if ret is NotImplemented: # <<<<<<<<<<<<<< - * return ret - * else: - */ - } - - /* "aiohttp/_multidict.pyx":189 - * return ret - * else: - * return not ret # <<<<<<<<<<<<<< - * else: - * return NotImplemented - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_ret); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __Pyx_PyBool_FromLong((!__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - } - - /* "aiohttp/_multidict.pyx":184 - * if op == 2: # == - * return _eq(self, other) - * elif op == 3: # != # <<<<<<<<<<<<<< - * ret = _eq(self, other) - * if ret is NotImplemented: - */ - } - - /* "aiohttp/_multidict.pyx":191 - * return not ret - * else: - * return NotImplemented # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - } - - /* "aiohttp/_multidict.pyx":181 - * return True - * - * def __richcmp__(self, other, op): # <<<<<<<<<<<<<< - * if op == 2: # == - * return _eq(self, other) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict._Base.__richcmp__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ret); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":196 - * cdef class MultiDictProxy(_Base): - * - * def __init__(self, arg): # <<<<<<<<<<<<<< - * cdef MultiDict mdict - * if not isinstance(arg, MultiDict): - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_14MultiDictProxy_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_14MultiDictProxy_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_arg = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_arg,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_arg)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_arg = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict.MultiDictProxy.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_14MultiDictProxy___init__(((struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy *)__pyx_v_self), __pyx_v_arg); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_14MultiDictProxy___init__(struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy *__pyx_v_self, PyObject *__pyx_v_arg) { - struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_mdict = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__init__", 0); - - /* "aiohttp/_multidict.pyx":198 - * def __init__(self, arg): - * cdef MultiDict mdict - * if not isinstance(arg, MultiDict): # <<<<<<<<<<<<<< - * raise TypeError( - * 'MultiDictProxy requires MultiDict instance, not {}'.format( - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_arg, __pyx_ptype_7aiohttp_10_multidict_MultiDict); - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":200 - * if not isinstance(arg, MultiDict): - * raise TypeError( - * 'MultiDictProxy requires MultiDict instance, not {}'.format( # <<<<<<<<<<<<<< - * type(arg))) - * - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_MultiDictProxy_requires_MultiDic, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - - /* "aiohttp/_multidict.pyx":201 - * raise TypeError( - * 'MultiDictProxy requires MultiDict instance, not {}'.format( - * type(arg))) # <<<<<<<<<<<<<< - * - * mdict = arg - */ - __pyx_t_5 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - if (!__pyx_t_5) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, ((PyObject *)Py_TYPE(__pyx_v_arg))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - } else { - __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; - __Pyx_INCREF(((PyObject *)Py_TYPE(__pyx_v_arg))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(__pyx_v_arg))); - PyTuple_SET_ITEM(__pyx_t_6, 0+1, ((PyObject *)Py_TYPE(__pyx_v_arg))); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 200; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":199 - * cdef MultiDict mdict - * if not isinstance(arg, MultiDict): - * raise TypeError( # <<<<<<<<<<<<<< - * 'MultiDictProxy requires MultiDict instance, not {}'.format( - * type(arg))) - */ - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":198 - * def __init__(self, arg): - * cdef MultiDict mdict - * if not isinstance(arg, MultiDict): # <<<<<<<<<<<<<< - * raise TypeError( - * 'MultiDictProxy requires MultiDict instance, not {}'.format( - */ - } - - /* "aiohttp/_multidict.pyx":203 - * type(arg))) - * - * mdict = arg # <<<<<<<<<<<<<< - * self._items = mdict._items - * - */ - if (!(likely(((__pyx_v_arg) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_arg, __pyx_ptype_7aiohttp_10_multidict_MultiDict))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __pyx_v_arg; - __Pyx_INCREF(__pyx_t_3); - __pyx_v_mdict = ((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":204 - * - * mdict = arg - * self._items = mdict._items # <<<<<<<<<<<<<< - * - * def copy(self): - */ - __pyx_t_3 = __pyx_v_mdict->__pyx_base._items; - __Pyx_INCREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->__pyx_base._items); - __Pyx_DECREF(__pyx_v_self->__pyx_base._items); - __pyx_v_self->__pyx_base._items = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":196 - * cdef class MultiDictProxy(_Base): - * - * def __init__(self, arg): # <<<<<<<<<<<<<< - * cdef MultiDict mdict - * if not isinstance(arg, MultiDict): - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._multidict.MultiDictProxy.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_mdict); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":206 - * self._items = mdict._items - * - * def copy(self): # <<<<<<<<<<<<<< - * """Return a copy of itself.""" - * return MultiDict(self._items) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_14MultiDictProxy_3copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_14MultiDictProxy_2copy[] = "Return a copy of itself."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_14MultiDictProxy_3copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("copy (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_14MultiDictProxy_2copy(((struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_14MultiDictProxy_2copy(struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("copy", 0); - - /* "aiohttp/_multidict.pyx":208 - * def copy(self): - * """Return a copy of itself.""" - * return MultiDict(self._items) # <<<<<<<<<<<<<< - * - * abc.Mapping.register(MultiDictProxy) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->__pyx_base._items); - __Pyx_GIVEREF(__pyx_v_self->__pyx_base._items); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->__pyx_base._items); - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_MultiDict), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":206 - * self._items = mdict._items - * - * def copy(self): # <<<<<<<<<<<<<< - * """Return a copy of itself.""" - * return MultiDict(self._items) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict.MultiDictProxy.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":215 - * cdef class CIMultiDictProxy(MultiDictProxy): - * - * def __init__(self, arg): # <<<<<<<<<<<<<< - * cdef CIMultiDict mdict - * if not isinstance(arg, CIMultiDict): - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_16CIMultiDictProxy_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_16CIMultiDictProxy_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_arg = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_arg,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_arg)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_arg = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict.CIMultiDictProxy.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_16CIMultiDictProxy___init__(((struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *)__pyx_v_self), __pyx_v_arg); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_16CIMultiDictProxy___init__(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *__pyx_v_self, PyObject *__pyx_v_arg) { - struct __pyx_obj_7aiohttp_10_multidict_CIMultiDict *__pyx_v_mdict = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__init__", 0); - - /* "aiohttp/_multidict.pyx":217 - * def __init__(self, arg): - * cdef CIMultiDict mdict - * if not isinstance(arg, CIMultiDict): # <<<<<<<<<<<<<< - * raise TypeError( - * 'CIMultiDictProxy requires CIMultiDict instance, not {}'.format( - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_arg, __pyx_ptype_7aiohttp_10_multidict_CIMultiDict); - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":219 - * if not isinstance(arg, CIMultiDict): - * raise TypeError( - * 'CIMultiDictProxy requires CIMultiDict instance, not {}'.format( # <<<<<<<<<<<<<< - * type(arg))) - * - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_CIMultiDictProxy_requires_CIMult, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - - /* "aiohttp/_multidict.pyx":220 - * raise TypeError( - * 'CIMultiDictProxy requires CIMultiDict instance, not {}'.format( - * type(arg))) # <<<<<<<<<<<<<< - * - * mdict = arg - */ - __pyx_t_5 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - if (!__pyx_t_5) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, ((PyObject *)Py_TYPE(__pyx_v_arg))); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - } else { - __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; - __Pyx_INCREF(((PyObject *)Py_TYPE(__pyx_v_arg))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(__pyx_v_arg))); - PyTuple_SET_ITEM(__pyx_t_6, 0+1, ((PyObject *)Py_TYPE(__pyx_v_arg))); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":218 - * cdef CIMultiDict mdict - * if not isinstance(arg, CIMultiDict): - * raise TypeError( # <<<<<<<<<<<<<< - * 'CIMultiDictProxy requires CIMultiDict instance, not {}'.format( - * type(arg))) - */ - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":217 - * def __init__(self, arg): - * cdef CIMultiDict mdict - * if not isinstance(arg, CIMultiDict): # <<<<<<<<<<<<<< - * raise TypeError( - * 'CIMultiDictProxy requires CIMultiDict instance, not {}'.format( - */ - } - - /* "aiohttp/_multidict.pyx":222 - * type(arg))) - * - * mdict = arg # <<<<<<<<<<<<<< - * self._items = mdict._items - * - */ - if (!(likely(((__pyx_v_arg) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_arg, __pyx_ptype_7aiohttp_10_multidict_CIMultiDict))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __pyx_v_arg; - __Pyx_INCREF(__pyx_t_3); - __pyx_v_mdict = ((struct __pyx_obj_7aiohttp_10_multidict_CIMultiDict *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":223 - * - * mdict = arg - * self._items = mdict._items # <<<<<<<<<<<<<< - * - * cdef str _upper(self, s): - */ - __pyx_t_3 = __pyx_v_mdict->__pyx_base.__pyx_base._items; - __Pyx_INCREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->__pyx_base.__pyx_base._items); - __Pyx_DECREF(__pyx_v_self->__pyx_base.__pyx_base._items); - __pyx_v_self->__pyx_base.__pyx_base._items = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":215 - * cdef class CIMultiDictProxy(MultiDictProxy): - * - * def __init__(self, arg): # <<<<<<<<<<<<<< - * cdef CIMultiDict mdict - * if not isinstance(arg, CIMultiDict): - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._multidict.CIMultiDictProxy.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_mdict); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":225 - * self._items = mdict._items - * - * cdef str _upper(self, s): # <<<<<<<<<<<<<< - * if type(s) is self._upstr: - * return <str>s - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_16CIMultiDictProxy__upper(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *__pyx_v_self, PyObject *__pyx_v_s) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_upper", 0); - - /* "aiohttp/_multidict.pyx":226 - * - * cdef str _upper(self, s): - * if type(s) is self._upstr: # <<<<<<<<<<<<<< - * return <str>s - * return s.upper() - */ - __pyx_t_1 = (((PyObject *)Py_TYPE(__pyx_v_s)) == __pyx_v_self->__pyx_base.__pyx_base._upstr); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":227 - * cdef str _upper(self, s): - * if type(s) is self._upstr: - * return <str>s # <<<<<<<<<<<<<< - * return s.upper() - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject*)__pyx_v_s)); - __pyx_r = ((PyObject*)__pyx_v_s); - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":226 - * - * cdef str _upper(self, s): - * if type(s) is self._upstr: # <<<<<<<<<<<<<< - * return <str>s - * return s.upper() - */ - } - - /* "aiohttp/_multidict.pyx":228 - * if type(s) is self._upstr: - * return <str>s - * return s.upper() # <<<<<<<<<<<<<< - * - * def copy(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_s, __pyx_n_s_upper); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - if (__pyx_t_5) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else { - __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(PyString_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":225 - * self._items = mdict._items - * - * cdef str _upper(self, s): # <<<<<<<<<<<<<< - * if type(s) is self._upstr: - * return <str>s - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("aiohttp._multidict.CIMultiDictProxy._upper", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":230 - * return s.upper() - * - * def copy(self): # <<<<<<<<<<<<<< - * """Return a copy of itself.""" - * return CIMultiDict(self._items) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_16CIMultiDictProxy_3copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_16CIMultiDictProxy_2copy[] = "Return a copy of itself."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_16CIMultiDictProxy_3copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("copy (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_16CIMultiDictProxy_2copy(((struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_16CIMultiDictProxy_2copy(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("copy", 0); - - /* "aiohttp/_multidict.pyx":232 - * def copy(self): - * """Return a copy of itself.""" - * return CIMultiDict(self._items) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->__pyx_base.__pyx_base._items); - __Pyx_GIVEREF(__pyx_v_self->__pyx_base.__pyx_base._items); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->__pyx_base.__pyx_base._items); - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_CIMultiDict), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":230 - * return s.upper() - * - * def copy(self): # <<<<<<<<<<<<<< - * """Return a copy of itself.""" - * return CIMultiDict(self._items) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict.CIMultiDictProxy.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":241 - * """An ordered dictionary that can have multiple values for each key.""" - * - * def __init__(self, *args, **kwargs): # <<<<<<<<<<<<<< - * self._items = [] - * - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_9MultiDict_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_9MultiDict_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_args = 0; - PyObject *__pyx_v_kwargs = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - if (unlikely(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__init__", 1))) return -1; - __pyx_v_kwargs = (__pyx_kwds) ? PyDict_Copy(__pyx_kwds) : PyDict_New(); if (unlikely(!__pyx_v_kwargs)) return -1; - __Pyx_GOTREF(__pyx_v_kwargs); - __Pyx_INCREF(__pyx_args); - __pyx_v_args = __pyx_args; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict___init__(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self), __pyx_v_args, __pyx_v_kwargs); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_args); - __Pyx_XDECREF(__pyx_v_kwargs); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_9MultiDict___init__(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__init__", 0); - - /* "aiohttp/_multidict.pyx":242 - * - * def __init__(self, *args, **kwargs): - * self._items = [] # <<<<<<<<<<<<<< - * - * self._extend(args, kwargs, self.__class__.__name__, 1) - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->__pyx_base._items); - __Pyx_DECREF(__pyx_v_self->__pyx_base._items); - __pyx_v_self->__pyx_base._items = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":244 - * self._items = [] - * - * self._extend(args, kwargs, self.__class__.__name__, 1) # <<<<<<<<<<<<<< - * - * cdef _extend(self, tuple args, dict kwargs, name, int do_add): - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_name); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_extend(__pyx_v_self, __pyx_v_args, __pyx_v_kwargs, __pyx_t_2, 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":241 - * """An ordered dictionary that can have multiple values for each key.""" - * - * def __init__(self, *args, **kwargs): # <<<<<<<<<<<<<< - * self._items = [] - * - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":246 - * self._extend(args, kwargs, self.__class__.__name__, 1) - * - * cdef _extend(self, tuple args, dict kwargs, name, int do_add): # <<<<<<<<<<<<<< - * cdef _Pair item - * cdef str key - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_9MultiDict__extend(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, PyObject *__pyx_v_name, int __pyx_v_do_add) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_key = 0; - PyObject *__pyx_v_arg = NULL; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_value = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - PyObject *(*__pyx_t_9)(PyObject *); - Py_ssize_t __pyx_t_10; - PyObject *(*__pyx_t_11)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_extend", 0); - - /* "aiohttp/_multidict.pyx":250 - * cdef str key - * - * if len(args) > 1: # <<<<<<<<<<<<<< - * raise TypeError("{} takes at most 1 positional argument" - * " ({} given)".format(name, len(args))) - */ - if (unlikely(__pyx_v_args == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_args); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 250; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = ((__pyx_t_1 > 1) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":252 - * if len(args) > 1: - * raise TypeError("{} takes at most 1 positional argument" - * " ({} given)".format(name, len(args))) # <<<<<<<<<<<<<< - * - * if args: - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_takes_at_most_1_positional_argu, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (unlikely(__pyx_v_args == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_args); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyInt_FromSsize_t(__pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - __pyx_t_1 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_1 = 1; - } - } - __pyx_t_7 = PyTuple_New(2+__pyx_t_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_6) { - __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); __pyx_t_6 = NULL; - } - __Pyx_INCREF(__pyx_v_name); - __Pyx_GIVEREF(__pyx_v_name); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_1, __pyx_v_name); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_1, __pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_7, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":251 - * - * if len(args) > 1: - * raise TypeError("{} takes at most 1 positional argument" # <<<<<<<<<<<<<< - * " ({} given)".format(name, len(args))) - * - */ - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":250 - * cdef str key - * - * if len(args) > 1: # <<<<<<<<<<<<<< - * raise TypeError("{} takes at most 1 positional argument" - * " ({} given)".format(name, len(args))) - */ - } - - /* "aiohttp/_multidict.pyx":254 - * " ({} given)".format(name, len(args))) - * - * if args: # <<<<<<<<<<<<<< - * arg = args[0] - * if isinstance(arg, _Base): - */ - __pyx_t_2 = (__pyx_v_args != Py_None) && (PyTuple_GET_SIZE(__pyx_v_args) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":255 - * - * if args: - * arg = args[0] # <<<<<<<<<<<<<< - * if isinstance(arg, _Base): - * for i in (<_Base>arg)._items: - */ - if (unlikely(__pyx_v_args == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_3 = __Pyx_GetItemInt_Tuple(__pyx_v_args, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_arg = __pyx_t_3; - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":256 - * if args: - * arg = args[0] - * if isinstance(arg, _Base): # <<<<<<<<<<<<<< - * for i in (<_Base>arg)._items: - * item = <_Pair>i - */ - __pyx_t_2 = __Pyx_TypeCheck(__pyx_v_arg, __pyx_ptype_7aiohttp_10_multidict__Base); - __pyx_t_8 = (__pyx_t_2 != 0); - if (__pyx_t_8) { - - /* "aiohttp/_multidict.pyx":257 - * arg = args[0] - * if isinstance(arg, _Base): - * for i in (<_Base>arg)._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * key = self._upper(item._key) - */ - if (unlikely(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_arg)->_items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_3 = ((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_arg)->_items; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; - for (;;) { - if (__pyx_t_1 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_4); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_4); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":258 - * if isinstance(arg, _Base): - * for i in (<_Base>arg)._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * key = self._upper(item._key) - * value = item._value - */ - __pyx_t_4 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":259 - * for i in (<_Base>arg)._items: - * item = <_Pair>i - * key = self._upper(item._key) # <<<<<<<<<<<<<< - * value = item._value - * if do_add: - */ - __pyx_t_4 = __pyx_v_item->_key; - __Pyx_INCREF(__pyx_t_4); - __pyx_t_7 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._upper(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_t_4); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 259; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_7)); - __pyx_t_7 = 0; - - /* "aiohttp/_multidict.pyx":260 - * item = <_Pair>i - * key = self._upper(item._key) - * value = item._value # <<<<<<<<<<<<<< - * if do_add: - * self._add(key, value) - */ - __pyx_t_7 = __pyx_v_item->_value; - __Pyx_INCREF(__pyx_t_7); - __Pyx_XDECREF_SET(__pyx_v_value, __pyx_t_7); - __pyx_t_7 = 0; - - /* "aiohttp/_multidict.pyx":261 - * key = self._upper(item._key) - * value = item._value - * if do_add: # <<<<<<<<<<<<<< - * self._add(key, value) - * else: - */ - __pyx_t_8 = (__pyx_v_do_add != 0); - if (__pyx_t_8) { - - /* "aiohttp/_multidict.pyx":262 - * value = item._value - * if do_add: - * self._add(key, value) # <<<<<<<<<<<<<< - * else: - * self._replace(key, value) - */ - __pyx_t_7 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_add(__pyx_v_self, __pyx_v_key, __pyx_v_value); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "aiohttp/_multidict.pyx":261 - * key = self._upper(item._key) - * value = item._value - * if do_add: # <<<<<<<<<<<<<< - * self._add(key, value) - * else: - */ - goto __pyx_L8; - } - - /* "aiohttp/_multidict.pyx":264 - * self._add(key, value) - * else: - * self._replace(key, value) # <<<<<<<<<<<<<< - * elif hasattr(arg, 'items'): - * for i in arg.items(): - */ - /*else*/ { - __pyx_t_7 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_replace(__pyx_v_self, __pyx_v_key, __pyx_v_value); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 264; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __pyx_L8:; - - /* "aiohttp/_multidict.pyx":257 - * arg = args[0] - * if isinstance(arg, _Base): - * for i in (<_Base>arg)._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * key = self._upper(item._key) - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":256 - * if args: - * arg = args[0] - * if isinstance(arg, _Base): # <<<<<<<<<<<<<< - * for i in (<_Base>arg)._items: - * item = <_Pair>i - */ - goto __pyx_L5; - } - - /* "aiohttp/_multidict.pyx":265 - * else: - * self._replace(key, value) - * elif hasattr(arg, 'items'): # <<<<<<<<<<<<<< - * for i in arg.items(): - * if isinstance(i, _Pair): - */ - __pyx_t_8 = PyObject_HasAttr(__pyx_v_arg, __pyx_n_s_items); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 265; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_8 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":266 - * self._replace(key, value) - * elif hasattr(arg, 'items'): - * for i in arg.items(): # <<<<<<<<<<<<<< - * if isinstance(i, _Pair): - * item = <_Pair>i - */ - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_items); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - if (__pyx_t_4) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else { - __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_7); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (likely(PyList_CheckExact(__pyx_t_3)) || PyTuple_CheckExact(__pyx_t_3)) { - __pyx_t_7 = __pyx_t_3; __Pyx_INCREF(__pyx_t_7); __pyx_t_1 = 0; - __pyx_t_9 = NULL; - } else { - __pyx_t_1 = -1; __pyx_t_7 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = Py_TYPE(__pyx_t_7)->tp_iternext; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - for (;;) { - if (likely(!__pyx_t_9)) { - if (likely(PyList_CheckExact(__pyx_t_7))) { - if (__pyx_t_1 >= PyList_GET_SIZE(__pyx_t_7)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_7, __pyx_t_1); __Pyx_INCREF(__pyx_t_3); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_7, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - } else { - if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_7)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_7, __pyx_t_1); __Pyx_INCREF(__pyx_t_3); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_7, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - } - } else { - __pyx_t_3 = __pyx_t_9(__pyx_t_7); - if (unlikely(!__pyx_t_3)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 266; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_3); - } - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":267 - * elif hasattr(arg, 'items'): - * for i in arg.items(): - * if isinstance(i, _Pair): # <<<<<<<<<<<<<< - * item = <_Pair>i - * key = item._key - */ - __pyx_t_2 = __Pyx_TypeCheck(__pyx_v_i, __pyx_ptype_7aiohttp_10_multidict__Pair); - __pyx_t_8 = (__pyx_t_2 != 0); - if (__pyx_t_8) { - - /* "aiohttp/_multidict.pyx":268 - * for i in arg.items(): - * if isinstance(i, _Pair): - * item = <_Pair>i # <<<<<<<<<<<<<< - * key = item._key - * value = item._value - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":269 - * if isinstance(i, _Pair): - * item = <_Pair>i - * key = item._key # <<<<<<<<<<<<<< - * value = item._value - * else: - */ - if (!(likely(PyString_CheckExact(__pyx_v_item->_key))||((__pyx_v_item->_key) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(__pyx_v_item->_key)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __pyx_v_item->_key; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":270 - * item = <_Pair>i - * key = item._key - * value = item._value # <<<<<<<<<<<<<< - * else: - * key = self._upper(i[0]) - */ - __pyx_t_3 = __pyx_v_item->_value; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_value, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":267 - * elif hasattr(arg, 'items'): - * for i in arg.items(): - * if isinstance(i, _Pair): # <<<<<<<<<<<<<< - * item = <_Pair>i - * key = item._key - */ - goto __pyx_L11; - } - - /* "aiohttp/_multidict.pyx":272 - * value = item._value - * else: - * key = self._upper(i[0]) # <<<<<<<<<<<<<< - * value = i[1] - * if do_add: - */ - /*else*/ { - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_i, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._upper(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 272; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":273 - * else: - * key = self._upper(i[0]) - * value = i[1] # <<<<<<<<<<<<<< - * if do_add: - * self._add(key, value) - */ - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_i, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_4 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 273; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_value, __pyx_t_4); - __pyx_t_4 = 0; - } - __pyx_L11:; - - /* "aiohttp/_multidict.pyx":274 - * key = self._upper(i[0]) - * value = i[1] - * if do_add: # <<<<<<<<<<<<<< - * self._add(key, value) - * else: - */ - __pyx_t_8 = (__pyx_v_do_add != 0); - if (__pyx_t_8) { - - /* "aiohttp/_multidict.pyx":275 - * value = i[1] - * if do_add: - * self._add(key, value) # <<<<<<<<<<<<<< - * else: - * self._replace(key, value) - */ - __pyx_t_4 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_add(__pyx_v_self, __pyx_v_key, __pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":274 - * key = self._upper(i[0]) - * value = i[1] - * if do_add: # <<<<<<<<<<<<<< - * self._add(key, value) - * else: - */ - goto __pyx_L12; - } - - /* "aiohttp/_multidict.pyx":277 - * self._add(key, value) - * else: - * self._replace(key, value) # <<<<<<<<<<<<<< - * else: - * for i in arg: - */ - /*else*/ { - __pyx_t_4 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_replace(__pyx_v_self, __pyx_v_key, __pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __pyx_L12:; - - /* "aiohttp/_multidict.pyx":266 - * self._replace(key, value) - * elif hasattr(arg, 'items'): - * for i in arg.items(): # <<<<<<<<<<<<<< - * if isinstance(i, _Pair): - * item = <_Pair>i - */ - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "aiohttp/_multidict.pyx":265 - * else: - * self._replace(key, value) - * elif hasattr(arg, 'items'): # <<<<<<<<<<<<<< - * for i in arg.items(): - * if isinstance(i, _Pair): - */ - goto __pyx_L5; - } - - /* "aiohttp/_multidict.pyx":279 - * self._replace(key, value) - * else: - * for i in arg: # <<<<<<<<<<<<<< - * if isinstance(i, _Pair): - * item = <_Pair>i - */ - /*else*/ { - if (likely(PyList_CheckExact(__pyx_v_arg)) || PyTuple_CheckExact(__pyx_v_arg)) { - __pyx_t_7 = __pyx_v_arg; __Pyx_INCREF(__pyx_t_7); __pyx_t_1 = 0; - __pyx_t_9 = NULL; - } else { - __pyx_t_1 = -1; __pyx_t_7 = PyObject_GetIter(__pyx_v_arg); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = Py_TYPE(__pyx_t_7)->tp_iternext; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - for (;;) { - if (likely(!__pyx_t_9)) { - if (likely(PyList_CheckExact(__pyx_t_7))) { - if (__pyx_t_1 >= PyList_GET_SIZE(__pyx_t_7)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_7, __pyx_t_1); __Pyx_INCREF(__pyx_t_4); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_7, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_7)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_7, __pyx_t_1); __Pyx_INCREF(__pyx_t_4); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_7, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - #endif - } - } else { - __pyx_t_4 = __pyx_t_9(__pyx_t_7); - if (unlikely(!__pyx_t_4)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_4); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":280 - * else: - * for i in arg: - * if isinstance(i, _Pair): # <<<<<<<<<<<<<< - * item = <_Pair>i - * key = item._key - */ - __pyx_t_8 = __Pyx_TypeCheck(__pyx_v_i, __pyx_ptype_7aiohttp_10_multidict__Pair); - __pyx_t_2 = (__pyx_t_8 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":281 - * for i in arg: - * if isinstance(i, _Pair): - * item = <_Pair>i # <<<<<<<<<<<<<< - * key = item._key - * value = item._value - */ - __pyx_t_4 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":282 - * if isinstance(i, _Pair): - * item = <_Pair>i - * key = item._key # <<<<<<<<<<<<<< - * value = item._value - * else: - */ - if (!(likely(PyString_CheckExact(__pyx_v_item->_key))||((__pyx_v_item->_key) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(__pyx_v_item->_key)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __pyx_v_item->_key; - __Pyx_INCREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":283 - * item = <_Pair>i - * key = item._key - * value = item._value # <<<<<<<<<<<<<< - * else: - * if not len(i) == 2: - */ - __pyx_t_4 = __pyx_v_item->_value; - __Pyx_INCREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_value, __pyx_t_4); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":280 - * else: - * for i in arg: - * if isinstance(i, _Pair): # <<<<<<<<<<<<<< - * item = <_Pair>i - * key = item._key - */ - goto __pyx_L15; - } - - /* "aiohttp/_multidict.pyx":285 - * value = item._value - * else: - * if not len(i) == 2: # <<<<<<<<<<<<<< - * raise TypeError( - * "{} takes either dict or list of (key, value) " - */ - /*else*/ { - __pyx_t_10 = PyObject_Length(__pyx_v_i); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = ((!((__pyx_t_10 == 2) != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":288 - * raise TypeError( - * "{} takes either dict or list of (key, value) " - * "tuples".format(name)) # <<<<<<<<<<<<<< - * key = self._upper(i[0]) - * value = i[1] - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_takes_either_dict_or_list_of_ke, __pyx_n_s_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - if (!__pyx_t_5) { - __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_name); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - } else { - __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; - __Pyx_INCREF(__pyx_v_name); - __Pyx_GIVEREF(__pyx_v_name); - PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_v_name); - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":286 - * else: - * if not len(i) == 2: - * raise TypeError( # <<<<<<<<<<<<<< - * "{} takes either dict or list of (key, value) " - * "tuples".format(name)) - */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":285 - * value = item._value - * else: - * if not len(i) == 2: # <<<<<<<<<<<<<< - * raise TypeError( - * "{} takes either dict or list of (key, value) " - */ - } - - /* "aiohttp/_multidict.pyx":289 - * "{} takes either dict or list of (key, value) " - * "tuples".format(name)) - * key = self._upper(i[0]) # <<<<<<<<<<<<<< - * value = i[1] - * if do_add: - */ - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_i, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_4 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._upper(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 289; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":290 - * "tuples".format(name)) - * key = self._upper(i[0]) - * value = i[1] # <<<<<<<<<<<<<< - * if do_add: - * self._add(key, value) - */ - __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_i, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_value, __pyx_t_3); - __pyx_t_3 = 0; - } - __pyx_L15:; - - /* "aiohttp/_multidict.pyx":291 - * key = self._upper(i[0]) - * value = i[1] - * if do_add: # <<<<<<<<<<<<<< - * self._add(key, value) - * else: - */ - __pyx_t_2 = (__pyx_v_do_add != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":292 - * value = i[1] - * if do_add: - * self._add(key, value) # <<<<<<<<<<<<<< - * else: - * self._replace(key, value) - */ - __pyx_t_3 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_add(__pyx_v_self, __pyx_v_key, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 292; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":291 - * key = self._upper(i[0]) - * value = i[1] - * if do_add: # <<<<<<<<<<<<<< - * self._add(key, value) - * else: - */ - goto __pyx_L17; - } - - /* "aiohttp/_multidict.pyx":294 - * self._add(key, value) - * else: - * self._replace(key, value) # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __pyx_t_3 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_replace(__pyx_v_self, __pyx_v_key, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 294; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __pyx_L17:; - - /* "aiohttp/_multidict.pyx":279 - * self._replace(key, value) - * else: - * for i in arg: # <<<<<<<<<<<<<< - * if isinstance(i, _Pair): - * item = <_Pair>i - */ - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __pyx_L5:; - - /* "aiohttp/_multidict.pyx":254 - * " ({} given)".format(name, len(args))) - * - * if args: # <<<<<<<<<<<<<< - * arg = args[0] - * if isinstance(arg, _Base): - */ - } - - /* "aiohttp/_multidict.pyx":297 - * - * - * for key, value in kwargs.items(): # <<<<<<<<<<<<<< - * key = self._upper(key) - * if do_add: - */ - if (unlikely(__pyx_v_kwargs == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "items"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_7 = __Pyx_PyDict_Items(__pyx_v_kwargs); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - if (likely(PyList_CheckExact(__pyx_t_7)) || PyTuple_CheckExact(__pyx_t_7)) { - __pyx_t_3 = __pyx_t_7; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; - __pyx_t_9 = NULL; - } else { - __pyx_t_1 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_7); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_9 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - for (;;) { - if (likely(!__pyx_t_9)) { - if (likely(PyList_CheckExact(__pyx_t_3))) { - if (__pyx_t_1 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_7 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_7); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - #endif - } else { - if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_7); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - #endif - } - } else { - __pyx_t_7 = __pyx_t_9(__pyx_t_3); - if (unlikely(!__pyx_t_7)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_7); - } - if ((likely(PyTuple_CheckExact(__pyx_t_7))) || (PyList_CheckExact(__pyx_t_7))) { - PyObject* sequence = __pyx_t_7; - #if CYTHON_COMPILING_IN_CPYTHON - Py_ssize_t size = Py_SIZE(sequence); - #else - Py_ssize_t size = PySequence_Size(sequence); - #endif - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #if CYTHON_COMPILING_IN_CPYTHON - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_4 = PyList_GET_ITEM(sequence, 0); - __pyx_t_6 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_6); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - #endif - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_5 = PyObject_GetIter(__pyx_t_7); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_11 = Py_TYPE(__pyx_t_5)->tp_iternext; - index = 0; __pyx_t_4 = __pyx_t_11(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L20_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - index = 1; __pyx_t_6 = __pyx_t_11(__pyx_t_5); if (unlikely(!__pyx_t_6)) goto __pyx_L20_unpacking_failed; - __Pyx_GOTREF(__pyx_t_6); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_11(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_11 = NULL; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L21_unpacking_done; - __pyx_L20_unpacking_failed:; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_11 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_L21_unpacking_done:; - } - if (!(likely(PyString_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 297; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_XDECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_4)); - __pyx_t_4 = 0; - __Pyx_XDECREF_SET(__pyx_v_value, __pyx_t_6); - __pyx_t_6 = 0; - - /* "aiohttp/_multidict.pyx":298 - * - * for key, value in kwargs.items(): - * key = self._upper(key) # <<<<<<<<<<<<<< - * if do_add: - * self._add(key, value) - */ - __pyx_t_7 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._upper(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_key); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 298; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF_SET(__pyx_v_key, ((PyObject*)__pyx_t_7)); - __pyx_t_7 = 0; - - /* "aiohttp/_multidict.pyx":299 - * for key, value in kwargs.items(): - * key = self._upper(key) - * if do_add: # <<<<<<<<<<<<<< - * self._add(key, value) - * else: - */ - __pyx_t_2 = (__pyx_v_do_add != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":300 - * key = self._upper(key) - * if do_add: - * self._add(key, value) # <<<<<<<<<<<<<< - * else: - * self._replace(key, value) - */ - __pyx_t_7 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_add(__pyx_v_self, __pyx_v_key, __pyx_v_value); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 300; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "aiohttp/_multidict.pyx":299 - * for key, value in kwargs.items(): - * key = self._upper(key) - * if do_add: # <<<<<<<<<<<<<< - * self._add(key, value) - * else: - */ - goto __pyx_L22; - } - - /* "aiohttp/_multidict.pyx":302 - * self._add(key, value) - * else: - * self._replace(key, value) # <<<<<<<<<<<<<< - * - * cdef _add(self, str key, value): - */ - /*else*/ { - __pyx_t_7 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_replace(__pyx_v_self, __pyx_v_key, __pyx_v_value); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __pyx_L22:; - - /* "aiohttp/_multidict.pyx":297 - * - * - * for key, value in kwargs.items(): # <<<<<<<<<<<<<< - * key = self._upper(key) - * if do_add: - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":246 - * self._extend(args, kwargs, self.__class__.__name__, 1) - * - * cdef _extend(self, tuple args, dict kwargs, name, int do_add): # <<<<<<<<<<<<<< - * cdef _Pair item - * cdef str key - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict._extend", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_key); - __Pyx_XDECREF(__pyx_v_arg); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_value); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":304 - * self._replace(key, value) - * - * cdef _add(self, str key, value): # <<<<<<<<<<<<<< - * self._items.append(_Pair.__new__(_Pair, key, value)) - * - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_9MultiDict__add(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_add", 0); - - /* "aiohttp/_multidict.pyx":305 - * - * cdef _add(self, str key, value): - * self._items.append(_Pair.__new__(_Pair, key, value)) # <<<<<<<<<<<<<< - * - * cdef _replace(self, str key, value): - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "append"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_key); - __Pyx_GIVEREF(__pyx_v_key); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_key); - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value); - __pyx_t_2 = __pyx_tp_new_7aiohttp_10_multidict__Pair(((PyTypeObject *)__pyx_ptype_7aiohttp_10_multidict__Pair), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyList_Append(__pyx_v_self->__pyx_base._items, __pyx_t_2); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 305; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":304 - * self._replace(key, value) - * - * cdef _add(self, str key, value): # <<<<<<<<<<<<<< - * self._items.append(_Pair.__new__(_Pair, key, value)) - * - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict._add", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":307 - * self._items.append(_Pair.__new__(_Pair, key, value)) - * - * cdef _replace(self, str key, value): # <<<<<<<<<<<<<< - * self._remove(key, 0) - * self._items.append(_Pair.__new__(_Pair, key, value)) - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_9MultiDict__replace(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_replace", 0); - - /* "aiohttp/_multidict.pyx":308 - * - * cdef _replace(self, str key, value): - * self._remove(key, 0) # <<<<<<<<<<<<<< - * self._items.append(_Pair.__new__(_Pair, key, value)) - * - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_remove(__pyx_v_self, __pyx_v_key, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":309 - * cdef _replace(self, str key, value): - * self._remove(key, 0) - * self._items.append(_Pair.__new__(_Pair, key, value)) # <<<<<<<<<<<<<< - * - * def add(self, key, value): - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "append"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 309; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 309; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_key); - __Pyx_GIVEREF(__pyx_v_key); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_key); - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value); - __pyx_t_2 = __pyx_tp_new_7aiohttp_10_multidict__Pair(((PyTypeObject *)__pyx_ptype_7aiohttp_10_multidict__Pair), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 309; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = __Pyx_PyList_Append(__pyx_v_self->__pyx_base._items, __pyx_t_2); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 309; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":307 - * self._items.append(_Pair.__new__(_Pair, key, value)) - * - * cdef _replace(self, str key, value): # <<<<<<<<<<<<<< - * self._remove(key, 0) - * self._items.append(_Pair.__new__(_Pair, key, value)) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict._replace", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":311 - * self._items.append(_Pair.__new__(_Pair, key, value)) - * - * def add(self, key, value): # <<<<<<<<<<<<<< - * """Add the key and value, not overwriting any previous value.""" - * self._add(self._upper(key), value) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_3add(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_9MultiDict_2add[] = "Add the key and value, not overwriting any previous value."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_3add(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_key = 0; - PyObject *__pyx_v_value = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("add (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_key,&__pyx_n_s_value,0}; - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_key)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_value)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("add", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "add") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_key = values[0]; - __pyx_v_value = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("add", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 311; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.add", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_2add(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self), __pyx_v_key, __pyx_v_value); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_2add(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("add", 0); - - /* "aiohttp/_multidict.pyx":313 - * def add(self, key, value): - * """Add the key and value, not overwriting any previous value.""" - * self._add(self._upper(key), value) # <<<<<<<<<<<<<< - * - * def copy(self): - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._upper(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_add(__pyx_v_self, ((PyObject*)__pyx_t_1), __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":311 - * self._items.append(_Pair.__new__(_Pair, key, value)) - * - * def add(self, key, value): # <<<<<<<<<<<<<< - * """Add the key and value, not overwriting any previous value.""" - * self._add(self._upper(key), value) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.add", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":315 - * self._add(self._upper(key), value) - * - * def copy(self): # <<<<<<<<<<<<<< - * """Return a copy of itself.""" - * cls = self.__class__ - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_5copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_9MultiDict_4copy[] = "Return a copy of itself."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_5copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("copy (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_4copy(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_4copy(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self) { - PyObject *__pyx_v_cls = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("copy", 0); - - /* "aiohttp/_multidict.pyx":317 - * def copy(self): - * """Return a copy of itself.""" - * cls = self.__class__ # <<<<<<<<<<<<<< - * return cls(self._items) - * - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":318 - * """Return a copy of itself.""" - * cls = self.__class__ - * return cls(self._items) # <<<<<<<<<<<<<< - * - * def extend(self, *args, **kwargs): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_cls); - __pyx_t_2 = __pyx_v_cls; __pyx_t_3 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - if (!__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_self->__pyx_base._items); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - } else { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; - __Pyx_INCREF(__pyx_v_self->__pyx_base._items); - __Pyx_GIVEREF(__pyx_v_self->__pyx_base._items); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v_self->__pyx_base._items); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":315 - * self._add(self._upper(key), value) - * - * def copy(self): # <<<<<<<<<<<<<< - * """Return a copy of itself.""" - * cls = self.__class__ - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_cls); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":320 - * return cls(self._items) - * - * def extend(self, *args, **kwargs): # <<<<<<<<<<<<<< - * """Extend current MultiDict with more values. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_7extend(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_9MultiDict_6extend[] = "Extend current MultiDict with more values.\n\n This method must be used instead of update.\n "; -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_7extend(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_args = 0; - PyObject *__pyx_v_kwargs = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("extend (wrapper)", 0); - if (unlikely(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "extend", 1))) return NULL; - __pyx_v_kwargs = (__pyx_kwds) ? PyDict_Copy(__pyx_kwds) : PyDict_New(); if (unlikely(!__pyx_v_kwargs)) return NULL; - __Pyx_GOTREF(__pyx_v_kwargs); - __Pyx_INCREF(__pyx_args); - __pyx_v_args = __pyx_args; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_6extend(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self), __pyx_v_args, __pyx_v_kwargs); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_args); - __Pyx_XDECREF(__pyx_v_kwargs); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_6extend(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("extend", 0); - - /* "aiohttp/_multidict.pyx":325 - * This method must be used instead of update. - * """ - * self._extend(args, kwargs, "extend", 1) # <<<<<<<<<<<<<< - * - * def clear(self): - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_extend(__pyx_v_self, __pyx_v_args, __pyx_v_kwargs, __pyx_n_s_extend, 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":320 - * return cls(self._items) - * - * def extend(self, *args, **kwargs): # <<<<<<<<<<<<<< - * """Extend current MultiDict with more values. - * - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.extend", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":327 - * self._extend(args, kwargs, "extend", 1) - * - * def clear(self): # <<<<<<<<<<<<<< - * """Remove all items from MultiDict""" - * self._items.clear() - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_9clear(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_9MultiDict_8clear[] = "Remove all items from MultiDict"; -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_9clear(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("clear (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_8clear(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_8clear(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("clear", 0); - - /* "aiohttp/_multidict.pyx":329 - * def clear(self): - * """Remove all items from MultiDict""" - * self._items.clear() # <<<<<<<<<<<<<< - * - * # MutableMapping interface # - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->__pyx_base._items, __pyx_n_s_clear); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - if (__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":327 - * self._extend(args, kwargs, "extend", 1) - * - * def clear(self): # <<<<<<<<<<<<<< - * """Remove all items from MultiDict""" - * self._items.clear() - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.clear", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":333 - * # MutableMapping interface # - * - * def __setitem__(self, key, value): # <<<<<<<<<<<<<< - * self._replace(self._upper(key), value) - * - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_9MultiDict_11__setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_9MultiDict_11__setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_10__setitem__(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self), ((PyObject *)__pyx_v_key), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_9MultiDict_10__setitem__(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setitem__", 0); - - /* "aiohttp/_multidict.pyx":334 - * - * def __setitem__(self, key, value): - * self._replace(self._upper(key), value) # <<<<<<<<<<<<<< - * - * def __delitem__(self, key): - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._upper(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_replace(__pyx_v_self, ((PyObject*)__pyx_t_1), __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":333 - * # MutableMapping interface # - * - * def __setitem__(self, key, value): # <<<<<<<<<<<<<< - * self._replace(self._upper(key), value) - * - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":336 - * self._replace(self._upper(key), value) - * - * def __delitem__(self, key): # <<<<<<<<<<<<<< - * self._remove(self._upper(key), True) - * - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_9MultiDict_13__delitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_9MultiDict_13__delitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__delitem__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_12__delitem__(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self), ((PyObject *)__pyx_v_key)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_9MultiDict_12__delitem__(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__delitem__", 0); - - /* "aiohttp/_multidict.pyx":337 - * - * def __delitem__(self, key): - * self._remove(self._upper(key), True) # <<<<<<<<<<<<<< - * - * cdef _remove(self, str key, int raise_key_error): - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._upper(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_remove(__pyx_v_self, ((PyObject*)__pyx_t_1), 1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":336 - * self._replace(self._upper(key), value) - * - * def __delitem__(self, key): # <<<<<<<<<<<<<< - * self._remove(self._upper(key), True) - * - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.__delitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":339 - * self._remove(self._upper(key), True) - * - * cdef _remove(self, str key, int raise_key_error): # <<<<<<<<<<<<<< - * cdef _Pair item - * cdef int found - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_9MultiDict__remove(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, int __pyx_v_raise_key_error) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - int __pyx_v_found; - Py_ssize_t __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_remove", 0); - - /* "aiohttp/_multidict.pyx":342 - * cdef _Pair item - * cdef int found - * found = False # <<<<<<<<<<<<<< - * for i in range(len(self._items) - 1, -1, -1): - * item = <_Pair>self._items[i] - */ - __pyx_v_found = 0; - - /* "aiohttp/_multidict.pyx":343 - * cdef int found - * found = False - * for i in range(len(self._items) - 1, -1, -1): # <<<<<<<<<<<<<< - * item = <_Pair>self._items[i] - * if item._key == key: - */ - __pyx_t_1 = __pyx_v_self->__pyx_base._items; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = PyList_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - for (__pyx_t_3 = (__pyx_t_2 - 1); __pyx_t_3 > -1L; __pyx_t_3-=1) { - __pyx_v_i = __pyx_t_3; - - /* "aiohttp/_multidict.pyx":344 - * found = False - * for i in range(len(self._items) - 1, -1, -1): - * item = <_Pair>self._items[i] # <<<<<<<<<<<<<< - * if item._key == key: - * del self._items[i] - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 344; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_self->__pyx_base._items, __pyx_v_i, Py_ssize_t, 1, PyInt_FromSsize_t, 1, 1, 1); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 344; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __pyx_t_1; - __Pyx_INCREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":345 - * for i in range(len(self._items) - 1, -1, -1): - * item = <_Pair>self._items[i] - * if item._key == key: # <<<<<<<<<<<<<< - * del self._items[i] - * found = True - */ - __pyx_t_5 = (__Pyx_PyString_Equals(__pyx_v_item->_key, __pyx_v_key, Py_EQ)); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 345; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_5) { - - /* "aiohttp/_multidict.pyx":346 - * item = <_Pair>self._items[i] - * if item._key == key: - * del self._items[i] # <<<<<<<<<<<<<< - * found = True - * if not found and raise_key_error: - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 346; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - if (__Pyx_DelItemInt(__pyx_v_self->__pyx_base._items, __pyx_v_i, Py_ssize_t, 1, PyInt_FromSsize_t, 1, 1, 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 346; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":347 - * if item._key == key: - * del self._items[i] - * found = True # <<<<<<<<<<<<<< - * if not found and raise_key_error: - * raise KeyError(key) - */ - __pyx_v_found = 1; - - /* "aiohttp/_multidict.pyx":345 - * for i in range(len(self._items) - 1, -1, -1): - * item = <_Pair>self._items[i] - * if item._key == key: # <<<<<<<<<<<<<< - * del self._items[i] - * found = True - */ - } - } - - /* "aiohttp/_multidict.pyx":348 - * del self._items[i] - * found = True - * if not found and raise_key_error: # <<<<<<<<<<<<<< - * raise KeyError(key) - * - */ - __pyx_t_6 = ((!(__pyx_v_found != 0)) != 0); - if (__pyx_t_6) { - } else { - __pyx_t_5 = __pyx_t_6; - goto __pyx_L7_bool_binop_done; - } - __pyx_t_6 = (__pyx_v_raise_key_error != 0); - __pyx_t_5 = __pyx_t_6; - __pyx_L7_bool_binop_done:; - if (__pyx_t_5) { - - /* "aiohttp/_multidict.pyx":349 - * found = True - * if not found and raise_key_error: - * raise KeyError(key) # <<<<<<<<<<<<<< - * - * def setdefault(self, key, default=None): - */ - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_key); - __Pyx_GIVEREF(__pyx_v_key); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_key); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_KeyError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 349; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":348 - * del self._items[i] - * found = True - * if not found and raise_key_error: # <<<<<<<<<<<<<< - * raise KeyError(key) - * - */ - } - - /* "aiohttp/_multidict.pyx":339 - * self._remove(self._upper(key), True) - * - * cdef _remove(self, str key, int raise_key_error): # <<<<<<<<<<<<<< - * cdef _Pair item - * cdef int found - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict._remove", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":351 - * raise KeyError(key) - * - * def setdefault(self, key, default=None): # <<<<<<<<<<<<<< - * """Return value for key, set value to default if key is not present.""" - * cdef str skey - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_15setdefault(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_9MultiDict_14setdefault[] = "Return value for key, set value to default if key is not present."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_15setdefault(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_key = 0; - PyObject *__pyx_v_default = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("setdefault (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_key,&__pyx_n_s_default,0}; - PyObject* values[2] = {0,0}; - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_key)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_default); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "setdefault") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_key = values[0]; - __pyx_v_default = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("setdefault", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.setdefault", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_14setdefault(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self), __pyx_v_key, __pyx_v_default); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_14setdefault(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default) { - PyObject *__pyx_v_skey = 0; - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setdefault", 0); - - /* "aiohttp/_multidict.pyx":355 - * cdef str skey - * cdef _Pair item - * skey = self._upper(key) # <<<<<<<<<<<<<< - * for i in self._items: - * item = <_Pair>i - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._upper(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_skey = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":356 - * cdef _Pair item - * skey = self._upper(key) - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == skey: - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->__pyx_base._items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":357 - * skey = self._upper(key) - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * if item._key == skey: - * return item._value - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":358 - * for i in self._items: - * item = <_Pair>i - * if item._key == skey: # <<<<<<<<<<<<<< - * return item._value - * self._add(skey, default) - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_item->_key, __pyx_v_skey, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 358; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":359 - * item = <_Pair>i - * if item._key == skey: - * return item._value # <<<<<<<<<<<<<< - * self._add(skey, default) - * return default - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_item->_value); - __pyx_r = __pyx_v_item->_value; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":358 - * for i in self._items: - * item = <_Pair>i - * if item._key == skey: # <<<<<<<<<<<<<< - * return item._value - * self._add(skey, default) - */ - } - - /* "aiohttp/_multidict.pyx":356 - * cdef _Pair item - * skey = self._upper(key) - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == skey: - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":360 - * if item._key == skey: - * return item._value - * self._add(skey, default) # <<<<<<<<<<<<<< - * return default - * - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_add(__pyx_v_self, __pyx_v_skey, __pyx_v_default); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":361 - * return item._value - * self._add(skey, default) - * return default # <<<<<<<<<<<<<< - * - * def pop(self, key, default=_marker): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_default); - __pyx_r = __pyx_v_default; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":351 - * raise KeyError(key) - * - * def setdefault(self, key, default=None): # <<<<<<<<<<<<<< - * """Return value for key, set value to default if key is not present.""" - * cdef str skey - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.setdefault", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_skey); - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":363 - * return default - * - * def pop(self, key, default=_marker): # <<<<<<<<<<<<<< - * """Remove specified key and return the corresponding value. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_17pop(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_9MultiDict_16pop[] = "Remove specified key and return the corresponding value.\n\n If key is not found, d is returned if given, otherwise\n KeyError is raised.\n\n "; -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_17pop(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_key = 0; - PyObject *__pyx_v_default = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("pop (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_key,&__pyx_n_s_default,0}; - PyObject* values[2] = {0,0}; - values[1] = __pyx_k__6; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_key)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_default); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "pop") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_key = values[0]; - __pyx_v_default = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("pop", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.pop", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_16pop(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self), __pyx_v_key, __pyx_v_default); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_16pop(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_default) { - int __pyx_v_found; - CYTHON_UNUSED PyObject *__pyx_v_skey = 0; - PyObject *__pyx_v_value = 0; - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - Py_ssize_t __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("pop", 0); - - /* "aiohttp/_multidict.pyx":374 - * cdef object value - * cdef _Pair item - * skey = self._upper(key) # <<<<<<<<<<<<<< - * value = None - * found = False - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._upper(((struct __pyx_obj_7aiohttp_10_multidict__Base *)__pyx_v_self), __pyx_v_key); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_skey = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":375 - * cdef _Pair item - * skey = self._upper(key) - * value = None # <<<<<<<<<<<<<< - * found = False - * for i in range(len(self._items) - 1, -1, -1): - */ - __Pyx_INCREF(Py_None); - __pyx_v_value = Py_None; - - /* "aiohttp/_multidict.pyx":376 - * skey = self._upper(key) - * value = None - * found = False # <<<<<<<<<<<<<< - * for i in range(len(self._items) - 1, -1, -1): - * item = <_Pair>self._items[i] - */ - __pyx_v_found = 0; - - /* "aiohttp/_multidict.pyx":377 - * value = None - * found = False - * for i in range(len(self._items) - 1, -1, -1): # <<<<<<<<<<<<<< - * item = <_Pair>self._items[i] - * if item._key == key: - */ - __pyx_t_1 = __pyx_v_self->__pyx_base._items; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = PyList_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - for (__pyx_t_3 = (__pyx_t_2 - 1); __pyx_t_3 > -1L; __pyx_t_3-=1) { - __pyx_v_i = __pyx_t_3; - - /* "aiohttp/_multidict.pyx":378 - * found = False - * for i in range(len(self._items) - 1, -1, -1): - * item = <_Pair>self._items[i] # <<<<<<<<<<<<<< - * if item._key == key: - * value = item._value - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_self->__pyx_base._items, __pyx_v_i, Py_ssize_t, 1, PyInt_FromSsize_t, 1, 1, 1); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __pyx_t_1; - __Pyx_INCREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":379 - * for i in range(len(self._items) - 1, -1, -1): - * item = <_Pair>self._items[i] - * if item._key == key: # <<<<<<<<<<<<<< - * value = item._value - * del self._items[i] - */ - __pyx_t_4 = PyObject_RichCompare(__pyx_v_item->_key, __pyx_v_key, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_5) { - - /* "aiohttp/_multidict.pyx":380 - * item = <_Pair>self._items[i] - * if item._key == key: - * value = item._value # <<<<<<<<<<<<<< - * del self._items[i] - * found = True - */ - __pyx_t_4 = __pyx_v_item->_value; - __Pyx_INCREF(__pyx_t_4); - __Pyx_DECREF_SET(__pyx_v_value, __pyx_t_4); - __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":381 - * if item._key == key: - * value = item._value - * del self._items[i] # <<<<<<<<<<<<<< - * found = True - * if not found: - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - if (__Pyx_DelItemInt(__pyx_v_self->__pyx_base._items, __pyx_v_i, Py_ssize_t, 1, PyInt_FromSsize_t, 1, 1, 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":382 - * value = item._value - * del self._items[i] - * found = True # <<<<<<<<<<<<<< - * if not found: - * if default is self.marker: - */ - __pyx_v_found = 1; - - /* "aiohttp/_multidict.pyx":379 - * for i in range(len(self._items) - 1, -1, -1): - * item = <_Pair>self._items[i] - * if item._key == key: # <<<<<<<<<<<<<< - * value = item._value - * del self._items[i] - */ - } - } - - /* "aiohttp/_multidict.pyx":383 - * del self._items[i] - * found = True - * if not found: # <<<<<<<<<<<<<< - * if default is self.marker: - * raise KeyError(key) - */ - __pyx_t_5 = ((!(__pyx_v_found != 0)) != 0); - if (__pyx_t_5) { - - /* "aiohttp/_multidict.pyx":384 - * found = True - * if not found: - * if default is self.marker: # <<<<<<<<<<<<<< - * raise KeyError(key) - * else: - */ - __pyx_t_5 = (__pyx_v_default == __pyx_v_self->__pyx_base.marker); - __pyx_t_6 = (__pyx_t_5 != 0); - if (__pyx_t_6) { - - /* "aiohttp/_multidict.pyx":385 - * if not found: - * if default is self.marker: - * raise KeyError(key) # <<<<<<<<<<<<<< - * else: - * return default - */ - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_key); - __Pyx_GIVEREF(__pyx_v_key); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_key); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_KeyError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":384 - * found = True - * if not found: - * if default is self.marker: # <<<<<<<<<<<<<< - * raise KeyError(key) - * else: - */ - } - - /* "aiohttp/_multidict.pyx":387 - * raise KeyError(key) - * else: - * return default # <<<<<<<<<<<<<< - * else: - * return value - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_default); - __pyx_r = __pyx_v_default; - goto __pyx_L0; - } - - /* "aiohttp/_multidict.pyx":383 - * del self._items[i] - * found = True - * if not found: # <<<<<<<<<<<<<< - * if default is self.marker: - * raise KeyError(key) - */ - } - - /* "aiohttp/_multidict.pyx":389 - * return default - * else: - * return value # <<<<<<<<<<<<<< - * - * def popitem(self): - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_value); - __pyx_r = __pyx_v_value; - goto __pyx_L0; - } - - /* "aiohttp/_multidict.pyx":363 - * return default - * - * def pop(self, key, default=_marker): # <<<<<<<<<<<<<< - * """Remove specified key and return the corresponding value. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.pop", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_skey); - __Pyx_XDECREF(__pyx_v_value); - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":391 - * return value - * - * def popitem(self): # <<<<<<<<<<<<<< - * """Remove and return an arbitrary (key, value) pair.""" - * cdef _Pair item - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_19popitem(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_9MultiDict_18popitem[] = "Remove and return an arbitrary (key, value) pair."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_19popitem(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("popitem (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_18popitem(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_18popitem(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("popitem", 0); - - /* "aiohttp/_multidict.pyx":394 - * """Remove and return an arbitrary (key, value) pair.""" - * cdef _Pair item - * if self._items: # <<<<<<<<<<<<<< - * item = <_Pair>self._items.pop(0) - * return (item._key, item._value) - */ - __pyx_t_1 = (__pyx_v_self->__pyx_base._items != Py_None) && (PyList_GET_SIZE(__pyx_v_self->__pyx_base._items) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":395 - * cdef _Pair item - * if self._items: - * item = <_Pair>self._items.pop(0) # <<<<<<<<<<<<<< - * return (item._key, item._value) - * else: - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "pop"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = __Pyx_PyList_PopIndex(__pyx_v_self->__pyx_base._items, __pyx_int_0, 0, 1, Py_ssize_t, PyInt_FromSsize_t); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_item = ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":396 - * if self._items: - * item = <_Pair>self._items.pop(0) - * return (item._key, item._value) # <<<<<<<<<<<<<< - * else: - * raise KeyError("empty multidict") - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_item->_key); - __Pyx_GIVEREF(__pyx_v_item->_key); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_item->_key); - __Pyx_INCREF(__pyx_v_item->_value); - __Pyx_GIVEREF(__pyx_v_item->_value); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_item->_value); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":394 - * """Remove and return an arbitrary (key, value) pair.""" - * cdef _Pair item - * if self._items: # <<<<<<<<<<<<<< - * item = <_Pair>self._items.pop(0) - * return (item._key, item._value) - */ - } - - /* "aiohttp/_multidict.pyx":398 - * return (item._key, item._value) - * else: - * raise KeyError("empty multidict") # <<<<<<<<<<<<<< - * - * def update(self, *args, **kwargs): - */ - /*else*/ { - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_KeyError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - - /* "aiohttp/_multidict.pyx":391 - * return value - * - * def popitem(self): # <<<<<<<<<<<<<< - * """Remove and return an arbitrary (key, value) pair.""" - * cdef _Pair item - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.popitem", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":400 - * raise KeyError("empty multidict") - * - * def update(self, *args, **kwargs): # <<<<<<<<<<<<<< - * """Update the dictionary from *other*, overwriting existing keys.""" - * self._extend(args, kwargs, "update", 0) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_21update(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_9MultiDict_20update[] = "Update the dictionary from *other*, overwriting existing keys."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_9MultiDict_21update(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_args = 0; - PyObject *__pyx_v_kwargs = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("update (wrapper)", 0); - if (unlikely(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "update", 1))) return NULL; - __pyx_v_kwargs = (__pyx_kwds) ? PyDict_Copy(__pyx_kwds) : PyDict_New(); if (unlikely(!__pyx_v_kwargs)) return NULL; - __Pyx_GOTREF(__pyx_v_kwargs); - __Pyx_INCREF(__pyx_args); - __pyx_v_args = __pyx_args; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9MultiDict_20update(((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)__pyx_v_self), __pyx_v_args, __pyx_v_kwargs); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_args); - __Pyx_XDECREF(__pyx_v_kwargs); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9MultiDict_20update(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("update", 0); - - /* "aiohttp/_multidict.pyx":402 - * def update(self, *args, **kwargs): - * """Update the dictionary from *other*, overwriting existing keys.""" - * self._extend(args, kwargs, "update", 0) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict *)__pyx_v_self->__pyx_base.__pyx_vtab)->_extend(__pyx_v_self, __pyx_v_args, __pyx_v_kwargs, __pyx_n_s_update, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":400 - * raise KeyError("empty multidict") - * - * def update(self, *args, **kwargs): # <<<<<<<<<<<<<< - * """Update the dictionary from *other*, overwriting existing keys.""" - * self._extend(args, kwargs, "update", 0) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict.MultiDict.update", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":411 - * """An ordered dictionary that can have multiple values for each key.""" - * - * cdef str _upper(self, s): # <<<<<<<<<<<<<< - * if type(s) is self._upstr: - * return <str>s - */ - -static PyObject *__pyx_f_7aiohttp_10_multidict_11CIMultiDict__upper(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDict *__pyx_v_self, PyObject *__pyx_v_s) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_upper", 0); - - /* "aiohttp/_multidict.pyx":412 - * - * cdef str _upper(self, s): - * if type(s) is self._upstr: # <<<<<<<<<<<<<< - * return <str>s - * return s.upper() - */ - __pyx_t_1 = (((PyObject *)Py_TYPE(__pyx_v_s)) == __pyx_v_self->__pyx_base.__pyx_base._upstr); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":413 - * cdef str _upper(self, s): - * if type(s) is self._upstr: - * return <str>s # <<<<<<<<<<<<<< - * return s.upper() - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject*)__pyx_v_s)); - __pyx_r = ((PyObject*)__pyx_v_s); - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":412 - * - * cdef str _upper(self, s): - * if type(s) is self._upstr: # <<<<<<<<<<<<<< - * return <str>s - * return s.upper() - */ - } - - /* "aiohttp/_multidict.pyx":414 - * if type(s) is self._upstr: - * return <str>s - * return s.upper() # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_s, __pyx_n_s_upper); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - if (__pyx_t_5) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else { - __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(PyString_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":411 - * """An ordered dictionary that can have multiple values for each key.""" - * - * cdef str _upper(self, s): # <<<<<<<<<<<<<< - * if type(s) is self._upstr: - * return <str>s - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("aiohttp._multidict.CIMultiDict._upper", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":425 - * cdef list _items - * - * def __cinit__(self, list items): # <<<<<<<<<<<<<< - * self._items = items - * - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_9_ViewBase_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_9_ViewBase_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_items = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_items,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_items)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_items = ((PyObject*)values[0]); - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._ViewBase.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_items), (&PyList_Type), 1, "items", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9_ViewBase___cinit__(((struct __pyx_obj_7aiohttp_10_multidict__ViewBase *)__pyx_v_self), __pyx_v_items); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_9_ViewBase___cinit__(struct __pyx_obj_7aiohttp_10_multidict__ViewBase *__pyx_v_self, PyObject *__pyx_v_items) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "aiohttp/_multidict.pyx":426 - * - * def __cinit__(self, list items): - * self._items = items # <<<<<<<<<<<<<< - * - * def __len__(self): - */ - __Pyx_INCREF(__pyx_v_items); - __Pyx_GIVEREF(__pyx_v_items); - __Pyx_GOTREF(__pyx_v_self->_items); - __Pyx_DECREF(__pyx_v_self->_items); - __pyx_v_self->_items = __pyx_v_items; - - /* "aiohttp/_multidict.pyx":425 - * cdef list _items - * - * def __cinit__(self, list items): # <<<<<<<<<<<<<< - * self._items = items - * - */ - - /* function exit code */ - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":428 - * self._items = items - * - * def __len__(self): # <<<<<<<<<<<<<< - * return len(self._items) - * - */ - -/* Python wrapper */ -static Py_ssize_t __pyx_pw_7aiohttp_10_multidict_9_ViewBase_3__len__(PyObject *__pyx_v_self); /*proto*/ -static Py_ssize_t __pyx_pw_7aiohttp_10_multidict_9_ViewBase_3__len__(PyObject *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9_ViewBase_2__len__(((struct __pyx_obj_7aiohttp_10_multidict__ViewBase *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static Py_ssize_t __pyx_pf_7aiohttp_10_multidict_9_ViewBase_2__len__(struct __pyx_obj_7aiohttp_10_multidict__ViewBase *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__len__", 0); - - /* "aiohttp/_multidict.pyx":429 - * - * def __len__(self): - * return len(self._items) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __pyx_v_self->_items; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = PyList_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":428 - * self._items = items - * - * def __len__(self): # <<<<<<<<<<<<<< - * return len(self._items) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict._ViewBase.__len__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":434 - * cdef class _ViewBaseSet(_ViewBase): - * - * def __richcmp__(self, other, op): # <<<<<<<<<<<<<< - * if op == 0: # < - * if not isinstance(other, Set): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_1__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, int __pyx_arg_op); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_1__richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, int __pyx_arg_op) { - PyObject *__pyx_v_op = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__richcmp__ (wrapper)", 0); - __pyx_v_op = __Pyx_PyInt_From_int(__pyx_arg_op); if (unlikely(!__pyx_v_op)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __Pyx_GOTREF(__pyx_v_op); - goto __pyx_L4_argument_unpacking_done; - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._ViewBaseSet.__richcmp__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet___richcmp__(((PyObject *)__pyx_v_self), ((PyObject *)__pyx_v_other), ((PyObject *)__pyx_v_op)); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_op); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet___richcmp__(PyObject *__pyx_v_self, PyObject *__pyx_v_other, PyObject *__pyx_v_op) { - PyObject *__pyx_v_elem = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - Py_ssize_t __pyx_t_4; - Py_ssize_t __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *(*__pyx_t_7)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__richcmp__", 0); - - /* "aiohttp/_multidict.pyx":435 - * - * def __richcmp__(self, other, op): - * if op == 0: # < # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - __pyx_t_1 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_0, 0, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":436 - * def __richcmp__(self, other, op): - * if op == 0: # < - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * return len(self) < len(other) and self <= other - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Set); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":437 - * if op == 0: # < - * if not isinstance(other, Set): - * return NotImplemented # <<<<<<<<<<<<<< - * return len(self) < len(other) and self <= other - * elif op == 1: # <= - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":436 - * def __richcmp__(self, other, op): - * if op == 0: # < - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * return len(self) < len(other) and self <= other - */ - } - - /* "aiohttp/_multidict.pyx":438 - * if not isinstance(other, Set): - * return NotImplemented - * return len(self) < len(other) and self <= other # <<<<<<<<<<<<<< - * elif op == 1: # <= - * if not isinstance(other, Set): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = PyObject_Length(__pyx_v_self); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyObject_Length(__pyx_v_other); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = (__pyx_t_4 < __pyx_t_5); - if (__pyx_t_3) { - } else { - __pyx_t_6 = __Pyx_PyBool_FromLong(__pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L5_bool_binop_done; - } - __pyx_t_6 = PyObject_RichCompare(__pyx_v_self, __pyx_v_other, Py_LE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_INCREF(__pyx_t_6); - __pyx_t_1 = __pyx_t_6; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_L5_bool_binop_done:; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":435 - * - * def __richcmp__(self, other, op): - * if op == 0: # < # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - } - - /* "aiohttp/_multidict.pyx":439 - * return NotImplemented - * return len(self) < len(other) and self <= other - * elif op == 1: # <= # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - __pyx_t_1 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 439; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":440 - * return len(self) < len(other) and self <= other - * elif op == 1: # <= - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * if len(self) > len(other): - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Set); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = ((!(__pyx_t_3 != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":441 - * elif op == 1: # <= - * if not isinstance(other, Set): - * return NotImplemented # <<<<<<<<<<<<<< - * if len(self) > len(other): - * return False - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":440 - * return len(self) < len(other) and self <= other - * elif op == 1: # <= - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * if len(self) > len(other): - */ - } - - /* "aiohttp/_multidict.pyx":442 - * if not isinstance(other, Set): - * return NotImplemented - * if len(self) > len(other): # <<<<<<<<<<<<<< - * return False - * for elem in self: - */ - __pyx_t_5 = PyObject_Length(__pyx_v_self); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyObject_Length(__pyx_v_other); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = ((__pyx_t_5 > __pyx_t_4) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":443 - * return NotImplemented - * if len(self) > len(other): - * return False # <<<<<<<<<<<<<< - * for elem in self: - * if elem not in other: - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":442 - * if not isinstance(other, Set): - * return NotImplemented - * if len(self) > len(other): # <<<<<<<<<<<<<< - * return False - * for elem in self: - */ - } - - /* "aiohttp/_multidict.pyx":444 - * if len(self) > len(other): - * return False - * for elem in self: # <<<<<<<<<<<<<< - * if elem not in other: - * return False - */ - if (likely(PyList_CheckExact(__pyx_v_self)) || PyTuple_CheckExact(__pyx_v_self)) { - __pyx_t_1 = __pyx_v_self; __Pyx_INCREF(__pyx_t_1); __pyx_t_4 = 0; - __pyx_t_7 = NULL; - } else { - __pyx_t_4 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - for (;;) { - if (likely(!__pyx_t_7)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_4 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_6 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_4); __Pyx_INCREF(__pyx_t_6); __pyx_t_4++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_6 = PySequence_ITEM(__pyx_t_1, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - #endif - } else { - if (__pyx_t_4 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_6 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_4); __Pyx_INCREF(__pyx_t_6); __pyx_t_4++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_6 = PySequence_ITEM(__pyx_t_1, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - #endif - } - } else { - __pyx_t_6 = __pyx_t_7(__pyx_t_1); - if (unlikely(!__pyx_t_6)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_6); - } - __Pyx_XDECREF_SET(__pyx_v_elem, __pyx_t_6); - __pyx_t_6 = 0; - - /* "aiohttp/_multidict.pyx":445 - * return False - * for elem in self: - * if elem not in other: # <<<<<<<<<<<<<< - * return False - * return True - */ - __pyx_t_2 = (__Pyx_PySequence_ContainsTF(__pyx_v_elem, __pyx_v_other, Py_NE)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":446 - * for elem in self: - * if elem not in other: - * return False # <<<<<<<<<<<<<< - * return True - * elif op == 2: # == - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":445 - * return False - * for elem in self: - * if elem not in other: # <<<<<<<<<<<<<< - * return False - * return True - */ - } - - /* "aiohttp/_multidict.pyx":444 - * if len(self) > len(other): - * return False - * for elem in self: # <<<<<<<<<<<<<< - * if elem not in other: - * return False - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":447 - * if elem not in other: - * return False - * return True # <<<<<<<<<<<<<< - * elif op == 2: # == - * if not isinstance(other, Set): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_True); - __pyx_r = Py_True; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":439 - * return NotImplemented - * return len(self) < len(other) and self <= other - * elif op == 1: # <= # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - } - - /* "aiohttp/_multidict.pyx":448 - * return False - * return True - * elif op == 2: # == # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - __pyx_t_1 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_2, 2, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":449 - * return True - * elif op == 2: # == - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * return len(self) == len(other) and self <= other - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Set); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 449; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = ((!(__pyx_t_3 != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":450 - * elif op == 2: # == - * if not isinstance(other, Set): - * return NotImplemented # <<<<<<<<<<<<<< - * return len(self) == len(other) and self <= other - * elif op == 3: # != - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":449 - * return True - * elif op == 2: # == - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * return len(self) == len(other) and self <= other - */ - } - - /* "aiohttp/_multidict.pyx":451 - * if not isinstance(other, Set): - * return NotImplemented - * return len(self) == len(other) and self <= other # <<<<<<<<<<<<<< - * elif op == 3: # != - * return not self == other - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = PyObject_Length(__pyx_v_self); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyObject_Length(__pyx_v_other); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_4 == __pyx_t_5); - if (__pyx_t_2) { - } else { - __pyx_t_6 = __Pyx_PyBool_FromLong(__pyx_t_2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L13_bool_binop_done; - } - __pyx_t_6 = PyObject_RichCompare(__pyx_v_self, __pyx_v_other, Py_LE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_INCREF(__pyx_t_6); - __pyx_t_1 = __pyx_t_6; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_L13_bool_binop_done:; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":448 - * return False - * return True - * elif op == 2: # == # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - } - - /* "aiohttp/_multidict.pyx":452 - * return NotImplemented - * return len(self) == len(other) and self <= other - * elif op == 3: # != # <<<<<<<<<<<<<< - * return not self == other - * elif op == 4: # > - */ - __pyx_t_1 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_3, 3, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":453 - * return len(self) == len(other) and self <= other - * elif op == 3: # != - * return not self == other # <<<<<<<<<<<<<< - * elif op == 4: # > - * if not isinstance(other, Set): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyObject_RichCompare(__pyx_v_self, __pyx_v_other, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyBool_FromLong((!__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":452 - * return NotImplemented - * return len(self) == len(other) and self <= other - * elif op == 3: # != # <<<<<<<<<<<<<< - * return not self == other - * elif op == 4: # > - */ - } - - /* "aiohttp/_multidict.pyx":454 - * elif op == 3: # != - * return not self == other - * elif op == 4: # > # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - __pyx_t_1 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_4, 4, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":455 - * return not self == other - * elif op == 4: # > - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * return len(self) > len(other) and self >= other - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Set); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 455; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":456 - * elif op == 4: # > - * if not isinstance(other, Set): - * return NotImplemented # <<<<<<<<<<<<<< - * return len(self) > len(other) and self >= other - * elif op == 5: # >= - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":455 - * return not self == other - * elif op == 4: # > - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * return len(self) > len(other) and self >= other - */ - } - - /* "aiohttp/_multidict.pyx":457 - * if not isinstance(other, Set): - * return NotImplemented - * return len(self) > len(other) and self >= other # <<<<<<<<<<<<<< - * elif op == 5: # >= - * if not isinstance(other, Set): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = PyObject_Length(__pyx_v_self); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyObject_Length(__pyx_v_other); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = (__pyx_t_5 > __pyx_t_4); - if (__pyx_t_3) { - } else { - __pyx_t_6 = __Pyx_PyBool_FromLong(__pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L16_bool_binop_done; - } - __pyx_t_6 = PyObject_RichCompare(__pyx_v_self, __pyx_v_other, Py_GE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_INCREF(__pyx_t_6); - __pyx_t_1 = __pyx_t_6; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_L16_bool_binop_done:; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":454 - * elif op == 3: # != - * return not self == other - * elif op == 4: # > # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - } - - /* "aiohttp/_multidict.pyx":458 - * return NotImplemented - * return len(self) > len(other) and self >= other - * elif op == 5: # >= # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - __pyx_t_1 = __Pyx_PyInt_EqObjC(__pyx_v_op, __pyx_int_5, 5, 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 458; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 458; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":459 - * return len(self) > len(other) and self >= other - * elif op == 5: # >= - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * if len(self) < len(other): - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Set); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 459; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = ((!(__pyx_t_3 != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":460 - * elif op == 5: # >= - * if not isinstance(other, Set): - * return NotImplemented # <<<<<<<<<<<<<< - * if len(self) < len(other): - * return False - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":459 - * return len(self) > len(other) and self >= other - * elif op == 5: # >= - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * return NotImplemented - * if len(self) < len(other): - */ - } - - /* "aiohttp/_multidict.pyx":461 - * if not isinstance(other, Set): - * return NotImplemented - * if len(self) < len(other): # <<<<<<<<<<<<<< - * return False - * for elem in other: - */ - __pyx_t_4 = PyObject_Length(__pyx_v_self); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyObject_Length(__pyx_v_other); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 461; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = ((__pyx_t_4 < __pyx_t_5) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":462 - * return NotImplemented - * if len(self) < len(other): - * return False # <<<<<<<<<<<<<< - * for elem in other: - * if elem not in self: - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":461 - * if not isinstance(other, Set): - * return NotImplemented - * if len(self) < len(other): # <<<<<<<<<<<<<< - * return False - * for elem in other: - */ - } - - /* "aiohttp/_multidict.pyx":463 - * if len(self) < len(other): - * return False - * for elem in other: # <<<<<<<<<<<<<< - * if elem not in self: - * return False - */ - if (likely(PyList_CheckExact(__pyx_v_other)) || PyTuple_CheckExact(__pyx_v_other)) { - __pyx_t_1 = __pyx_v_other; __Pyx_INCREF(__pyx_t_1); __pyx_t_5 = 0; - __pyx_t_7 = NULL; - } else { - __pyx_t_5 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_other); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - for (;;) { - if (likely(!__pyx_t_7)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_6 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_5); __Pyx_INCREF(__pyx_t_6); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_6 = PySequence_ITEM(__pyx_t_1, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - #endif - } else { - if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_6 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_5); __Pyx_INCREF(__pyx_t_6); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_6 = PySequence_ITEM(__pyx_t_1, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - #endif - } - } else { - __pyx_t_6 = __pyx_t_7(__pyx_t_1); - if (unlikely(!__pyx_t_6)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 463; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_6); - } - __Pyx_XDECREF_SET(__pyx_v_elem, __pyx_t_6); - __pyx_t_6 = 0; - - /* "aiohttp/_multidict.pyx":464 - * return False - * for elem in other: - * if elem not in self: # <<<<<<<<<<<<<< - * return False - * return True - */ - __pyx_t_2 = (__Pyx_PySequence_ContainsTF(__pyx_v_elem, __pyx_v_self, Py_NE)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":465 - * for elem in other: - * if elem not in self: - * return False # <<<<<<<<<<<<<< - * return True - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":464 - * return False - * for elem in other: - * if elem not in self: # <<<<<<<<<<<<<< - * return False - * return True - */ - } - - /* "aiohttp/_multidict.pyx":463 - * if len(self) < len(other): - * return False - * for elem in other: # <<<<<<<<<<<<<< - * if elem not in self: - * return False - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":466 - * if elem not in self: - * return False - * return True # <<<<<<<<<<<<<< - * - * def __and__(self, other): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_True); - __pyx_r = Py_True; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":458 - * return NotImplemented - * return len(self) > len(other) and self >= other - * elif op == 5: # >= # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * return NotImplemented - */ - } - - /* "aiohttp/_multidict.pyx":434 - * cdef class _ViewBaseSet(_ViewBase): - * - * def __richcmp__(self, other, op): # <<<<<<<<<<<<<< - * if op == 0: # < - * if not isinstance(other, Set): - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._multidict._ViewBaseSet.__richcmp__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_elem); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":468 - * return True - * - * def __and__(self, other): # <<<<<<<<<<<<<< - * if not isinstance(other, Iterable): - * return NotImplemented - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_3__and__(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_3__and__(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__and__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_2__and__(((PyObject *)__pyx_v_self), ((PyObject *)__pyx_v_other)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_2__and__(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__and__", 0); - __Pyx_INCREF(__pyx_v_other); - - /* "aiohttp/_multidict.pyx":469 - * - * def __and__(self, other): - * if not isinstance(other, Iterable): # <<<<<<<<<<<<<< - * return NotImplemented - * if not isinstance(other, Set): - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Iterable); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":470 - * def __and__(self, other): - * if not isinstance(other, Iterable): - * return NotImplemented # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * other = set(other) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":469 - * - * def __and__(self, other): - * if not isinstance(other, Iterable): # <<<<<<<<<<<<<< - * return NotImplemented - * if not isinstance(other, Set): - */ - } - - /* "aiohttp/_multidict.pyx":471 - * if not isinstance(other, Iterable): - * return NotImplemented - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * other = set(other) - * return set(self) & other - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Set); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 471; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = ((!(__pyx_t_3 != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":472 - * return NotImplemented - * if not isinstance(other, Set): - * other = set(other) # <<<<<<<<<<<<<< - * return set(self) & other - * - */ - __pyx_t_1 = PySet_New(__pyx_v_other); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_other, __pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":471 - * if not isinstance(other, Iterable): - * return NotImplemented - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * other = set(other) - * return set(self) & other - */ - } - - /* "aiohttp/_multidict.pyx":473 - * if not isinstance(other, Set): - * other = set(other) - * return set(self) & other # <<<<<<<<<<<<<< - * - * def __or__(self, other): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PySet_New(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_And(__pyx_t_1, __pyx_v_other); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 473; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":468 - * return True - * - * def __and__(self, other): # <<<<<<<<<<<<<< - * if not isinstance(other, Iterable): - * return NotImplemented - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._multidict._ViewBaseSet.__and__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_other); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":475 - * return set(self) & other - * - * def __or__(self, other): # <<<<<<<<<<<<<< - * if not isinstance(other, Iterable): - * return NotImplemented - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_5__or__(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_5__or__(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__or__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_4__or__(((PyObject *)__pyx_v_self), ((PyObject *)__pyx_v_other)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_4__or__(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__or__", 0); - __Pyx_INCREF(__pyx_v_other); - - /* "aiohttp/_multidict.pyx":476 - * - * def __or__(self, other): - * if not isinstance(other, Iterable): # <<<<<<<<<<<<<< - * return NotImplemented - * if not isinstance(other, Set): - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Iterable); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":477 - * def __or__(self, other): - * if not isinstance(other, Iterable): - * return NotImplemented # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * other = set(other) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":476 - * - * def __or__(self, other): - * if not isinstance(other, Iterable): # <<<<<<<<<<<<<< - * return NotImplemented - * if not isinstance(other, Set): - */ - } - - /* "aiohttp/_multidict.pyx":478 - * if not isinstance(other, Iterable): - * return NotImplemented - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * other = set(other) - * return set(self) | other - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Set); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 478; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = ((!(__pyx_t_3 != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":479 - * return NotImplemented - * if not isinstance(other, Set): - * other = set(other) # <<<<<<<<<<<<<< - * return set(self) | other - * - */ - __pyx_t_1 = PySet_New(__pyx_v_other); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_other, __pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":478 - * if not isinstance(other, Iterable): - * return NotImplemented - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * other = set(other) - * return set(self) | other - */ - } - - /* "aiohttp/_multidict.pyx":480 - * if not isinstance(other, Set): - * other = set(other) - * return set(self) | other # <<<<<<<<<<<<<< - * - * def __sub__(self, other): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PySet_New(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Or(__pyx_t_1, __pyx_v_other); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":475 - * return set(self) & other - * - * def __or__(self, other): # <<<<<<<<<<<<<< - * if not isinstance(other, Iterable): - * return NotImplemented - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._multidict._ViewBaseSet.__or__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_other); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":482 - * return set(self) | other - * - * def __sub__(self, other): # <<<<<<<<<<<<<< - * if not isinstance(other, Iterable): - * return NotImplemented - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_7__sub__(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_7__sub__(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__sub__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_6__sub__(((PyObject *)__pyx_v_self), ((PyObject *)__pyx_v_other)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_6__sub__(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__sub__", 0); - __Pyx_INCREF(__pyx_v_other); - - /* "aiohttp/_multidict.pyx":483 - * - * def __sub__(self, other): - * if not isinstance(other, Iterable): # <<<<<<<<<<<<<< - * return NotImplemented - * if not isinstance(other, Set): - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Iterable); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 483; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":484 - * def __sub__(self, other): - * if not isinstance(other, Iterable): - * return NotImplemented # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * other = set(other) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":483 - * - * def __sub__(self, other): - * if not isinstance(other, Iterable): # <<<<<<<<<<<<<< - * return NotImplemented - * if not isinstance(other, Set): - */ - } - - /* "aiohttp/_multidict.pyx":485 - * if not isinstance(other, Iterable): - * return NotImplemented - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * other = set(other) - * return set(self) - other - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Set); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = ((!(__pyx_t_3 != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":486 - * return NotImplemented - * if not isinstance(other, Set): - * other = set(other) # <<<<<<<<<<<<<< - * return set(self) - other - * - */ - __pyx_t_1 = PySet_New(__pyx_v_other); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_other, __pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":485 - * if not isinstance(other, Iterable): - * return NotImplemented - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * other = set(other) - * return set(self) - other - */ - } - - /* "aiohttp/_multidict.pyx":487 - * if not isinstance(other, Set): - * other = set(other) - * return set(self) - other # <<<<<<<<<<<<<< - * - * def __xor__(self, other): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PySet_New(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Subtract(__pyx_t_1, __pyx_v_other); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":482 - * return set(self) | other - * - * def __sub__(self, other): # <<<<<<<<<<<<<< - * if not isinstance(other, Iterable): - * return NotImplemented - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._multidict._ViewBaseSet.__sub__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_other); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":489 - * return set(self) - other - * - * def __xor__(self, other): # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * if not isinstance(other, Iterable): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_9__xor__(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_9__xor__(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__xor__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_8__xor__(((PyObject *)__pyx_v_self), ((PyObject *)__pyx_v_other)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_12_ViewBaseSet_8__xor__(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__xor__", 0); - __Pyx_INCREF(__pyx_v_other); - - /* "aiohttp/_multidict.pyx":490 - * - * def __xor__(self, other): - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * if not isinstance(other, Iterable): - * return NotImplemented - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Set); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 490; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 490; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_3) { - - /* "aiohttp/_multidict.pyx":491 - * def __xor__(self, other): - * if not isinstance(other, Set): - * if not isinstance(other, Iterable): # <<<<<<<<<<<<<< - * return NotImplemented - * other = set(other) - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_Iterable); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 491; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyObject_IsInstance(__pyx_v_other, __pyx_t_1); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 491; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = ((!(__pyx_t_3 != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_multidict.pyx":492 - * if not isinstance(other, Set): - * if not isinstance(other, Iterable): - * return NotImplemented # <<<<<<<<<<<<<< - * other = set(other) - * return set(self) ^ other - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_builtin_NotImplemented); - __pyx_r = __pyx_builtin_NotImplemented; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":491 - * def __xor__(self, other): - * if not isinstance(other, Set): - * if not isinstance(other, Iterable): # <<<<<<<<<<<<<< - * return NotImplemented - * other = set(other) - */ - } - - /* "aiohttp/_multidict.pyx":493 - * if not isinstance(other, Iterable): - * return NotImplemented - * other = set(other) # <<<<<<<<<<<<<< - * return set(self) ^ other - * - */ - __pyx_t_1 = PySet_New(__pyx_v_other); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_other, __pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":490 - * - * def __xor__(self, other): - * if not isinstance(other, Set): # <<<<<<<<<<<<<< - * if not isinstance(other, Iterable): - * return NotImplemented - */ - } - - /* "aiohttp/_multidict.pyx":494 - * return NotImplemented - * other = set(other) - * return set(self) ^ other # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PySet_New(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyNumber_Xor(__pyx_t_1, __pyx_v_other); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":489 - * return set(self) - other - * - * def __xor__(self, other): # <<<<<<<<<<<<<< - * if not isinstance(other, Set): - * if not isinstance(other, Iterable): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._multidict._ViewBaseSet.__xor__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_other); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":502 - * cdef int _len - * - * def __cinit__(self, items): # <<<<<<<<<<<<<< - * self._items = items - * self._current = 0 - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_10_ItemsIter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_10_ItemsIter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_items = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_items,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_items)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_items = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._ItemsIter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_10_ItemsIter___cinit__(((struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *)__pyx_v_self), __pyx_v_items); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_10_ItemsIter___cinit__(struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *__pyx_v_self, PyObject *__pyx_v_items) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "aiohttp/_multidict.pyx":503 - * - * def __cinit__(self, items): - * self._items = items # <<<<<<<<<<<<<< - * self._current = 0 - * self._len = len(self._items) - */ - if (!(likely(PyList_CheckExact(__pyx_v_items))||((__pyx_v_items) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "list", Py_TYPE(__pyx_v_items)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __pyx_v_items; - __Pyx_INCREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->_items); - __Pyx_DECREF(__pyx_v_self->_items); - __pyx_v_self->_items = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":504 - * def __cinit__(self, items): - * self._items = items - * self._current = 0 # <<<<<<<<<<<<<< - * self._len = len(self._items) - * - */ - __pyx_v_self->_current = 0; - - /* "aiohttp/_multidict.pyx":505 - * self._items = items - * self._current = 0 - * self._len = len(self._items) # <<<<<<<<<<<<<< - * - * def __iter__(self): - */ - __pyx_t_1 = __pyx_v_self->_items; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = PyList_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_self->_len = __pyx_t_2; - - /* "aiohttp/_multidict.pyx":502 - * cdef int _len - * - * def __cinit__(self, items): # <<<<<<<<<<<<<< - * self._items = items - * self._current = 0 - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict._ItemsIter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":507 - * self._len = len(self._items) - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsIter_3__iter__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsIter_3__iter__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_10_ItemsIter_2__iter__(((struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsIter_2__iter__(struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__", 0); - - /* "aiohttp/_multidict.pyx":508 - * - * def __iter__(self): - * return self # <<<<<<<<<<<<<< - * - * def __next__(self): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __pyx_r = ((PyObject *)__pyx_v_self); - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":507 - * self._len = len(self._items) - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":510 - * return self - * - * def __next__(self): # <<<<<<<<<<<<<< - * if self._current == self._len: - * raise StopIteration - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsIter_5__next__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsIter_5__next__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_10_ItemsIter_4__next__(((struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsIter_4__next__(struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *__pyx_v_self) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__next__", 0); - - /* "aiohttp/_multidict.pyx":511 - * - * def __next__(self): - * if self._current == self._len: # <<<<<<<<<<<<<< - * raise StopIteration - * item = <_Pair>self._items[self._current] - */ - __pyx_t_1 = ((__pyx_v_self->_current == __pyx_v_self->_len) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":512 - * def __next__(self): - * if self._current == self._len: - * raise StopIteration # <<<<<<<<<<<<<< - * item = <_Pair>self._items[self._current] - * self._current += 1 - */ - __Pyx_Raise(__pyx_builtin_StopIteration, 0, 0, 0); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":511 - * - * def __next__(self): - * if self._current == self._len: # <<<<<<<<<<<<<< - * raise StopIteration - * item = <_Pair>self._items[self._current] - */ - } - - /* "aiohttp/_multidict.pyx":513 - * if self._current == self._len: - * raise StopIteration - * item = <_Pair>self._items[self._current] # <<<<<<<<<<<<<< - * self._current += 1 - * return (item._key, item._value) - */ - if (unlikely(__pyx_v_self->_items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = __Pyx_GetItemInt_List(__pyx_v_self->_items, __pyx_v_self->_current, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_item = ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":514 - * raise StopIteration - * item = <_Pair>self._items[self._current] - * self._current += 1 # <<<<<<<<<<<<<< - * return (item._key, item._value) - * - */ - __pyx_v_self->_current = (__pyx_v_self->_current + 1); - - /* "aiohttp/_multidict.pyx":515 - * item = <_Pair>self._items[self._current] - * self._current += 1 - * return (item._key, item._value) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_item->_key); - __Pyx_GIVEREF(__pyx_v_item->_key); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_item->_key); - __Pyx_INCREF(__pyx_v_item->_value); - __Pyx_GIVEREF(__pyx_v_item->_value); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_item->_value); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":510 - * return self - * - * def __next__(self): # <<<<<<<<<<<<<< - * if self._current == self._len: - * raise StopIteration - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._ItemsIter.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":520 - * cdef class _ItemsView(_ViewBaseSet): - * - * def isdisjoint(self, other): # <<<<<<<<<<<<<< - * 'Return True if two sets have a null intersection.' - * cdef _Pair item - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsView_1isdisjoint(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_10_ItemsView_isdisjoint[] = "Return True if two sets have a null intersection."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsView_1isdisjoint(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("isdisjoint (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_10_ItemsView_isdisjoint(((struct __pyx_obj_7aiohttp_10_multidict__ItemsView *)__pyx_v_self), ((PyObject *)__pyx_v_other)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsView_isdisjoint(struct __pyx_obj_7aiohttp_10_multidict__ItemsView *__pyx_v_self, PyObject *__pyx_v_other) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_t = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("isdisjoint", 0); - - /* "aiohttp/_multidict.pyx":523 - * 'Return True if two sets have a null intersection.' - * cdef _Pair item - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * t = (item._key, item._value) - */ - if (unlikely(__pyx_v_self->__pyx_base.__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base._items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":524 - * cdef _Pair item - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * t = (item._key, item._value) - * if t in other: - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":525 - * for i in self._items: - * item = <_Pair>i - * t = (item._key, item._value) # <<<<<<<<<<<<<< - * if t in other: - * return False - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_item->_key); - __Pyx_GIVEREF(__pyx_v_item->_key); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_item->_key); - __Pyx_INCREF(__pyx_v_item->_value); - __Pyx_GIVEREF(__pyx_v_item->_value); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_item->_value); - __Pyx_XDECREF_SET(__pyx_v_t, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":526 - * item = <_Pair>i - * t = (item._key, item._value) - * if t in other: # <<<<<<<<<<<<<< - * return False - * return True - */ - __pyx_t_4 = (__Pyx_PySequence_ContainsTF(__pyx_v_t, __pyx_v_other, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = (__pyx_t_4 != 0); - if (__pyx_t_5) { - - /* "aiohttp/_multidict.pyx":527 - * t = (item._key, item._value) - * if t in other: - * return False # <<<<<<<<<<<<<< - * return True - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":526 - * item = <_Pair>i - * t = (item._key, item._value) - * if t in other: # <<<<<<<<<<<<<< - * return False - * return True - */ - } - - /* "aiohttp/_multidict.pyx":523 - * 'Return True if two sets have a null intersection.' - * cdef _Pair item - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * t = (item._key, item._value) - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":528 - * if t in other: - * return False - * return True # <<<<<<<<<<<<<< - * - * def __contains__(self, i): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_True); - __pyx_r = Py_True; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":520 - * cdef class _ItemsView(_ViewBaseSet): - * - * def isdisjoint(self, other): # <<<<<<<<<<<<<< - * 'Return True if two sets have a null intersection.' - * cdef _Pair item - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._ItemsView.isdisjoint", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_t); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":530 - * return True - * - * def __contains__(self, i): # <<<<<<<<<<<<<< - * cdef _Pair item - * assert isinstance(i, tuple) or isinstance(i, list) - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_10_ItemsView_3__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_i); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_10_ItemsView_3__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_i) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__contains__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_10_ItemsView_2__contains__(((struct __pyx_obj_7aiohttp_10_multidict__ItemsView *)__pyx_v_self), ((PyObject *)__pyx_v_i)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_10_ItemsView_2__contains__(struct __pyx_obj_7aiohttp_10_multidict__ItemsView *__pyx_v_self, PyObject *__pyx_v_i) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - Py_ssize_t __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__contains__", 0); - - /* "aiohttp/_multidict.pyx":532 - * def __contains__(self, i): - * cdef _Pair item - * assert isinstance(i, tuple) or isinstance(i, list) # <<<<<<<<<<<<<< - * assert len(i) == 2 - * item = _Pair.__new__(_Pair, i[0], i[1]) - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - __pyx_t_2 = PyTuple_Check(__pyx_v_i); - __pyx_t_3 = (__pyx_t_2 != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_1 = __pyx_t_3; - goto __pyx_L3_bool_binop_done; - } - __pyx_t_3 = PyList_Check(__pyx_v_i); - __pyx_t_2 = (__pyx_t_3 != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L3_bool_binop_done:; - if (unlikely(!__pyx_t_1)) { - PyErr_SetNone(PyExc_AssertionError); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - } - #endif - - /* "aiohttp/_multidict.pyx":533 - * cdef _Pair item - * assert isinstance(i, tuple) or isinstance(i, list) - * assert len(i) == 2 # <<<<<<<<<<<<<< - * item = _Pair.__new__(_Pair, i[0], i[1]) - * return item in self._items - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - __pyx_t_4 = PyObject_Length(__pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!((__pyx_t_4 == 2) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - } - #endif - - /* "aiohttp/_multidict.pyx":534 - * assert isinstance(i, tuple) or isinstance(i, list) - * assert len(i) == 2 - * item = _Pair.__new__(_Pair, i[0], i[1]) # <<<<<<<<<<<<<< - * return item in self._items - * - */ - __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_i, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 534; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __Pyx_GetItemInt(__pyx_v_i, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 534; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_6); - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_6 = __pyx_tp_new_7aiohttp_10_multidict__Pair(((PyTypeObject *)__pyx_ptype_7aiohttp_10_multidict__Pair), __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (!(likely(__Pyx_TypeTest(__pyx_t_6, __pyx_ptype_7aiohttp_10_multidict__Pair)))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_item = ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_6); - __pyx_t_6 = 0; - - /* "aiohttp/_multidict.pyx":535 - * assert len(i) == 2 - * item = _Pair.__new__(_Pair, i[0], i[1]) - * return item in self._items # <<<<<<<<<<<<<< - * - * def __iter__(self): - */ - __pyx_t_1 = (__Pyx_PySequence_ContainsTF(((PyObject *)__pyx_v_item), __pyx_v_self->__pyx_base.__pyx_base._items, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_r = __pyx_t_1; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":530 - * return True - * - * def __contains__(self, i): # <<<<<<<<<<<<<< - * cdef _Pair item - * assert isinstance(i, tuple) or isinstance(i, list) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._multidict._ItemsView.__contains__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":537 - * return item in self._items - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return _ItemsIter.__new__(_ItemsIter, self._items) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsView_5__iter__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsView_5__iter__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_10_ItemsView_4__iter__(((struct __pyx_obj_7aiohttp_10_multidict__ItemsView *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsView_4__iter__(struct __pyx_obj_7aiohttp_10_multidict__ItemsView *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__iter__", 0); - - /* "aiohttp/_multidict.pyx":538 - * - * def __iter__(self): - * return _ItemsIter.__new__(_ItemsIter, self._items) # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->__pyx_base.__pyx_base._items); - __Pyx_GIVEREF(__pyx_v_self->__pyx_base.__pyx_base._items); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->__pyx_base.__pyx_base._items); - __pyx_t_2 = __pyx_tp_new_7aiohttp_10_multidict__ItemsIter(((PyTypeObject *)__pyx_ptype_7aiohttp_10_multidict__ItemsIter), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":537 - * return item in self._items - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return _ItemsIter.__new__(_ItemsIter, self._items) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._ItemsView.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":540 - * return _ItemsIter.__new__(_ItemsIter, self._items) - * - * def __repr__(self): # <<<<<<<<<<<<<< - * cdef _Pair item - * lst = [] - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsView_7__repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_10_ItemsView_7__repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_10_ItemsView_6__repr__(((struct __pyx_obj_7aiohttp_10_multidict__ItemsView *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_10_ItemsView_6__repr__(struct __pyx_obj_7aiohttp_10_multidict__ItemsView *__pyx_v_self) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_lst = NULL; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_body = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - Py_ssize_t __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "aiohttp/_multidict.pyx":542 - * def __repr__(self): - * cdef _Pair item - * lst = [] # <<<<<<<<<<<<<< - * for i in self._items: - * item = <_Pair>i - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_lst = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":543 - * cdef _Pair item - * lst = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * lst.append("{!r}: {!r}".format(item._key, item._value)) - */ - if (unlikely(__pyx_v_self->__pyx_base.__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base._items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":544 - * lst = [] - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * lst.append("{!r}: {!r}".format(item._key, item._value)) - * body = ', '.join(lst) - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":545 - * for i in self._items: - * item = <_Pair>i - * lst.append("{!r}: {!r}".format(item._key, item._value)) # <<<<<<<<<<<<<< - * body = ', '.join(lst) - * return '{}({})'.format(self.__class__.__name__, body) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_r_r, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - __pyx_t_6 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_6 = 1; - } - } - __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_5) { - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_5); __pyx_t_5 = NULL; - } - __Pyx_INCREF(__pyx_v_item->_key); - __Pyx_GIVEREF(__pyx_v_item->_key); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_v_item->_key); - __Pyx_INCREF(__pyx_v_item->_value); - __Pyx_GIVEREF(__pyx_v_item->_value); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_v_item->_value); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_7, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_8 = __Pyx_PyList_Append(__pyx_v_lst, __pyx_t_3); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":543 - * cdef _Pair item - * lst = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * lst.append("{!r}: {!r}".format(item._key, item._value)) - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":546 - * item = <_Pair>i - * lst.append("{!r}: {!r}".format(item._key, item._value)) - * body = ', '.join(lst) # <<<<<<<<<<<<<< - * return '{}({})'.format(self.__class__.__name__, body) - * - */ - __pyx_t_1 = __Pyx_PyString_Join(__pyx_kp_s__4, __pyx_v_lst); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_body = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":547 - * lst.append("{!r}: {!r}".format(item._key, item._value)) - * body = ', '.join(lst) - * return '{}({})'.format(self.__class__.__name__, body) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s__8, __pyx_n_s_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_name); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - __pyx_t_2 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_2 = 1; - } - } - __pyx_t_5 = PyTuple_New(2+__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_2, __pyx_t_7); - __Pyx_INCREF(__pyx_v_body); - __Pyx_GIVEREF(__pyx_v_body); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_2, __pyx_v_body); - __pyx_t_7 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":540 - * return _ItemsIter.__new__(_ItemsIter, self._items) - * - * def __repr__(self): # <<<<<<<<<<<<<< - * cdef _Pair item - * lst = [] - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._multidict._ItemsView.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_lst); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_body); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":558 - * cdef int _len - * - * def __cinit__(self, items): # <<<<<<<<<<<<<< - * self._items = items - * self._current = 0 - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_11_ValuesIter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_11_ValuesIter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_items = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_items,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_items)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 558; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_items = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 558; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._ValuesIter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_11_ValuesIter___cinit__(((struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *)__pyx_v_self), __pyx_v_items); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_11_ValuesIter___cinit__(struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *__pyx_v_self, PyObject *__pyx_v_items) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "aiohttp/_multidict.pyx":559 - * - * def __cinit__(self, items): - * self._items = items # <<<<<<<<<<<<<< - * self._current = 0 - * self._len = len(self._items) - */ - if (!(likely(PyList_CheckExact(__pyx_v_items))||((__pyx_v_items) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "list", Py_TYPE(__pyx_v_items)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __pyx_v_items; - __Pyx_INCREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->_items); - __Pyx_DECREF(__pyx_v_self->_items); - __pyx_v_self->_items = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":560 - * def __cinit__(self, items): - * self._items = items - * self._current = 0 # <<<<<<<<<<<<<< - * self._len = len(self._items) - * - */ - __pyx_v_self->_current = 0; - - /* "aiohttp/_multidict.pyx":561 - * self._items = items - * self._current = 0 - * self._len = len(self._items) # <<<<<<<<<<<<<< - * - * def __iter__(self): - */ - __pyx_t_1 = __pyx_v_self->_items; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = PyList_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_self->_len = __pyx_t_2; - - /* "aiohttp/_multidict.pyx":558 - * cdef int _len - * - * def __cinit__(self, items): # <<<<<<<<<<<<<< - * self._items = items - * self._current = 0 - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict._ValuesIter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":563 - * self._len = len(self._items) - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_11_ValuesIter_3__iter__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_11_ValuesIter_3__iter__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_11_ValuesIter_2__iter__(((struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_11_ValuesIter_2__iter__(struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__", 0); - - /* "aiohttp/_multidict.pyx":564 - * - * def __iter__(self): - * return self # <<<<<<<<<<<<<< - * - * def __next__(self): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __pyx_r = ((PyObject *)__pyx_v_self); - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":563 - * self._len = len(self._items) - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":566 - * return self - * - * def __next__(self): # <<<<<<<<<<<<<< - * if self._current == self._len: - * raise StopIteration - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_11_ValuesIter_5__next__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_11_ValuesIter_5__next__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_11_ValuesIter_4__next__(((struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_11_ValuesIter_4__next__(struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *__pyx_v_self) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__next__", 0); - - /* "aiohttp/_multidict.pyx":567 - * - * def __next__(self): - * if self._current == self._len: # <<<<<<<<<<<<<< - * raise StopIteration - * item = <_Pair>self._items[self._current] - */ - __pyx_t_1 = ((__pyx_v_self->_current == __pyx_v_self->_len) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":568 - * def __next__(self): - * if self._current == self._len: - * raise StopIteration # <<<<<<<<<<<<<< - * item = <_Pair>self._items[self._current] - * self._current += 1 - */ - __Pyx_Raise(__pyx_builtin_StopIteration, 0, 0, 0); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":567 - * - * def __next__(self): - * if self._current == self._len: # <<<<<<<<<<<<<< - * raise StopIteration - * item = <_Pair>self._items[self._current] - */ - } - - /* "aiohttp/_multidict.pyx":569 - * if self._current == self._len: - * raise StopIteration - * item = <_Pair>self._items[self._current] # <<<<<<<<<<<<<< - * self._current += 1 - * return item._value - */ - if (unlikely(__pyx_v_self->_items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = __Pyx_GetItemInt_List(__pyx_v_self->_items, __pyx_v_self->_current, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_item = ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":570 - * raise StopIteration - * item = <_Pair>self._items[self._current] - * self._current += 1 # <<<<<<<<<<<<<< - * return item._value - * - */ - __pyx_v_self->_current = (__pyx_v_self->_current + 1); - - /* "aiohttp/_multidict.pyx":571 - * item = <_Pair>self._items[self._current] - * self._current += 1 - * return item._value # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_item->_value); - __pyx_r = __pyx_v_item->_value; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":566 - * return self - * - * def __next__(self): # <<<<<<<<<<<<<< - * if self._current == self._len: - * raise StopIteration - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._ValuesIter.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":576 - * cdef class _ValuesView(_ViewBase): - * - * def __contains__(self, value): # <<<<<<<<<<<<<< - * cdef _Pair item - * for i in self._items: - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_11_ValuesView_1__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_11_ValuesView_1__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__contains__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_11_ValuesView___contains__(((struct __pyx_obj_7aiohttp_10_multidict__ValuesView *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_11_ValuesView___contains__(struct __pyx_obj_7aiohttp_10_multidict__ValuesView *__pyx_v_self, PyObject *__pyx_v_value) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_i = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__contains__", 0); - - /* "aiohttp/_multidict.pyx":578 - * def __contains__(self, value): - * cdef _Pair item - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._value == value: - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 578; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->__pyx_base._items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 578; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 578; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":579 - * cdef _Pair item - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * if item._value == value: - * return True - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":580 - * for i in self._items: - * item = <_Pair>i - * if item._value == value: # <<<<<<<<<<<<<< - * return True - * return False - */ - __pyx_t_3 = PyObject_RichCompare(__pyx_v_item->_value, __pyx_v_value, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":581 - * item = <_Pair>i - * if item._value == value: - * return True # <<<<<<<<<<<<<< - * return False - * - */ - __pyx_r = 1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":580 - * for i in self._items: - * item = <_Pair>i - * if item._value == value: # <<<<<<<<<<<<<< - * return True - * return False - */ - } - - /* "aiohttp/_multidict.pyx":578 - * def __contains__(self, value): - * cdef _Pair item - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._value == value: - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":582 - * if item._value == value: - * return True - * return False # <<<<<<<<<<<<<< - * - * def __iter__(self): - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":576 - * cdef class _ValuesView(_ViewBase): - * - * def __contains__(self, value): # <<<<<<<<<<<<<< - * cdef _Pair item - * for i in self._items: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._ValuesView.__contains__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":584 - * return False - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return _ValuesIter.__new__(_ValuesIter, self._items) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_11_ValuesView_3__iter__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_11_ValuesView_3__iter__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_11_ValuesView_2__iter__(((struct __pyx_obj_7aiohttp_10_multidict__ValuesView *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_11_ValuesView_2__iter__(struct __pyx_obj_7aiohttp_10_multidict__ValuesView *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__iter__", 0); - - /* "aiohttp/_multidict.pyx":585 - * - * def __iter__(self): - * return _ValuesIter.__new__(_ValuesIter, self._items) # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->__pyx_base._items); - __Pyx_GIVEREF(__pyx_v_self->__pyx_base._items); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->__pyx_base._items); - __pyx_t_2 = __pyx_tp_new_7aiohttp_10_multidict__ValuesIter(((PyTypeObject *)__pyx_ptype_7aiohttp_10_multidict__ValuesIter), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":584 - * return False - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return _ValuesIter.__new__(_ValuesIter, self._items) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._ValuesView.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":587 - * return _ValuesIter.__new__(_ValuesIter, self._items) - * - * def __repr__(self): # <<<<<<<<<<<<<< - * cdef _Pair item - * lst = [] - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_11_ValuesView_5__repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_11_ValuesView_5__repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_11_ValuesView_4__repr__(((struct __pyx_obj_7aiohttp_10_multidict__ValuesView *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_11_ValuesView_4__repr__(struct __pyx_obj_7aiohttp_10_multidict__ValuesView *__pyx_v_self) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_lst = NULL; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_body = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "aiohttp/_multidict.pyx":589 - * def __repr__(self): - * cdef _Pair item - * lst = [] # <<<<<<<<<<<<<< - * for i in self._items: - * item = <_Pair>i - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 589; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_lst = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":590 - * cdef _Pair item - * lst = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * lst.append("{!r}".format(item._value)) - */ - if (unlikely(__pyx_v_self->__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->__pyx_base._items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":591 - * lst = [] - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * lst.append("{!r}".format(item._value)) - * body = ', '.join(lst) - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":592 - * for i in self._items: - * item = <_Pair>i - * lst.append("{!r}".format(item._value)) # <<<<<<<<<<<<<< - * body = ', '.join(lst) - * return '{}({})'.format(self.__class__.__name__, body) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_r_2, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - if (!__pyx_t_5) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_v_item->_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - } else { - __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; - __Pyx_INCREF(__pyx_v_item->_value); - __Pyx_GIVEREF(__pyx_v_item->_value); - PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_v_item->_value); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_7 = __Pyx_PyList_Append(__pyx_v_lst, __pyx_t_3); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":590 - * cdef _Pair item - * lst = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * lst.append("{!r}".format(item._value)) - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":593 - * item = <_Pair>i - * lst.append("{!r}".format(item._value)) - * body = ', '.join(lst) # <<<<<<<<<<<<<< - * return '{}({})'.format(self.__class__.__name__, body) - * - */ - __pyx_t_1 = __Pyx_PyString_Join(__pyx_kp_s__4, __pyx_v_lst); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_body = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":594 - * lst.append("{!r}".format(item._value)) - * body = ', '.join(lst) - * return '{}({})'.format(self.__class__.__name__, body) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s__8, __pyx_n_s_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_name); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - __pyx_t_2 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_2 = 1; - } - } - __pyx_t_5 = PyTuple_New(2+__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_2, __pyx_t_6); - __Pyx_INCREF(__pyx_v_body); - __Pyx_GIVEREF(__pyx_v_body); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_2, __pyx_v_body); - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":587 - * return _ValuesIter.__new__(_ValuesIter, self._items) - * - * def __repr__(self): # <<<<<<<<<<<<<< - * cdef _Pair item - * lst = [] - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._multidict._ValuesView.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_lst); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_body); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":605 - * cdef int _len - * - * def __cinit__(self, items): # <<<<<<<<<<<<<< - * self._items = items - * self._current = 0 - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_9_KeysIter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_9_KeysIter_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_items = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_items,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_items)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 605; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_items = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 605; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._multidict._KeysIter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9_KeysIter___cinit__(((struct __pyx_obj_7aiohttp_10_multidict__KeysIter *)__pyx_v_self), __pyx_v_items); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_9_KeysIter___cinit__(struct __pyx_obj_7aiohttp_10_multidict__KeysIter *__pyx_v_self, PyObject *__pyx_v_items) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "aiohttp/_multidict.pyx":606 - * - * def __cinit__(self, items): - * self._items = items # <<<<<<<<<<<<<< - * self._current = 0 - * self._len = len(self._items) - */ - if (!(likely(PyList_CheckExact(__pyx_v_items))||((__pyx_v_items) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "list", Py_TYPE(__pyx_v_items)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __pyx_v_items; - __Pyx_INCREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->_items); - __Pyx_DECREF(__pyx_v_self->_items); - __pyx_v_self->_items = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":607 - * def __cinit__(self, items): - * self._items = items - * self._current = 0 # <<<<<<<<<<<<<< - * self._len = len(self._items) - * - */ - __pyx_v_self->_current = 0; - - /* "aiohttp/_multidict.pyx":608 - * self._items = items - * self._current = 0 - * self._len = len(self._items) # <<<<<<<<<<<<<< - * - * def __iter__(self): - */ - __pyx_t_1 = __pyx_v_self->_items; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = PyList_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_2 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_self->_len = __pyx_t_2; - - /* "aiohttp/_multidict.pyx":605 - * cdef int _len - * - * def __cinit__(self, items): # <<<<<<<<<<<<<< - * self._items = items - * self._current = 0 - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._multidict._KeysIter.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":610 - * self._len = len(self._items) - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysIter_3__iter__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysIter_3__iter__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9_KeysIter_2__iter__(((struct __pyx_obj_7aiohttp_10_multidict__KeysIter *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysIter_2__iter__(struct __pyx_obj_7aiohttp_10_multidict__KeysIter *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__", 0); - - /* "aiohttp/_multidict.pyx":611 - * - * def __iter__(self): - * return self # <<<<<<<<<<<<<< - * - * def __next__(self): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __pyx_r = ((PyObject *)__pyx_v_self); - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":610 - * self._len = len(self._items) - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return self - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":613 - * return self - * - * def __next__(self): # <<<<<<<<<<<<<< - * if self._current == self._len: - * raise StopIteration - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysIter_5__next__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysIter_5__next__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9_KeysIter_4__next__(((struct __pyx_obj_7aiohttp_10_multidict__KeysIter *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysIter_4__next__(struct __pyx_obj_7aiohttp_10_multidict__KeysIter *__pyx_v_self) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__next__", 0); - - /* "aiohttp/_multidict.pyx":614 - * - * def __next__(self): - * if self._current == self._len: # <<<<<<<<<<<<<< - * raise StopIteration - * item = <_Pair>self._items[self._current] - */ - __pyx_t_1 = ((__pyx_v_self->_current == __pyx_v_self->_len) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_multidict.pyx":615 - * def __next__(self): - * if self._current == self._len: - * raise StopIteration # <<<<<<<<<<<<<< - * item = <_Pair>self._items[self._current] - * self._current += 1 - */ - __Pyx_Raise(__pyx_builtin_StopIteration, 0, 0, 0); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":614 - * - * def __next__(self): - * if self._current == self._len: # <<<<<<<<<<<<<< - * raise StopIteration - * item = <_Pair>self._items[self._current] - */ - } - - /* "aiohttp/_multidict.pyx":616 - * if self._current == self._len: - * raise StopIteration - * item = <_Pair>self._items[self._current] # <<<<<<<<<<<<<< - * self._current += 1 - * return item._key - */ - if (unlikely(__pyx_v_self->_items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 616; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_2 = __Pyx_GetItemInt_List(__pyx_v_self->_items, __pyx_v_self->_current, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 616; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_item = ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":617 - * raise StopIteration - * item = <_Pair>self._items[self._current] - * self._current += 1 # <<<<<<<<<<<<<< - * return item._key - * - */ - __pyx_v_self->_current = (__pyx_v_self->_current + 1); - - /* "aiohttp/_multidict.pyx":618 - * item = <_Pair>self._items[self._current] - * self._current += 1 - * return item._key # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_item->_key); - __pyx_r = __pyx_v_item->_key; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":613 - * return self - * - * def __next__(self): # <<<<<<<<<<<<<< - * if self._current == self._len: - * raise StopIteration - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._KeysIter.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":623 - * cdef class _KeysView(_ViewBaseSet): - * - * def isdisjoint(self, other): # <<<<<<<<<<<<<< - * 'Return True if two sets have a null intersection.' - * cdef _Pair item - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysView_1isdisjoint(PyObject *__pyx_v_self, PyObject *__pyx_v_other); /*proto*/ -static char __pyx_doc_7aiohttp_10_multidict_9_KeysView_isdisjoint[] = "Return True if two sets have a null intersection."; -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysView_1isdisjoint(PyObject *__pyx_v_self, PyObject *__pyx_v_other) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("isdisjoint (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9_KeysView_isdisjoint(((struct __pyx_obj_7aiohttp_10_multidict__KeysView *)__pyx_v_self), ((PyObject *)__pyx_v_other)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysView_isdisjoint(struct __pyx_obj_7aiohttp_10_multidict__KeysView *__pyx_v_self, PyObject *__pyx_v_other) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("isdisjoint", 0); - - /* "aiohttp/_multidict.pyx":626 - * 'Return True if two sets have a null intersection.' - * cdef _Pair item - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key in other: - */ - if (unlikely(__pyx_v_self->__pyx_base.__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 626; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base._items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 626; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 626; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":627 - * cdef _Pair item - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * if item._key in other: - * return False - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":628 - * for i in self._items: - * item = <_Pair>i - * if item._key in other: # <<<<<<<<<<<<<< - * return False - * return True - */ - __pyx_t_4 = (__Pyx_PySequence_ContainsTF(__pyx_v_item->_key, __pyx_v_other, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = (__pyx_t_4 != 0); - if (__pyx_t_5) { - - /* "aiohttp/_multidict.pyx":629 - * item = <_Pair>i - * if item._key in other: - * return False # <<<<<<<<<<<<<< - * return True - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_False); - __pyx_r = Py_False; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":628 - * for i in self._items: - * item = <_Pair>i - * if item._key in other: # <<<<<<<<<<<<<< - * return False - * return True - */ - } - - /* "aiohttp/_multidict.pyx":626 - * 'Return True if two sets have a null intersection.' - * cdef _Pair item - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key in other: - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":630 - * if item._key in other: - * return False - * return True # <<<<<<<<<<<<<< - * - * def __contains__(self, value): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(Py_True); - __pyx_r = Py_True; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":623 - * cdef class _KeysView(_ViewBaseSet): - * - * def isdisjoint(self, other): # <<<<<<<<<<<<<< - * 'Return True if two sets have a null intersection.' - * cdef _Pair item - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._KeysView.isdisjoint", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":632 - * return True - * - * def __contains__(self, value): # <<<<<<<<<<<<<< - * cdef _Pair item - * for i in self._items: - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_10_multidict_9_KeysView_3__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7aiohttp_10_multidict_9_KeysView_3__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__contains__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9_KeysView_2__contains__(((struct __pyx_obj_7aiohttp_10_multidict__KeysView *)__pyx_v_self), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_10_multidict_9_KeysView_2__contains__(struct __pyx_obj_7aiohttp_10_multidict__KeysView *__pyx_v_self, PyObject *__pyx_v_value) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_i = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__contains__", 0); - - /* "aiohttp/_multidict.pyx":634 - * def __contains__(self, value): - * cdef _Pair item - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == value: - */ - if (unlikely(__pyx_v_self->__pyx_base.__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base._items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 634; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":635 - * cdef _Pair item - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * if item._key == value: - * return True - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":636 - * for i in self._items: - * item = <_Pair>i - * if item._key == value: # <<<<<<<<<<<<<< - * return True - * return False - */ - __pyx_t_3 = PyObject_RichCompare(__pyx_v_item->_key, __pyx_v_value, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 636; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 636; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - - /* "aiohttp/_multidict.pyx":637 - * item = <_Pair>i - * if item._key == value: - * return True # <<<<<<<<<<<<<< - * return False - * - */ - __pyx_r = 1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":636 - * for i in self._items: - * item = <_Pair>i - * if item._key == value: # <<<<<<<<<<<<<< - * return True - * return False - */ - } - - /* "aiohttp/_multidict.pyx":634 - * def __contains__(self, value): - * cdef _Pair item - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * if item._key == value: - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":638 - * if item._key == value: - * return True - * return False # <<<<<<<<<<<<<< - * - * def __iter__(self): - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":632 - * return True - * - * def __contains__(self, value): # <<<<<<<<<<<<<< - * cdef _Pair item - * for i in self._items: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._multidict._KeysView.__contains__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":640 - * return False - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return _KeysIter.__new__(_KeysIter, self._items) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysView_5__iter__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysView_5__iter__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9_KeysView_4__iter__(((struct __pyx_obj_7aiohttp_10_multidict__KeysView *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysView_4__iter__(struct __pyx_obj_7aiohttp_10_multidict__KeysView *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__iter__", 0); - - /* "aiohttp/_multidict.pyx":641 - * - * def __iter__(self): - * return _KeysIter.__new__(_KeysIter, self._items) # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->__pyx_base.__pyx_base._items); - __Pyx_GIVEREF(__pyx_v_self->__pyx_base.__pyx_base._items); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->__pyx_base.__pyx_base._items); - __pyx_t_2 = __pyx_tp_new_7aiohttp_10_multidict__KeysIter(((PyTypeObject *)__pyx_ptype_7aiohttp_10_multidict__KeysIter), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":640 - * return False - * - * def __iter__(self): # <<<<<<<<<<<<<< - * return _KeysIter.__new__(_KeysIter, self._items) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._multidict._KeysView.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_multidict.pyx":643 - * return _KeysIter.__new__(_KeysIter, self._items) - * - * def __repr__(self): # <<<<<<<<<<<<<< - * cdef _Pair item - * lst = [] - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysView_7__repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_10_multidict_9_KeysView_7__repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_10_multidict_9_KeysView_6__repr__(((struct __pyx_obj_7aiohttp_10_multidict__KeysView *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_multidict_9_KeysView_6__repr__(struct __pyx_obj_7aiohttp_10_multidict__KeysView *__pyx_v_self) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *__pyx_v_item = 0; - PyObject *__pyx_v_lst = NULL; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_body = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "aiohttp/_multidict.pyx":645 - * def __repr__(self): - * cdef _Pair item - * lst = [] # <<<<<<<<<<<<<< - * for i in self._items: - * item = <_Pair>i - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_lst = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":646 - * cdef _Pair item - * lst = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * lst.append("{!r}".format(item._key)) - */ - if (unlikely(__pyx_v_self->__pyx_base.__pyx_base._items == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_1 = __pyx_v_self->__pyx_base.__pyx_base._items; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":647 - * lst = [] - * for i in self._items: - * item = <_Pair>i # <<<<<<<<<<<<<< - * lst.append("{!r}".format(item._key)) - * body = ', '.join(lst) - */ - __pyx_t_3 = __pyx_v_i; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_item, ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":648 - * for i in self._items: - * item = <_Pair>i - * lst.append("{!r}".format(item._key)) # <<<<<<<<<<<<<< - * body = ', '.join(lst) - * return '{}({})'.format(self.__class__.__name__, body) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s_r_2, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - if (!__pyx_t_5) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_v_item->_key); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - } else { - __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; - __Pyx_INCREF(__pyx_v_item->_key); - __Pyx_GIVEREF(__pyx_v_item->_key); - PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_v_item->_key); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_7 = __Pyx_PyList_Append(__pyx_v_lst, __pyx_t_3); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_multidict.pyx":646 - * cdef _Pair item - * lst = [] - * for i in self._items: # <<<<<<<<<<<<<< - * item = <_Pair>i - * lst.append("{!r}".format(item._key)) - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":649 - * item = <_Pair>i - * lst.append("{!r}".format(item._key)) - * body = ', '.join(lst) # <<<<<<<<<<<<<< - * return '{}({})'.format(self.__class__.__name__, body) - * - */ - __pyx_t_1 = __Pyx_PyString_Join(__pyx_kp_s__4, __pyx_v_lst); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_body = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":650 - * lst.append("{!r}".format(item._key)) - * body = ', '.join(lst) - * return '{}({})'.format(self.__class__.__name__, body) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_kp_s__8, __pyx_n_s_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_class); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_name); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - __pyx_t_2 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_2 = 1; - } - } - __pyx_t_5 = PyTuple_New(2+__pyx_t_2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_2, __pyx_t_6); - __Pyx_INCREF(__pyx_v_body); - __Pyx_GIVEREF(__pyx_v_body); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_2, __pyx_v_body); - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_multidict.pyx":643 - * return _KeysIter.__new__(_KeysIter, self._items) - * - * def __repr__(self): # <<<<<<<<<<<<<< - * cdef _Pair item - * lst = [] - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._multidict._KeysView.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_item); - __Pyx_XDECREF(__pyx_v_lst); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_body); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__Pair(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict__Pair *)o); - p->_key = Py_None; Py_INCREF(Py_None); - p->_value = Py_None; Py_INCREF(Py_None); - if (unlikely(__pyx_pw_7aiohttp_10_multidict_5_Pair_1__cinit__(o, a, k) < 0)) { - Py_DECREF(o); o = 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_10_multidict__Pair(PyObject *o) { - struct __pyx_obj_7aiohttp_10_multidict__Pair *p = (struct __pyx_obj_7aiohttp_10_multidict__Pair *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->_key); - Py_CLEAR(p->_value); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_7aiohttp_10_multidict__Pair(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_10_multidict__Pair *p = (struct __pyx_obj_7aiohttp_10_multidict__Pair *)o; - if (p->_key) { - e = (*v)(p->_key, a); if (e) return e; - } - if (p->_value) { - e = (*v)(p->_value, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_10_multidict__Pair(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_10_multidict__Pair *p = (struct __pyx_obj_7aiohttp_10_multidict__Pair *)o; - tmp = ((PyObject*)p->_key); - p->_key = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_value); - p->_value = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__Pair[] = { - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__Pair = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._Pair", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__Pair), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__Pair, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__Pair, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__Pair, /*tp_clear*/ - __pyx_pw_7aiohttp_10_multidict_5_Pair_3__richcmp__, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__Pair, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__Pair, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict__Base __pyx_vtable_7aiohttp_10_multidict__Base; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__Base(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict__Base *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict__Base *)o); - p->__pyx_vtab = __pyx_vtabptr_7aiohttp_10_multidict__Base; - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_upstr = Py_None; Py_INCREF(Py_None); - p->marker = Py_None; Py_INCREF(Py_None); - if (unlikely(__pyx_pw_7aiohttp_10_multidict_5_Base_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) { - Py_DECREF(o); o = 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_10_multidict__Base(PyObject *o) { - struct __pyx_obj_7aiohttp_10_multidict__Base *p = (struct __pyx_obj_7aiohttp_10_multidict__Base *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->_items); - Py_CLEAR(p->_upstr); - Py_CLEAR(p->marker); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_7aiohttp_10_multidict__Base(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_10_multidict__Base *p = (struct __pyx_obj_7aiohttp_10_multidict__Base *)o; - if (p->_items) { - e = (*v)(p->_items, a); if (e) return e; - } - if (p->_upstr) { - e = (*v)(p->_upstr, a); if (e) return e; - } - if (p->marker) { - e = (*v)(p->marker, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_10_multidict__Base(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_10_multidict__Base *p = (struct __pyx_obj_7aiohttp_10_multidict__Base *)o; - tmp = ((PyObject*)p->_items); - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_upstr); - p->_upstr = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->marker); - p->marker = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} -static PyObject *__pyx_sq_item_7aiohttp_10_multidict__Base(PyObject *o, Py_ssize_t i) { - PyObject *r; - PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; - r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); - Py_DECREF(x); - return r; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__Base[] = { - {"getall", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_5_Base_3getall, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_multidict_5_Base_2getall}, - {"getone", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_5_Base_5getone, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_multidict_5_Base_4getone}, - {"get", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_5_Base_9get, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_multidict_5_Base_8get}, - {"keys", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_5_Base_17keys, METH_NOARGS, __pyx_doc_7aiohttp_10_multidict_5_Base_16keys}, - {"items", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_5_Base_19items, METH_NOARGS, __pyx_doc_7aiohttp_10_multidict_5_Base_18items}, - {"values", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_5_Base_21values, METH_NOARGS, __pyx_doc_7aiohttp_10_multidict_5_Base_20values}, - {0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence__Base = { - __pyx_pw_7aiohttp_10_multidict_5_Base_15__len__, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - __pyx_sq_item_7aiohttp_10_multidict__Base, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - __pyx_pw_7aiohttp_10_multidict_5_Base_11__contains__, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping__Base = { - __pyx_pw_7aiohttp_10_multidict_5_Base_15__len__, /*mp_length*/ - __pyx_pw_7aiohttp_10_multidict_5_Base_7__getitem__, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__Base = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._Base", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__Base), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__Base, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_pw_7aiohttp_10_multidict_5_Base_23__repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence__Base, /*tp_as_sequence*/ - &__pyx_tp_as_mapping__Base, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__Base, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__Base, /*tp_clear*/ - __pyx_pw_7aiohttp_10_multidict_5_Base_25__richcmp__, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - __pyx_pw_7aiohttp_10_multidict_5_Base_13__iter__, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__Base, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__Base, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDictProxy __pyx_vtable_7aiohttp_10_multidict_MultiDictProxy; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict_MultiDictProxy(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy *p; - PyObject *o = __pyx_tp_new_7aiohttp_10_multidict__Base(t, a, k); - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7aiohttp_10_multidict__Base*)__pyx_vtabptr_7aiohttp_10_multidict_MultiDictProxy; - return o; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict_MultiDictProxy[] = { - {"copy", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_14MultiDictProxy_3copy, METH_NOARGS, __pyx_doc_7aiohttp_10_multidict_14MultiDictProxy_2copy}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict_MultiDictProxy = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict.MultiDictProxy", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict_MultiDictProxy), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__Base, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_23__repr__, /*tp_repr*/ - #else - 0, /*tp_repr*/ - #endif - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__Base, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__Base, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_13__iter__, /*tp_iter*/ - #else - 0, /*tp_iter*/ - #endif - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict_MultiDictProxy, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pw_7aiohttp_10_multidict_14MultiDictProxy_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict_MultiDictProxy, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict_CIMultiDictProxy __pyx_vtable_7aiohttp_10_multidict_CIMultiDictProxy; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict_CIMultiDictProxy(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *p; - PyObject *o = __pyx_tp_new_7aiohttp_10_multidict_MultiDictProxy(t, a, k); - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7aiohttp_10_multidict__Base*)__pyx_vtabptr_7aiohttp_10_multidict_CIMultiDictProxy; - return o; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict_CIMultiDictProxy[] = { - {"copy", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_16CIMultiDictProxy_3copy, METH_NOARGS, __pyx_doc_7aiohttp_10_multidict_16CIMultiDictProxy_2copy}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict_CIMultiDictProxy = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict.CIMultiDictProxy", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDictProxy), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__Base, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_23__repr__, /*tp_repr*/ - #else - 0, /*tp_repr*/ - #endif - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__Base, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__Base, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_13__iter__, /*tp_iter*/ - #else - 0, /*tp_iter*/ - #endif - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict_CIMultiDictProxy, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pw_7aiohttp_10_multidict_16CIMultiDictProxy_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict_CIMultiDictProxy, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict_MultiDict __pyx_vtable_7aiohttp_10_multidict_MultiDict; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict_MultiDict(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict_MultiDict *p; - PyObject *o = __pyx_tp_new_7aiohttp_10_multidict__Base(t, a, k); - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict_MultiDict *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7aiohttp_10_multidict__Base*)__pyx_vtabptr_7aiohttp_10_multidict_MultiDict; - return o; -} - -static int __pyx_mp_ass_subscript_7aiohttp_10_multidict_MultiDict(PyObject *o, PyObject *i, PyObject *v) { - if (v) { - return __pyx_pw_7aiohttp_10_multidict_9MultiDict_11__setitem__(o, i, v); - } - else { - return __pyx_pw_7aiohttp_10_multidict_9MultiDict_13__delitem__(o, i); - } -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict_MultiDict[] = { - {"add", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9MultiDict_3add, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_multidict_9MultiDict_2add}, - {"copy", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9MultiDict_5copy, METH_NOARGS, __pyx_doc_7aiohttp_10_multidict_9MultiDict_4copy}, - {"extend", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9MultiDict_7extend, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_multidict_9MultiDict_6extend}, - {"clear", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9MultiDict_9clear, METH_NOARGS, __pyx_doc_7aiohttp_10_multidict_9MultiDict_8clear}, - {"setdefault", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9MultiDict_15setdefault, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_multidict_9MultiDict_14setdefault}, - {"pop", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9MultiDict_17pop, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_multidict_9MultiDict_16pop}, - {"popitem", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9MultiDict_19popitem, METH_NOARGS, __pyx_doc_7aiohttp_10_multidict_9MultiDict_18popitem}, - {"update", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9MultiDict_21update, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_multidict_9MultiDict_20update}, - {0, 0, 0, 0} -}; - -static PyMappingMethods __pyx_tp_as_mapping_MultiDict = { - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_15__len__, /*mp_length*/ - #else - 0, /*mp_length*/ - #endif - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_7__getitem__, /*mp_subscript*/ - #else - 0, /*mp_subscript*/ - #endif - __pyx_mp_ass_subscript_7aiohttp_10_multidict_MultiDict, /*mp_ass_subscript*/ -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict_MultiDict = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict.MultiDict", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict_MultiDict), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__Base, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_23__repr__, /*tp_repr*/ - #else - 0, /*tp_repr*/ - #endif - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_MultiDict, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - "An ordered dictionary that can have multiple values for each key.", /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__Base, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__Base, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_13__iter__, /*tp_iter*/ - #else - 0, /*tp_iter*/ - #endif - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict_MultiDict, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pw_7aiohttp_10_multidict_9MultiDict_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict_MultiDict, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; -static struct __pyx_vtabstruct_7aiohttp_10_multidict_CIMultiDict __pyx_vtable_7aiohttp_10_multidict_CIMultiDict; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict_CIMultiDict(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict_CIMultiDict *p; - PyObject *o = __pyx_tp_new_7aiohttp_10_multidict_MultiDict(t, a, k); - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict_CIMultiDict *)o); - p->__pyx_base.__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7aiohttp_10_multidict__Base*)__pyx_vtabptr_7aiohttp_10_multidict_CIMultiDict; - return o; -} - -static PyTypeObject __pyx_type_7aiohttp_10_multidict_CIMultiDict = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict.CIMultiDict", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict_CIMultiDict), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__Base, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_23__repr__, /*tp_repr*/ - #else - 0, /*tp_repr*/ - #endif - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - "An ordered dictionary that can have multiple values for each key.", /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__Base, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__Base, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_5_Base_13__iter__, /*tp_iter*/ - #else - 0, /*tp_iter*/ - #endif - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_9MultiDict_1__init__, /*tp_init*/ - #else - 0, /*tp_init*/ - #endif - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict_CIMultiDict, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ViewBase(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict__ViewBase *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict__ViewBase *)o); - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - if (unlikely(__pyx_pw_7aiohttp_10_multidict_9_ViewBase_1__cinit__(o, a, k) < 0)) { - Py_DECREF(o); o = 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_10_multidict__ViewBase(PyObject *o) { - struct __pyx_obj_7aiohttp_10_multidict__ViewBase *p = (struct __pyx_obj_7aiohttp_10_multidict__ViewBase *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->_items); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_7aiohttp_10_multidict__ViewBase(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_10_multidict__ViewBase *p = (struct __pyx_obj_7aiohttp_10_multidict__ViewBase *)o; - if (p->_items) { - e = (*v)(p->_items, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_10_multidict__ViewBase(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_10_multidict__ViewBase *p = (struct __pyx_obj_7aiohttp_10_multidict__ViewBase *)o; - tmp = ((PyObject*)p->_items); - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__ViewBase[] = { - {0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence__ViewBase = { - __pyx_pw_7aiohttp_10_multidict_9_ViewBase_3__len__, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping__ViewBase = { - __pyx_pw_7aiohttp_10_multidict_9_ViewBase_3__len__, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__ViewBase = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._ViewBase", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__ViewBase), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__ViewBase, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence__ViewBase, /*tp_as_sequence*/ - &__pyx_tp_as_mapping__ViewBase, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__ViewBase, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__ViewBase, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__ViewBase, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__ViewBase, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ViewBaseSet(PyTypeObject *t, PyObject *a, PyObject *k) { - PyObject *o = __pyx_tp_new_7aiohttp_10_multidict__ViewBase(t, a, k); - if (unlikely(!o)) return 0; - return o; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__ViewBaseSet[] = { - {0, 0, 0, 0} -}; - -static PyNumberMethods __pyx_tp_as_number__ViewBaseSet = { - 0, /*nb_add*/ - __pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_7__sub__, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 || CYTHON_COMPILING_IN_PYPY - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - __pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_3__and__, /*nb_and*/ - __pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_9__xor__, /*nb_xor*/ - __pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_5__or__, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 || CYTHON_COMPILING_IN_PYPY - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 || CYTHON_COMPILING_IN_PYPY - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 || CYTHON_COMPILING_IN_PYPY - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 || CYTHON_COMPILING_IN_PYPY - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - 0, /*nb_index*/ - #if PY_VERSION_HEX >= 0x03050000 - 0, /*nb_matrix_multiply*/ - #endif - #if PY_VERSION_HEX >= 0x03050000 - 0, /*nb_inplace_matrix_multiply*/ - #endif -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__ViewBaseSet = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._ViewBaseSet", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__ViewBaseSet), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__ViewBase, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number__ViewBaseSet, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__ViewBase, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__ViewBase, /*tp_clear*/ - __pyx_pw_7aiohttp_10_multidict_12_ViewBaseSet_1__richcmp__, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__ViewBaseSet, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__ViewBaseSet, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ItemsIter(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *)o); - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - if (unlikely(__pyx_pw_7aiohttp_10_multidict_10_ItemsIter_1__cinit__(o, a, k) < 0)) { - Py_DECREF(o); o = 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_10_multidict__ItemsIter(PyObject *o) { - struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *p = (struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->_items); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_7aiohttp_10_multidict__ItemsIter(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *p = (struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *)o; - if (p->_items) { - e = (*v)(p->_items, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_10_multidict__ItemsIter(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *p = (struct __pyx_obj_7aiohttp_10_multidict__ItemsIter *)o; - tmp = ((PyObject*)p->_items); - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__ItemsIter[] = { - {"__next__", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_10_ItemsIter_5__next__, METH_NOARGS|METH_COEXIST, 0}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__ItemsIter = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._ItemsIter", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__ItemsIter), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__ItemsIter, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__ItemsIter, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__ItemsIter, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - __pyx_pw_7aiohttp_10_multidict_10_ItemsIter_3__iter__, /*tp_iter*/ - __pyx_pw_7aiohttp_10_multidict_10_ItemsIter_5__next__, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__ItemsIter, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__ItemsIter, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ItemsView(PyTypeObject *t, PyObject *a, PyObject *k) { - PyObject *o = __pyx_tp_new_7aiohttp_10_multidict__ViewBaseSet(t, a, k); - if (unlikely(!o)) return 0; - return o; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__ItemsView[] = { - {"isdisjoint", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_10_ItemsView_1isdisjoint, METH_O, __pyx_doc_7aiohttp_10_multidict_10_ItemsView_isdisjoint}, - {0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence__ItemsView = { - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_9_ViewBase_3__len__, /*sq_length*/ - #else - 0, /*sq_length*/ - #endif - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - __pyx_pw_7aiohttp_10_multidict_10_ItemsView_3__contains__, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__ItemsView = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._ItemsView", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__ItemsView), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__ViewBase, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_pw_7aiohttp_10_multidict_10_ItemsView_7__repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence__ItemsView, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__ViewBase, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__ViewBase, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - __pyx_pw_7aiohttp_10_multidict_10_ItemsView_5__iter__, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__ItemsView, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__ItemsView, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ValuesIter(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *)o); - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - if (unlikely(__pyx_pw_7aiohttp_10_multidict_11_ValuesIter_1__cinit__(o, a, k) < 0)) { - Py_DECREF(o); o = 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_10_multidict__ValuesIter(PyObject *o) { - struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *p = (struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->_items); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_7aiohttp_10_multidict__ValuesIter(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *p = (struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *)o; - if (p->_items) { - e = (*v)(p->_items, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_10_multidict__ValuesIter(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *p = (struct __pyx_obj_7aiohttp_10_multidict__ValuesIter *)o; - tmp = ((PyObject*)p->_items); - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__ValuesIter[] = { - {"__next__", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_11_ValuesIter_5__next__, METH_NOARGS|METH_COEXIST, 0}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__ValuesIter = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._ValuesIter", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__ValuesIter), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__ValuesIter, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__ValuesIter, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__ValuesIter, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - __pyx_pw_7aiohttp_10_multidict_11_ValuesIter_3__iter__, /*tp_iter*/ - __pyx_pw_7aiohttp_10_multidict_11_ValuesIter_5__next__, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__ValuesIter, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__ValuesIter, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__ValuesView(PyTypeObject *t, PyObject *a, PyObject *k) { - PyObject *o = __pyx_tp_new_7aiohttp_10_multidict__ViewBase(t, a, k); - if (unlikely(!o)) return 0; - return o; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__ValuesView[] = { - {0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence__ValuesView = { - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_9_ViewBase_3__len__, /*sq_length*/ - #else - 0, /*sq_length*/ - #endif - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - __pyx_pw_7aiohttp_10_multidict_11_ValuesView_1__contains__, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__ValuesView = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._ValuesView", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__ValuesView), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__ViewBase, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_pw_7aiohttp_10_multidict_11_ValuesView_5__repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence__ValuesView, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__ViewBase, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__ViewBase, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - __pyx_pw_7aiohttp_10_multidict_11_ValuesView_3__iter__, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__ValuesView, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__ValuesView, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__KeysIter(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_10_multidict__KeysIter *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_10_multidict__KeysIter *)o); - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - if (unlikely(__pyx_pw_7aiohttp_10_multidict_9_KeysIter_1__cinit__(o, a, k) < 0)) { - Py_DECREF(o); o = 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_10_multidict__KeysIter(PyObject *o) { - struct __pyx_obj_7aiohttp_10_multidict__KeysIter *p = (struct __pyx_obj_7aiohttp_10_multidict__KeysIter *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->_items); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_7aiohttp_10_multidict__KeysIter(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_10_multidict__KeysIter *p = (struct __pyx_obj_7aiohttp_10_multidict__KeysIter *)o; - if (p->_items) { - e = (*v)(p->_items, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_10_multidict__KeysIter(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_10_multidict__KeysIter *p = (struct __pyx_obj_7aiohttp_10_multidict__KeysIter *)o; - tmp = ((PyObject*)p->_items); - p->_items = ((PyObject*)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__KeysIter[] = { - {"__next__", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9_KeysIter_5__next__, METH_NOARGS|METH_COEXIST, 0}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__KeysIter = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._KeysIter", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__KeysIter), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__KeysIter, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__KeysIter, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__KeysIter, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - __pyx_pw_7aiohttp_10_multidict_9_KeysIter_3__iter__, /*tp_iter*/ - __pyx_pw_7aiohttp_10_multidict_9_KeysIter_5__next__, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__KeysIter, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__KeysIter, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; - -static PyObject *__pyx_tp_new_7aiohttp_10_multidict__KeysView(PyTypeObject *t, PyObject *a, PyObject *k) { - PyObject *o = __pyx_tp_new_7aiohttp_10_multidict__ViewBaseSet(t, a, k); - if (unlikely(!o)) return 0; - return o; -} - -static PyMethodDef __pyx_methods_7aiohttp_10_multidict__KeysView[] = { - {"isdisjoint", (PyCFunction)__pyx_pw_7aiohttp_10_multidict_9_KeysView_1isdisjoint, METH_O, __pyx_doc_7aiohttp_10_multidict_9_KeysView_isdisjoint}, - {0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence__KeysView = { - #if CYTHON_COMPILING_IN_PYPY - __pyx_pw_7aiohttp_10_multidict_9_ViewBase_3__len__, /*sq_length*/ - #else - 0, /*sq_length*/ - #endif - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - __pyx_pw_7aiohttp_10_multidict_9_KeysView_3__contains__, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyTypeObject __pyx_type_7aiohttp_10_multidict__KeysView = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._multidict._KeysView", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_10_multidict__KeysView), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_10_multidict__ViewBase, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_pw_7aiohttp_10_multidict_9_KeysView_7__repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence__KeysView, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_10_multidict__ViewBase, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_10_multidict__ViewBase, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - __pyx_pw_7aiohttp_10_multidict_9_KeysView_5__iter__, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_10_multidict__KeysView, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_10_multidict__KeysView, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -static struct PyModuleDef __pyx_moduledef = { - #if PY_VERSION_HEX < 0x03020000 - { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, - #else - PyModuleDef_HEAD_INIT, - #endif - "_multidict", - 0, /* m_doc */ - -1, /* m_size */ - __pyx_methods /* m_methods */, - NULL, /* m_reload */ - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_s_, __pyx_k_, sizeof(__pyx_k_), 0, 0, 1, 0}, - {&__pyx_kp_s_CIMultiDictProxy_requires_CIMult, __pyx_k_CIMultiDictProxy_requires_CIMult, sizeof(__pyx_k_CIMultiDictProxy_requires_CIMult), 0, 0, 1, 0}, - {&__pyx_kp_s_Case_insensitive_str, __pyx_k_Case_insensitive_str, sizeof(__pyx_k_Case_insensitive_str), 0, 0, 1, 0}, - {&__pyx_n_s_ItemsView, __pyx_k_ItemsView, sizeof(__pyx_k_ItemsView), 0, 0, 1, 1}, - {&__pyx_n_s_Iterable, __pyx_k_Iterable, sizeof(__pyx_k_Iterable), 0, 0, 1, 1}, - {&__pyx_n_s_KeyError, __pyx_k_KeyError, sizeof(__pyx_k_KeyError), 0, 0, 1, 1}, - {&__pyx_kp_s_Key_not_found_r, __pyx_k_Key_not_found_r, sizeof(__pyx_k_Key_not_found_r), 0, 0, 1, 0}, - {&__pyx_n_s_KeysView, __pyx_k_KeysView, sizeof(__pyx_k_KeysView), 0, 0, 1, 1}, - {&__pyx_n_s_Mapping, __pyx_k_Mapping, sizeof(__pyx_k_Mapping), 0, 0, 1, 1}, - {&__pyx_kp_s_MultiDictProxy_requires_MultiDic, __pyx_k_MultiDictProxy_requires_MultiDic, sizeof(__pyx_k_MultiDictProxy_requires_MultiDic), 0, 0, 1, 0}, - {&__pyx_n_s_MutableMapping, __pyx_k_MutableMapping, sizeof(__pyx_k_MutableMapping), 0, 0, 1, 1}, - {&__pyx_n_s_NotImplemented, __pyx_k_NotImplemented, sizeof(__pyx_k_NotImplemented), 0, 0, 1, 1}, - {&__pyx_n_s_Set, __pyx_k_Set, sizeof(__pyx_k_Set), 0, 0, 1, 1}, - {&__pyx_n_s_StopIteration, __pyx_k_StopIteration, sizeof(__pyx_k_StopIteration), 0, 0, 1, 1}, - {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, - {&__pyx_n_s_ValuesView, __pyx_k_ValuesView, sizeof(__pyx_k_ValuesView), 0, 0, 1, 1}, - {&__pyx_kp_s__4, __pyx_k__4, sizeof(__pyx_k__4), 0, 0, 1, 0}, - {&__pyx_kp_s__5, __pyx_k__5, sizeof(__pyx_k__5), 0, 0, 1, 0}, - {&__pyx_kp_s__8, __pyx_k__8, sizeof(__pyx_k__8), 0, 0, 1, 0}, - {&__pyx_n_s_abc, __pyx_k_abc, sizeof(__pyx_k_abc), 0, 0, 1, 1}, - {&__pyx_n_s_aiohttp__multidict, __pyx_k_aiohttp__multidict, sizeof(__pyx_k_aiohttp__multidict), 0, 0, 1, 1}, - {&__pyx_n_s_arg, __pyx_k_arg, sizeof(__pyx_k_arg), 0, 0, 1, 1}, - {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, - {&__pyx_n_s_clear, __pyx_k_clear, sizeof(__pyx_k_clear), 0, 0, 1, 1}, - {&__pyx_n_s_cls, __pyx_k_cls, sizeof(__pyx_k_cls), 0, 0, 1, 1}, - {&__pyx_n_s_collections, __pyx_k_collections, sizeof(__pyx_k_collections), 0, 0, 1, 1}, - {&__pyx_n_s_collections_abc, __pyx_k_collections_abc, sizeof(__pyx_k_collections_abc), 0, 0, 1, 1}, - {&__pyx_n_s_default, __pyx_k_default, sizeof(__pyx_k_default), 0, 0, 1, 1}, - {&__pyx_n_s_doc, __pyx_k_doc, sizeof(__pyx_k_doc), 0, 0, 1, 1}, - {&__pyx_kp_s_empty_multidict, __pyx_k_empty_multidict, sizeof(__pyx_k_empty_multidict), 0, 0, 1, 0}, - {&__pyx_n_s_encoding, __pyx_k_encoding, sizeof(__pyx_k_encoding), 0, 0, 1, 1}, - {&__pyx_n_s_errors, __pyx_k_errors, sizeof(__pyx_k_errors), 0, 0, 1, 1}, - {&__pyx_n_s_extend, __pyx_k_extend, sizeof(__pyx_k_extend), 0, 0, 1, 1}, - {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, - {&__pyx_n_s_get, __pyx_k_get, sizeof(__pyx_k_get), 0, 0, 1, 1}, - {&__pyx_n_s_getdefaultencoding, __pyx_k_getdefaultencoding, sizeof(__pyx_k_getdefaultencoding), 0, 0, 1, 1}, - {&__pyx_kp_s_home_andrew_projects_aiohttp_ai, __pyx_k_home_andrew_projects_aiohttp_ai, sizeof(__pyx_k_home_andrew_projects_aiohttp_ai), 0, 0, 1, 0}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_s_itemgetter, __pyx_k_itemgetter, sizeof(__pyx_k_itemgetter), 0, 0, 1, 1}, - {&__pyx_n_s_items, __pyx_k_items, sizeof(__pyx_k_items), 0, 0, 1, 1}, - {&__pyx_n_s_join, __pyx_k_join, sizeof(__pyx_k_join), 0, 0, 1, 1}, - {&__pyx_n_s_key, __pyx_k_key, sizeof(__pyx_k_key), 0, 0, 1, 1}, - {&__pyx_n_s_keys, __pyx_k_keys, sizeof(__pyx_k_keys), 0, 0, 1, 1}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_marker, __pyx_k_marker, sizeof(__pyx_k_marker), 0, 0, 1, 1}, - {&__pyx_n_s_memoryview, __pyx_k_memoryview, sizeof(__pyx_k_memoryview), 0, 0, 1, 1}, - {&__pyx_n_s_metaclass, __pyx_k_metaclass, sizeof(__pyx_k_metaclass), 0, 0, 1, 1}, - {&__pyx_n_s_module, __pyx_k_module, sizeof(__pyx_k_module), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, - {&__pyx_n_s_object, __pyx_k_object, sizeof(__pyx_k_object), 0, 0, 1, 1}, - {&__pyx_n_s_operator, __pyx_k_operator, sizeof(__pyx_k_operator), 0, 0, 1, 1}, - {&__pyx_n_s_pop, __pyx_k_pop, sizeof(__pyx_k_pop), 0, 0, 1, 1}, - {&__pyx_n_s_prepare, __pyx_k_prepare, sizeof(__pyx_k_prepare), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, - {&__pyx_n_s_qualname, __pyx_k_qualname, sizeof(__pyx_k_qualname), 0, 0, 1, 1}, - {&__pyx_kp_s_r, __pyx_k_r, sizeof(__pyx_k_r), 0, 0, 1, 0}, - {&__pyx_kp_s_r_2, __pyx_k_r_2, sizeof(__pyx_k_r_2), 0, 0, 1, 0}, - {&__pyx_kp_s_r_r, __pyx_k_r_r, sizeof(__pyx_k_r_r), 0, 0, 1, 0}, - {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, - {&__pyx_n_s_register, __pyx_k_register, sizeof(__pyx_k_register), 0, 0, 1, 1}, - {&__pyx_n_s_self, __pyx_k_self, sizeof(__pyx_k_self), 0, 0, 1, 1}, - {&__pyx_n_s_strict, __pyx_k_strict, sizeof(__pyx_k_strict), 0, 0, 1, 1}, - {&__pyx_n_s_sys, __pyx_k_sys, sizeof(__pyx_k_sys), 0, 0, 1, 1}, - {&__pyx_kp_s_takes_at_most_1_positional_argu, __pyx_k_takes_at_most_1_positional_argu, sizeof(__pyx_k_takes_at_most_1_positional_argu), 0, 0, 1, 0}, - {&__pyx_kp_s_takes_either_dict_or_list_of_ke, __pyx_k_takes_either_dict_or_list_of_ke, sizeof(__pyx_k_takes_either_dict_or_list_of_ke), 0, 0, 1, 0}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, - {&__pyx_n_s_upper, __pyx_k_upper, sizeof(__pyx_k_upper), 0, 0, 1, 1}, - {&__pyx_n_s_upstr, __pyx_k_upstr, sizeof(__pyx_k_upstr), 0, 0, 1, 1}, - {&__pyx_n_s_upstr___new, __pyx_k_upstr___new, sizeof(__pyx_k_upstr___new), 0, 0, 1, 1}, - {&__pyx_n_s_upstr_upper, __pyx_k_upstr_upper, sizeof(__pyx_k_upstr_upper), 0, 0, 1, 1}, - {&__pyx_n_s_val, __pyx_k_val, sizeof(__pyx_k_val), 0, 0, 1, 1}, - {&__pyx_n_s_value, __pyx_k_value, sizeof(__pyx_k_value), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_object = __Pyx_GetBuiltinName(__pyx_n_s_object); if (!__pyx_builtin_object) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_memoryview = __Pyx_GetBuiltinName(__pyx_n_s_memoryview); if (!__pyx_builtin_memoryview) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_NotImplemented = __Pyx_GetBuiltinName(__pyx_n_s_NotImplemented); if (!__pyx_builtin_NotImplemented) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_KeyError = __Pyx_GetBuiltinName(__pyx_n_s_KeyError); if (!__pyx_builtin_KeyError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 98; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 343; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_StopIteration = __Pyx_GetBuiltinName(__pyx_n_s_StopIteration); if (!__pyx_builtin_StopIteration) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - return 0; - __pyx_L1_error:; - return -1; -} - -static int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "aiohttp/_multidict.pyx":398 - * return (item._key, item._value) - * else: - * raise KeyError("empty multidict") # <<<<<<<<<<<<<< - * - * def update(self, *args, **kwargs): - */ - __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_empty_multidict); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__7); - __Pyx_GIVEREF(__pyx_tuple__7); - - /* "aiohttp/_multidict.pyx":14 - * """Case insensitive str.""" - * - * def __new__(cls, val='', # <<<<<<<<<<<<<< - * encoding=sys.getdefaultencoding(), errors='strict'): - * if isinstance(val, (bytes, bytearray, memoryview)): - */ - __pyx_tuple__9 = PyTuple_Pack(4, __pyx_n_s_cls, __pyx_n_s_val, __pyx_n_s_encoding, __pyx_n_s_errors); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__9); - __Pyx_GIVEREF(__pyx_tuple__9); - __pyx_codeobj__10 = (PyObject*)__Pyx_PyCode_New(4, 0, 4, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__9, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_andrew_projects_aiohttp_ai, __pyx_n_s_new, 14, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":25 - * return str.__new__(cls, val) - * - * def upper(self): # <<<<<<<<<<<<<< - * return self - * - */ - __pyx_tuple__11 = PyTuple_Pack(1, __pyx_n_s_self); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__11); - __Pyx_GIVEREF(__pyx_tuple__11); - __pyx_codeobj__12 = (PyObject*)__Pyx_PyCode_New(1, 0, 1, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__11, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_andrew_projects_aiohttp_ai, __pyx_n_s_upper, 25, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_InitGlobals(void) { - __pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_int_3 = PyInt_FromLong(3); if (unlikely(!__pyx_int_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_int_4 = PyInt_FromLong(4); if (unlikely(!__pyx_int_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_int_5 = PyInt_FromLong(5); if (unlikely(!__pyx_int_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - return 0; - __pyx_L1_error:; - return -1; -} - -#if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC init_multidict(void); /*proto*/ -PyMODINIT_FUNC init_multidict(void) -#else -PyMODINIT_FUNC PyInit__multidict(void); /*proto*/ -PyMODINIT_FUNC PyInit__multidict(void) -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - #if CYTHON_REFNANNY - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); - if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); - } - #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__multidict(void)", 0); - if (__Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4("_multidict", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #if CYTHON_COMPILING_IN_PYPY - Py_INCREF(__pyx_b); - #endif - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - if (__pyx_module_is_main_aiohttp___multidict) { - if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (!PyDict_GetItemString(modules, "aiohttp._multidict")) { - if (unlikely(PyDict_SetItemString(modules, "aiohttp._multidict", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Global init code ---*/ - /*--- Variable export code ---*/ - /*--- Function export code ---*/ - /*--- Type init code ---*/ - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__Pair) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__Pair.tp_print = 0; - if (PyObject_SetAttrString(__pyx_m, "_Pair", (PyObject *)&__pyx_type_7aiohttp_10_multidict__Pair) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__Pair = &__pyx_type_7aiohttp_10_multidict__Pair; - __pyx_vtabptr_7aiohttp_10_multidict__Base = &__pyx_vtable_7aiohttp_10_multidict__Base; - __pyx_vtable_7aiohttp_10_multidict__Base._upper = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *))__pyx_f_7aiohttp_10_multidict_5_Base__upper; - __pyx_vtable_7aiohttp_10_multidict__Base._getall = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *, PyObject *))__pyx_f_7aiohttp_10_multidict_5_Base__getall; - __pyx_vtable_7aiohttp_10_multidict__Base._getone = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *, PyObject *))__pyx_f_7aiohttp_10_multidict_5_Base__getone; - __pyx_vtable_7aiohttp_10_multidict__Base._contains = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *))__pyx_f_7aiohttp_10_multidict_5_Base__contains; - __pyx_vtable_7aiohttp_10_multidict__Base.keys = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict__Base *, int __pyx_skip_dispatch))__pyx_f_7aiohttp_10_multidict_5_Base_keys; - __pyx_vtable_7aiohttp_10_multidict__Base._eq_to_mapping = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *))__pyx_f_7aiohttp_10_multidict_5_Base__eq_to_mapping; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__Base) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__Base.tp_print = 0; - if (__Pyx_SetVtable(__pyx_type_7aiohttp_10_multidict__Base.tp_dict, __pyx_vtabptr_7aiohttp_10_multidict__Base) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyObject_SetAttrString(__pyx_m, "_Base", (PyObject *)&__pyx_type_7aiohttp_10_multidict__Base) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 66; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__Base = &__pyx_type_7aiohttp_10_multidict__Base; - __pyx_vtabptr_7aiohttp_10_multidict_MultiDictProxy = &__pyx_vtable_7aiohttp_10_multidict_MultiDictProxy; - __pyx_vtable_7aiohttp_10_multidict_MultiDictProxy.__pyx_base = *__pyx_vtabptr_7aiohttp_10_multidict__Base; - __pyx_type_7aiohttp_10_multidict_MultiDictProxy.tp_base = __pyx_ptype_7aiohttp_10_multidict__Base; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict_MultiDictProxy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict_MultiDictProxy.tp_print = 0; - if (__Pyx_SetVtable(__pyx_type_7aiohttp_10_multidict_MultiDictProxy.tp_dict, __pyx_vtabptr_7aiohttp_10_multidict_MultiDictProxy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyObject_SetAttrString(__pyx_m, "MultiDictProxy", (PyObject *)&__pyx_type_7aiohttp_10_multidict_MultiDictProxy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict_MultiDictProxy = &__pyx_type_7aiohttp_10_multidict_MultiDictProxy; - __pyx_vtabptr_7aiohttp_10_multidict_CIMultiDictProxy = &__pyx_vtable_7aiohttp_10_multidict_CIMultiDictProxy; - __pyx_vtable_7aiohttp_10_multidict_CIMultiDictProxy.__pyx_base = *__pyx_vtabptr_7aiohttp_10_multidict_MultiDictProxy; - __pyx_vtable_7aiohttp_10_multidict_CIMultiDictProxy.__pyx_base.__pyx_base._upper = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *))__pyx_f_7aiohttp_10_multidict_16CIMultiDictProxy__upper; - __pyx_type_7aiohttp_10_multidict_CIMultiDictProxy.tp_base = __pyx_ptype_7aiohttp_10_multidict_MultiDictProxy; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict_CIMultiDictProxy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict_CIMultiDictProxy.tp_print = 0; - if (__Pyx_SetVtable(__pyx_type_7aiohttp_10_multidict_CIMultiDictProxy.tp_dict, __pyx_vtabptr_7aiohttp_10_multidict_CIMultiDictProxy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyObject_SetAttrString(__pyx_m, "CIMultiDictProxy", (PyObject *)&__pyx_type_7aiohttp_10_multidict_CIMultiDictProxy) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict_CIMultiDictProxy = &__pyx_type_7aiohttp_10_multidict_CIMultiDictProxy; - __pyx_vtabptr_7aiohttp_10_multidict_MultiDict = &__pyx_vtable_7aiohttp_10_multidict_MultiDict; - __pyx_vtable_7aiohttp_10_multidict_MultiDict.__pyx_base = *__pyx_vtabptr_7aiohttp_10_multidict__Base; - __pyx_vtable_7aiohttp_10_multidict_MultiDict._extend = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *, PyObject *, PyObject *, PyObject *, int))__pyx_f_7aiohttp_10_multidict_9MultiDict__extend; - __pyx_vtable_7aiohttp_10_multidict_MultiDict._add = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *, PyObject *, PyObject *))__pyx_f_7aiohttp_10_multidict_9MultiDict__add; - __pyx_vtable_7aiohttp_10_multidict_MultiDict._replace = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *, PyObject *, PyObject *))__pyx_f_7aiohttp_10_multidict_9MultiDict__replace; - __pyx_vtable_7aiohttp_10_multidict_MultiDict._remove = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict_MultiDict *, PyObject *, int))__pyx_f_7aiohttp_10_multidict_9MultiDict__remove; - __pyx_type_7aiohttp_10_multidict_MultiDict.tp_base = __pyx_ptype_7aiohttp_10_multidict__Base; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict_MultiDict) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict_MultiDict.tp_print = 0; - if (__Pyx_SetVtable(__pyx_type_7aiohttp_10_multidict_MultiDict.tp_dict, __pyx_vtabptr_7aiohttp_10_multidict_MultiDict) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyObject_SetAttrString(__pyx_m, "MultiDict", (PyObject *)&__pyx_type_7aiohttp_10_multidict_MultiDict) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict_MultiDict = &__pyx_type_7aiohttp_10_multidict_MultiDict; - __pyx_vtabptr_7aiohttp_10_multidict_CIMultiDict = &__pyx_vtable_7aiohttp_10_multidict_CIMultiDict; - __pyx_vtable_7aiohttp_10_multidict_CIMultiDict.__pyx_base = *__pyx_vtabptr_7aiohttp_10_multidict_MultiDict; - __pyx_vtable_7aiohttp_10_multidict_CIMultiDict.__pyx_base.__pyx_base._upper = (PyObject *(*)(struct __pyx_obj_7aiohttp_10_multidict__Base *, PyObject *))__pyx_f_7aiohttp_10_multidict_11CIMultiDict__upper; - __pyx_type_7aiohttp_10_multidict_CIMultiDict.tp_base = __pyx_ptype_7aiohttp_10_multidict_MultiDict; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict_CIMultiDict) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict_CIMultiDict.tp_print = 0; - if (__Pyx_SetVtable(__pyx_type_7aiohttp_10_multidict_CIMultiDict.tp_dict, __pyx_vtabptr_7aiohttp_10_multidict_CIMultiDict) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyObject_SetAttrString(__pyx_m, "CIMultiDict", (PyObject *)&__pyx_type_7aiohttp_10_multidict_CIMultiDict) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict_CIMultiDict = &__pyx_type_7aiohttp_10_multidict_CIMultiDict; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__ViewBase) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__ViewBase.tp_print = 0; - if (PyObject_SetAttrString(__pyx_m, "_ViewBase", (PyObject *)&__pyx_type_7aiohttp_10_multidict__ViewBase) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__ViewBase = &__pyx_type_7aiohttp_10_multidict__ViewBase; - __pyx_type_7aiohttp_10_multidict__ViewBaseSet.tp_base = __pyx_ptype_7aiohttp_10_multidict__ViewBase; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__ViewBaseSet) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__ViewBaseSet.tp_print = 0; - if (PyObject_SetAttrString(__pyx_m, "_ViewBaseSet", (PyObject *)&__pyx_type_7aiohttp_10_multidict__ViewBaseSet) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__ViewBaseSet = &__pyx_type_7aiohttp_10_multidict__ViewBaseSet; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__ItemsIter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__ItemsIter.tp_print = 0; - if (PyObject_SetAttrString(__pyx_m, "_ItemsIter", (PyObject *)&__pyx_type_7aiohttp_10_multidict__ItemsIter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__ItemsIter = &__pyx_type_7aiohttp_10_multidict__ItemsIter; - __pyx_type_7aiohttp_10_multidict__ItemsView.tp_base = __pyx_ptype_7aiohttp_10_multidict__ViewBaseSet; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__ItemsView) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__ItemsView.tp_print = 0; - if (PyObject_SetAttrString(__pyx_m, "_ItemsView", (PyObject *)&__pyx_type_7aiohttp_10_multidict__ItemsView) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__ItemsView = &__pyx_type_7aiohttp_10_multidict__ItemsView; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__ValuesIter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__ValuesIter.tp_print = 0; - if (PyObject_SetAttrString(__pyx_m, "_ValuesIter", (PyObject *)&__pyx_type_7aiohttp_10_multidict__ValuesIter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__ValuesIter = &__pyx_type_7aiohttp_10_multidict__ValuesIter; - __pyx_type_7aiohttp_10_multidict__ValuesView.tp_base = __pyx_ptype_7aiohttp_10_multidict__ViewBase; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__ValuesView) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__ValuesView.tp_print = 0; - if (PyObject_SetAttrString(__pyx_m, "_ValuesView", (PyObject *)&__pyx_type_7aiohttp_10_multidict__ValuesView) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__ValuesView = &__pyx_type_7aiohttp_10_multidict__ValuesView; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__KeysIter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__KeysIter.tp_print = 0; - if (PyObject_SetAttrString(__pyx_m, "_KeysIter", (PyObject *)&__pyx_type_7aiohttp_10_multidict__KeysIter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__KeysIter = &__pyx_type_7aiohttp_10_multidict__KeysIter; - __pyx_type_7aiohttp_10_multidict__KeysView.tp_base = __pyx_ptype_7aiohttp_10_multidict__ViewBaseSet; - if (PyType_Ready(&__pyx_type_7aiohttp_10_multidict__KeysView) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 621; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_type_7aiohttp_10_multidict__KeysView.tp_print = 0; - if (PyObject_SetAttrString(__pyx_m, "_KeysView", (PyObject *)&__pyx_type_7aiohttp_10_multidict__KeysView) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 621; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7aiohttp_10_multidict__KeysView = &__pyx_type_7aiohttp_10_multidict__KeysView; - /*--- Type import code ---*/ - /*--- Variable import code ---*/ - /*--- Function import code ---*/ - /*--- Execution code ---*/ - #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - - /* "aiohttp/_multidict.pyx":1 - * import sys # <<<<<<<<<<<<<< - * from collections import abc - * from collections.abc import Iterable, Set - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_sys, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_sys, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":2 - * import sys - * from collections import abc # <<<<<<<<<<<<<< - * from collections.abc import Iterable, Set - * from operator import itemgetter - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_abc); - __Pyx_GIVEREF(__pyx_n_s_abc); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_abc); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_collections, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_abc); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_abc, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":3 - * import sys - * from collections import abc - * from collections.abc import Iterable, Set # <<<<<<<<<<<<<< - * from operator import itemgetter - * - */ - __pyx_t_2 = PyList_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_Iterable); - __Pyx_GIVEREF(__pyx_n_s_Iterable); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_Iterable); - __Pyx_INCREF(__pyx_n_s_Set); - __Pyx_GIVEREF(__pyx_n_s_Set); - PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_Set); - __pyx_t_1 = __Pyx_Import(__pyx_n_s_collections_abc, __pyx_t_2, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_Iterable); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_Iterable, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_Set); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_Set, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_multidict.pyx":4 - * from collections import abc - * from collections.abc import Iterable, Set - * from operator import itemgetter # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_itemgetter); - __Pyx_GIVEREF(__pyx_n_s_itemgetter); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_itemgetter); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_operator, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_itemgetter); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_itemgetter, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":7 - * - * - * _marker = object() # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = __Pyx_PyObject_CallNoArg(__pyx_builtin_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_marker, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":10 - * - * - * class upstr(str): # <<<<<<<<<<<<<< - * - * """Case insensitive str.""" - */ - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)(&PyString_Type))); - __Pyx_GIVEREF(((PyObject *)(&PyString_Type))); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)(&PyString_Type))); - __pyx_t_1 = __Pyx_CalculateMetaclass(NULL, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_Py3MetaclassPrepare(__pyx_t_1, __pyx_t_2, __pyx_n_s_upstr, __pyx_n_s_upstr, (PyObject *) NULL, __pyx_n_s_aiohttp__multidict, __pyx_kp_s_Case_insensitive_str); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - - /* "aiohttp/_multidict.pyx":14 - * """Case insensitive str.""" - * - * def __new__(cls, val='', # <<<<<<<<<<<<<< - * encoding=sys.getdefaultencoding(), errors='strict'): - * if isinstance(val, (bytes, bytearray, memoryview)): - */ - __pyx_t_4 = __Pyx_CyFunction_NewEx(&__pyx_mdef_7aiohttp_10_multidict_5upstr_1__new__, __Pyx_CYFUNCTION_STATICMETHOD, __pyx_n_s_upstr___new, NULL, __pyx_n_s_aiohttp__multidict, __pyx_d, ((PyObject *)__pyx_codeobj__10)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (!__Pyx_CyFunction_InitDefaults(__pyx_t_4, sizeof(__pyx_defaults), 1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "aiohttp/_multidict.pyx":15 - * - * def __new__(cls, val='', - * encoding=sys.getdefaultencoding(), errors='strict'): # <<<<<<<<<<<<<< - * if isinstance(val, (bytes, bytearray, memoryview)): - * val = str(val, encoding, errors) - */ - __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_sys); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_getdefaultencoding); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - if (__pyx_t_6) { - __pyx_t_5 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else { - __pyx_t_5 = __Pyx_PyObject_CallNoArg(__pyx_t_7); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_CyFunction_Defaults(__pyx_defaults, __pyx_t_4)->__pyx_arg_encoding = __pyx_t_5; - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __Pyx_CyFunction_SetDefaultsGetter(__pyx_t_4, __pyx_pf_7aiohttp_10_multidict_5upstr_4__defaults__); - if (PyObject_SetItem(__pyx_t_3, __pyx_n_s_new, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":25 - * return str.__new__(cls, val) - * - * def upper(self): # <<<<<<<<<<<<<< - * return self - * - */ - __pyx_t_4 = __Pyx_CyFunction_NewEx(&__pyx_mdef_7aiohttp_10_multidict_5upstr_3upper, 0, __pyx_n_s_upstr_upper, NULL, __pyx_n_s_aiohttp__multidict, __pyx_d, ((PyObject *)__pyx_codeobj__12)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyObject_SetItem(__pyx_t_3, __pyx_n_s_upper, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "aiohttp/_multidict.pyx":10 - * - * - * class upstr(str): # <<<<<<<<<<<<<< - * - * """Case insensitive str.""" - */ - __pyx_t_4 = __Pyx_Py3ClassCreate(__pyx_t_1, __pyx_n_s_upstr, __pyx_t_2, __pyx_t_3, NULL, 0, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_upstr, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":81 - * return s - * - * def getall(self, key, default=_marker): # <<<<<<<<<<<<<< - * """Return a list of all values matching the key.""" - * return self._getall(self._upper(key), default) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_marker); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 81; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_k__2 = __pyx_t_2; - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":100 - * raise KeyError('Key not found: %r' % key) - * - * def getone(self, key, default=_marker): # <<<<<<<<<<<<<< - * """Get first value matching the key.""" - * return self._getone(self._upper(key), default) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_marker); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 100; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_k__3 = __pyx_t_2; - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":210 - * return MultiDict(self._items) - * - * abc.Mapping.register(MultiDictProxy) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_abc); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_Mapping); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_register); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - if (!__pyx_t_3) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict_MultiDictProxy)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - } else { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; - __Pyx_INCREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_MultiDictProxy)); - __Pyx_GIVEREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_MultiDictProxy)); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict_MultiDictProxy)); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 210; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":235 - * - * - * abc.Mapping.register(CIMultiDictProxy) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_abc); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_Mapping); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_register); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - if (!__pyx_t_4) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict_CIMultiDictProxy)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - } else { - __pyx_t_3 = PyTuple_New(1+1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __pyx_t_4 = NULL; - __Pyx_INCREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_CIMultiDictProxy)); - __Pyx_GIVEREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_CIMultiDictProxy)); - PyTuple_SET_ITEM(__pyx_t_3, 0+1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict_CIMultiDictProxy)); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":363 - * return default - * - * def pop(self, key, default=_marker): # <<<<<<<<<<<<<< - * """Remove specified key and return the corresponding value. - * - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_marker); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_k__6 = __pyx_t_2; - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":405 - * - * - * abc.MutableMapping.register(MultiDict) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_abc); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 405; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_MutableMapping); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 405; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_register); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 405; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - if (!__pyx_t_3) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict_MultiDict)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 405; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - } else { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 405; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; - __Pyx_INCREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_MultiDict)); - __Pyx_GIVEREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_MultiDict)); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict_MultiDict)); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 405; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":418 - * - * - * abc.MutableMapping.register(CIMultiDict) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_abc); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_MutableMapping); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_register); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - if (!__pyx_t_4) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict_CIMultiDict)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - } else { - __pyx_t_3 = PyTuple_New(1+1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __pyx_t_4 = NULL; - __Pyx_INCREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_CIMultiDict)); - __Pyx_GIVEREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict_CIMultiDict)); - PyTuple_SET_ITEM(__pyx_t_3, 0+1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict_CIMultiDict)); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":550 - * - * - * abc.ItemsView.register(_ItemsView) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_abc); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ItemsView); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_register); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - if (!__pyx_t_3) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict__ItemsView)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - } else { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; - __Pyx_INCREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict__ItemsView)); - __Pyx_GIVEREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict__ItemsView)); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict__ItemsView)); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 550; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":597 - * - * - * abc.ValuesView.register(_ValuesView) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_abc); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ValuesView); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_register); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - if (!__pyx_t_4) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict__ValuesView)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - } else { - __pyx_t_3 = PyTuple_New(1+1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __pyx_t_4 = NULL; - __Pyx_INCREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict__ValuesView)); - __Pyx_GIVEREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict__ValuesView)); - PyTuple_SET_ITEM(__pyx_t_3, 0+1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict__ValuesView)); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":653 - * - * - * abc.KeysView.register(_KeysView) # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_abc); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_KeysView); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_register); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - if (!__pyx_t_3) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict__KeysView)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - } else { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; - __Pyx_INCREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict__KeysView)); - __Pyx_GIVEREF(((PyObject *)__pyx_ptype_7aiohttp_10_multidict__KeysView)); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, ((PyObject *)__pyx_ptype_7aiohttp_10_multidict__KeysView)); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_4, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_multidict.pyx":1 - * import sys # <<<<<<<<<<<<<< - * from collections import abc - * from collections.abc import Iterable, Set - */ - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init aiohttp._multidict", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_DECREF(__pyx_m); __pyx_m = 0; - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init aiohttp._multidict"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if PY_MAJOR_VERSION < 3 - return; - #else - return __pyx_m; - #endif -} - -/* --- Runtime support code --- */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule((char *)modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif - -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = func->ob_type->tp_call; - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#ifdef __Pyx_CyFunction_USED - if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { -#else - if (likely(PyCFunction_Check(func))) { -#endif - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - return __Pyx_PyObject_CallMethO(func, arg); - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_Pack(1, arg); - if (unlikely(!args)) return NULL; - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -#endif - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { -#ifdef __Pyx_CyFunction_USED - if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { -#else - if (likely(PyCFunction_Check(func))) { -#endif - if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { - return __Pyx_PyObject_CallMethO(func, NULL); - } - } - return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); -} -#endif - -static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { - PyObject *result; -#if CYTHON_COMPILING_IN_CPYTHON - result = PyDict_GetItem(__pyx_d, name); - if (likely(result)) { - Py_INCREF(result); - } else { -#else - result = PyObject_GetItem(__pyx_d, name); - if (!result) { - PyErr_Clear(); -#endif - result = __Pyx_GetBuiltinName(name); - } - return result; -} - -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" -#endif - -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { - if (op1 == op2) { - Py_RETURN_TRUE; - } - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op1))) { - const long b = intval; - long a = PyInt_AS_LONG(op1); - if (a == b) { - Py_RETURN_TRUE; - } else { - Py_RETURN_FALSE; - } - } - #endif - #if CYTHON_USE_PYLONG_INTERNALS && PY_MAJOR_VERSION >= 3 - if (likely(PyLong_CheckExact(op1))) { - const long b = intval; - long a; - const digit* digits = ((PyLongObject*)op1)->ob_digit; - const Py_ssize_t size = Py_SIZE(op1); - if (likely(__Pyx_sst_abs(size) <= 1)) { - a = likely(size) ? digits[0] : 0; - if (size == -1) a = -a; - } else { - switch (size) { - case -2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - case 2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - case -3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - case 3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - case -4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - case 4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - #if PyLong_SHIFT < 30 && PyLong_SHIFT != 15 - default: return PyLong_Type.tp_richcompare(op1, op2, Py_EQ); - #else - default: Py_RETURN_FALSE; - #endif - } - } - if (a == b) { - Py_RETURN_TRUE; - } else { - Py_RETURN_FALSE; - } - } - #endif - if (PyFloat_CheckExact(op1)) { - const long b = intval; - double a = PyFloat_AS_DOUBLE(op1); - if ((double)a == (double)b) { - Py_RETURN_TRUE; - } else { - Py_RETURN_FALSE; - } - } - return PyObject_RichCompare(op1, op2, Py_EQ); -} -#endif - -static CYTHON_INLINE int __Pyx_CheckKeywordStrings( - PyObject *kwdict, - const char* function_name, - int kw_allowed) -{ - PyObject* key = 0; - Py_ssize_t pos = 0; -#if CYTHON_COMPILING_IN_PYPY - if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0)) - goto invalid_keyword; - return 1; -#else - while (PyDict_Next(kwdict, &pos, &key, 0)) { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) - #endif - if (unlikely(!PyUnicode_Check(key))) - goto invalid_keyword_type; - } - if ((!kw_allowed) && unlikely(key)) - goto invalid_keyword; - return 1; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - return 0; -#endif -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif - return 0; -} - -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else - if (s1 == s2) { - return (equals == Py_EQ); - } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { - const char *ps1, *ps2; - Py_ssize_t length = PyBytes_GET_SIZE(s1); - if (length != PyBytes_GET_SIZE(s2)) - return (equals == Py_NE); - ps1 = PyBytes_AS_STRING(s1); - ps2 = PyBytes_AS_STRING(s2); - if (ps1[0] != ps2[0]) { - return (equals == Py_NE); - } else if (length == 1) { - return (equals == Py_EQ); - } else { - int result = memcmp(ps1, ps2, (size_t)length); - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { - return (equals == Py_NE); - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -#endif -} - -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else -#if PY_MAJOR_VERSION < 3 - PyObject* owned_ref = NULL; -#endif - int s1_is_unicode, s2_is_unicode; - if (s1 == s2) { - goto return_eq; - } - s1_is_unicode = PyUnicode_CheckExact(s1); - s2_is_unicode = PyUnicode_CheckExact(s2); -#if PY_MAJOR_VERSION < 3 - if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { - owned_ref = PyUnicode_FromObject(s2); - if (unlikely(!owned_ref)) - return -1; - s2 = owned_ref; - s2_is_unicode = 1; - } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { - owned_ref = PyUnicode_FromObject(s1); - if (unlikely(!owned_ref)) - return -1; - s1 = owned_ref; - s1_is_unicode = 1; - } else if (((!s2_is_unicode) & (!s1_is_unicode))) { - return __Pyx_PyBytes_Equals(s1, s2, equals); - } -#endif - if (s1_is_unicode & s2_is_unicode) { - Py_ssize_t length; - int kind; - void *data1, *data2; - if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) - return -1; - length = __Pyx_PyUnicode_GET_LENGTH(s1); - if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { - goto return_ne; - } - kind = __Pyx_PyUnicode_KIND(s1); - if (kind != __Pyx_PyUnicode_KIND(s2)) { - goto return_ne; - } - data1 = __Pyx_PyUnicode_DATA(s1); - data2 = __Pyx_PyUnicode_DATA(s2); - if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { - goto return_ne; - } else if (length == 1) { - goto return_eq; - } else { - int result = memcmp(data1, data2, (size_t)(length * kind)); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & s2_is_unicode) { - goto return_ne; - } else if ((s2 == Py_None) & s1_is_unicode) { - goto return_ne; - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -return_eq: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ); -return_ne: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_NE); -#endif -} - -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_Restore(type, value, tb); -#endif -} -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(type, value, tb); -#endif -} - -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - if (PyType_Check(type)) { -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { - int is_subclass = PyObject_IsSubclass(instance_class, type); - if (!is_subclass) { - instance_class = NULL; - } else if (unlikely(is_subclass == -1)) { - goto bad; - } else { - type = instance_class; - } - } - } - if (!instance_class) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } -#if PY_VERSION_HEX >= 0x03030000 - if (cause) { -#else - if (cause && cause != Py_None) { -#endif - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { -#if CYTHON_COMPILING_IN_PYPY - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); - Py_INCREF(tb); - PyErr_Restore(tmp_type, tmp_value, tb); - Py_XDECREF(tmp_tb); -#else - PyThreadState *tstate = PyThreadState_GET(); - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -#if !CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values) { - return PyObject_CallMethodObjArgs(sep, __pyx_n_s_join, values, NULL); -} -#endif - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); - if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - return NULL; - } - } - return m->sq_item(o, i); - } - } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { - PyObject *method; - method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); - if (unlikely(!method)) - return -1; - target->method = method; -#if CYTHON_COMPILING_IN_CPYTHON - #if PY_MAJOR_VERSION >= 3 - if (likely(PyObject_TypeCheck(method, &PyMethodDescr_Type))) - #endif - { - PyMethodDescrObject *descr = (PyMethodDescrObject*) method; - target->func = descr->d_method->ml_meth; - target->flag = descr->d_method->ml_flags & (METH_VARARGS | METH_KEYWORDS | METH_O | METH_NOARGS); - } -#endif - return 0; -} - -static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { - PyObject *args, *result = NULL; - if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; -#if CYTHON_COMPILING_IN_CPYTHON - args = PyTuple_New(1); - if (unlikely(!args)) goto bad; - Py_INCREF(self); - PyTuple_SET_ITEM(args, 0, self); -#else - args = PyTuple_Pack(1, self); - if (unlikely(!args)) goto bad; -#endif - result = __Pyx_PyObject_Call(cfunc->method, args, NULL); - Py_DECREF(args); -bad: - return result; -} - -static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { - if (PY_MAJOR_VERSION >= 3) - return __Pyx_CallUnboundCMethod0(&__pyx_umethod_PyDict_Type_items, d); - else - return PyDict_Items(d); -} - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", - index, (index == 1) ? "" : "s"); -} - -static CYTHON_INLINE int __Pyx_IterFinish(void) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { - if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } else { - return -1; - } - } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; - } else { - return -1; - } - } - return 0; -#endif -} - -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; - } else { - return __Pyx_IterFinish(); - } - return 0; -} - -static CYTHON_INLINE int __Pyx_DelItem_Generic(PyObject *o, PyObject *j) { - int r; - if (!j) return -1; - r = PyObject_DelItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i, - CYTHON_UNUSED int is_list, CYTHON_NCP_UNUSED int wraparound) { -#if CYTHON_COMPILING_IN_PYPY - if (is_list || PySequence_Check(o)) { - return PySequence_DelItem(o, i); - } -#else - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_ass_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - return -1; - } - } - return m->sq_ass_item(o, i, (PyObject *)NULL); - } -#endif - return __Pyx_DelItem_Generic(o, PyInt_FromSsize_t(i)); -} - -static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { - PyObject *method, *result = NULL; - method = __Pyx_PyObject_GetAttrStr(obj, method_name); - if (unlikely(!method)) goto bad; -#if CYTHON_COMPILING_IN_CPYTHON - if (likely(PyMethod_Check(method))) { - PyObject *self = PyMethod_GET_SELF(method); - if (likely(self)) { - PyObject *args; - PyObject *function = PyMethod_GET_FUNCTION(method); - args = PyTuple_New(2); - if (unlikely(!args)) goto bad; - Py_INCREF(self); - PyTuple_SET_ITEM(args, 0, self); - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 1, arg); - Py_INCREF(function); - Py_DECREF(method); method = NULL; - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); - return result; - } - } -#endif - result = __Pyx_PyObject_CallOneArg(method, arg); -bad: - Py_XDECREF(method); - return result; -} - -static PyObject* __Pyx__PyObject_PopNewIndex(PyObject* L, PyObject* py_ix) { - PyObject *r; - if (unlikely(!py_ix)) return NULL; - r = __Pyx__PyObject_PopIndex(L, py_ix); - Py_DECREF(py_ix); - return r; -} -static PyObject* __Pyx__PyObject_PopIndex(PyObject* L, PyObject* py_ix) { - return __Pyx_PyObject_CallMethod1(L, __pyx_n_s_pop, py_ix); -} -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyList_PopIndex(PyObject* L, PyObject* py_ix, Py_ssize_t ix) { - Py_ssize_t size = PyList_GET_SIZE(L); - if (likely(size > (((PyListObject*)L)->allocated >> 1))) { - Py_ssize_t cix = ix; - if (cix < 0) { - cix += size; - } - if (likely(0 <= cix && cix < size)) { - PyObject* v = PyList_GET_ITEM(L, cix); - Py_SIZE(L) -= 1; - size -= 1; - memmove(&PyList_GET_ITEM(L, cix), &PyList_GET_ITEM(L, cix+1), (size_t)(size-cix)*sizeof(PyObject*)); - return v; - } - } - if (py_ix == Py_None) { - return __Pyx__PyObject_PopNewIndex(L, PyInt_FromSsize_t(ix)); - } else { - return __Pyx__PyObject_PopIndex(L, py_ix); - } -} -#endif - -static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { - PyErr_Format(PyExc_TypeError, - "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); -} -static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact) -{ - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - if (none_allowed && obj == Py_None) return 1; - else if (exact) { - if (likely(Py_TYPE(obj) == type)) return 1; - #if PY_MAJOR_VERSION == 2 - else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; - #endif - } - else { - if (likely(PyObject_TypeCheck(obj, type))) return 1; - } - __Pyx_RaiseArgumentTypeInvalid(name, obj, type); - return 0; -} - -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) - goto bad; - Py_DECREF(ob); - return 0; -bad: - Py_XDECREF(ob); - return -1; -} - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_VERSION_HEX < 0x03030000 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if (strchr(__Pyx_MODULE_NAME, '.')) { - #if PY_VERSION_HEX < 0x03030000 - PyObject *py_level = PyInt_FromLong(1); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - #endif - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; - } - #endif - if (!module) { - #if PY_VERSION_HEX < 0x03030000 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: - #if PY_VERSION_HEX < 0x03030000 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - -static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases) { - Py_ssize_t i, nbases = PyTuple_GET_SIZE(bases); - for (i=0; i < nbases; i++) { - PyTypeObject *tmptype; - PyObject *tmp = PyTuple_GET_ITEM(bases, i); - tmptype = Py_TYPE(tmp); -#if PY_MAJOR_VERSION < 3 - if (tmptype == &PyClass_Type) - continue; -#endif - if (!metaclass) { - metaclass = tmptype; - continue; - } - if (PyType_IsSubtype(metaclass, tmptype)) - continue; - if (PyType_IsSubtype(tmptype, metaclass)) { - metaclass = tmptype; - continue; - } - PyErr_SetString(PyExc_TypeError, - "metaclass conflict: " - "the metaclass of a derived class " - "must be a (non-strict) subclass " - "of the metaclasses of all its bases"); - return NULL; - } - if (!metaclass) { -#if PY_MAJOR_VERSION < 3 - metaclass = &PyClass_Type; -#else - metaclass = &PyType_Type; -#endif - } - Py_INCREF((PyObject*) metaclass); - return (PyObject*) metaclass; -} - -static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { - PyObject* fake_module; - PyTypeObject* cached_type = NULL; - fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI); - if (!fake_module) return NULL; - Py_INCREF(fake_module); - cached_type = (PyTypeObject*) PyObject_GetAttrString(fake_module, type->tp_name); - if (cached_type) { - if (!PyType_Check((PyObject*)cached_type)) { - PyErr_Format(PyExc_TypeError, - "Shared Cython type %.200s is not a type object", - type->tp_name); - goto bad; - } - if (cached_type->tp_basicsize != type->tp_basicsize) { - PyErr_Format(PyExc_TypeError, - "Shared Cython type %.200s has the wrong size, try recompiling", - type->tp_name); - goto bad; - } - } else { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; - PyErr_Clear(); - if (PyType_Ready(type) < 0) goto bad; - if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0) - goto bad; - Py_INCREF(type); - cached_type = type; - } -done: - Py_DECREF(fake_module); - return cached_type; -bad: - Py_XDECREF(cached_type); - cached_type = NULL; - goto done; -} - -static PyObject * -__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *closure) -{ - if (unlikely(op->func_doc == NULL)) { - if (op->func.m_ml->ml_doc) { -#if PY_MAJOR_VERSION >= 3 - op->func_doc = PyUnicode_FromString(op->func.m_ml->ml_doc); -#else - op->func_doc = PyString_FromString(op->func.m_ml->ml_doc); -#endif - if (unlikely(op->func_doc == NULL)) - return NULL; - } else { - Py_INCREF(Py_None); - return Py_None; - } - } - Py_INCREF(op->func_doc); - return op->func_doc; -} -static int -__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value) -{ - PyObject *tmp = op->func_doc; - if (value == NULL) { - value = Py_None; - } - Py_INCREF(value); - op->func_doc = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op) -{ - if (unlikely(op->func_name == NULL)) { -#if PY_MAJOR_VERSION >= 3 - op->func_name = PyUnicode_InternFromString(op->func.m_ml->ml_name); -#else - op->func_name = PyString_InternFromString(op->func.m_ml->ml_name); -#endif - if (unlikely(op->func_name == NULL)) - return NULL; - } - Py_INCREF(op->func_name); - return op->func_name; -} -static int -__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value) -{ - PyObject *tmp; -#if PY_MAJOR_VERSION >= 3 - if (unlikely(value == NULL || !PyUnicode_Check(value))) { -#else - if (unlikely(value == NULL || !PyString_Check(value))) { -#endif - PyErr_SetString(PyExc_TypeError, - "__name__ must be set to a string object"); - return -1; - } - tmp = op->func_name; - Py_INCREF(value); - op->func_name = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op) -{ - Py_INCREF(op->func_qualname); - return op->func_qualname; -} -static int -__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value) -{ - PyObject *tmp; -#if PY_MAJOR_VERSION >= 3 - if (unlikely(value == NULL || !PyUnicode_Check(value))) { -#else - if (unlikely(value == NULL || !PyString_Check(value))) { -#endif - PyErr_SetString(PyExc_TypeError, - "__qualname__ must be set to a string object"); - return -1; - } - tmp = op->func_qualname; - Py_INCREF(value); - op->func_qualname = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_self(__pyx_CyFunctionObject *m, CYTHON_UNUSED void *closure) -{ - PyObject *self; - self = m->func_closure; - if (self == NULL) - self = Py_None; - Py_INCREF(self); - return self; -} -static PyObject * -__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op) -{ - if (unlikely(op->func_dict == NULL)) { - op->func_dict = PyDict_New(); - if (unlikely(op->func_dict == NULL)) - return NULL; - } - Py_INCREF(op->func_dict); - return op->func_dict; -} -static int -__Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value) -{ - PyObject *tmp; - if (unlikely(value == NULL)) { - PyErr_SetString(PyExc_TypeError, - "function's dictionary may not be deleted"); - return -1; - } - if (unlikely(!PyDict_Check(value))) { - PyErr_SetString(PyExc_TypeError, - "setting function's dictionary to a non-dict"); - return -1; - } - tmp = op->func_dict; - Py_INCREF(value); - op->func_dict = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op) -{ - Py_INCREF(op->func_globals); - return op->func_globals; -} -static PyObject * -__Pyx_CyFunction_get_closure(CYTHON_UNUSED __pyx_CyFunctionObject *op) -{ - Py_INCREF(Py_None); - return Py_None; -} -static PyObject * -__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op) -{ - PyObject* result = (op->func_code) ? op->func_code : Py_None; - Py_INCREF(result); - return result; -} -static int -__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { - int result = 0; - PyObject *res = op->defaults_getter((PyObject *) op); - if (unlikely(!res)) - return -1; - #if CYTHON_COMPILING_IN_CPYTHON - op->defaults_tuple = PyTuple_GET_ITEM(res, 0); - Py_INCREF(op->defaults_tuple); - op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); - Py_INCREF(op->defaults_kwdict); - #else - op->defaults_tuple = PySequence_ITEM(res, 0); - if (unlikely(!op->defaults_tuple)) result = -1; - else { - op->defaults_kwdict = PySequence_ITEM(res, 1); - if (unlikely(!op->defaults_kwdict)) result = -1; - } - #endif - Py_DECREF(res); - return result; -} -static int -__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value) { - PyObject* tmp; - if (!value) { - value = Py_None; - } else if (value != Py_None && !PyTuple_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__defaults__ must be set to a tuple object"); - return -1; - } - Py_INCREF(value); - tmp = op->defaults_tuple; - op->defaults_tuple = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op) { - PyObject* result = op->defaults_tuple; - if (unlikely(!result)) { - if (op->defaults_getter) { - if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; - result = op->defaults_tuple; - } else { - result = Py_None; - } - } - Py_INCREF(result); - return result; -} -static int -__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value) { - PyObject* tmp; - if (!value) { - value = Py_None; - } else if (value != Py_None && !PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__kwdefaults__ must be set to a dict object"); - return -1; - } - Py_INCREF(value); - tmp = op->defaults_kwdict; - op->defaults_kwdict = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op) { - PyObject* result = op->defaults_kwdict; - if (unlikely(!result)) { - if (op->defaults_getter) { - if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; - result = op->defaults_kwdict; - } else { - result = Py_None; - } - } - Py_INCREF(result); - return result; -} -static int -__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value) { - PyObject* tmp; - if (!value || value == Py_None) { - value = NULL; - } else if (!PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__annotations__ must be set to a dict object"); - return -1; - } - Py_XINCREF(value); - tmp = op->func_annotations; - op->func_annotations = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op) { - PyObject* result = op->func_annotations; - if (unlikely(!result)) { - result = PyDict_New(); - if (unlikely(!result)) return NULL; - op->func_annotations = result; - } - Py_INCREF(result); - return result; -} -static PyGetSetDef __pyx_CyFunction_getsets[] = { - {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, - {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, - {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, - {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, - {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, - {(char *) "__self__", (getter)__Pyx_CyFunction_get_self, 0, 0, 0}, - {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, - {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, - {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, - {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, - {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, - {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, - {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, - {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, - {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, - {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, - {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, - {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, - {0, 0, 0, 0, 0} -}; -static PyMemberDef __pyx_CyFunction_members[] = { - {(char *) "__module__", T_OBJECT, offsetof(__pyx_CyFunctionObject, func.m_module), PY_WRITE_RESTRICTED, 0}, - {0, 0, 0, 0, 0} -}; -static PyObject * -__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, CYTHON_UNUSED PyObject *args) -{ -#if PY_MAJOR_VERSION >= 3 - return PyUnicode_FromString(m->func.m_ml->ml_name); -#else - return PyString_FromString(m->func.m_ml->ml_name); -#endif -} -static PyMethodDef __pyx_CyFunction_methods[] = { - {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, - {0, 0, 0, 0} -}; -#if PY_VERSION_HEX < 0x030500A0 -#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) -#else -#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func.m_weakreflist) -#endif -static PyObject *__Pyx_CyFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, PyObject* qualname, - PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { - __pyx_CyFunctionObject *op = PyObject_GC_New(__pyx_CyFunctionObject, type); - if (op == NULL) - return NULL; - op->flags = flags; - __Pyx_CyFunction_weakreflist(op) = NULL; - op->func.m_ml = ml; - op->func.m_self = (PyObject *) op; - Py_XINCREF(closure); - op->func_closure = closure; - Py_XINCREF(module); - op->func.m_module = module; - op->func_dict = NULL; - op->func_name = NULL; - Py_INCREF(qualname); - op->func_qualname = qualname; - op->func_doc = NULL; - op->func_classobj = NULL; - op->func_globals = globals; - Py_INCREF(op->func_globals); - Py_XINCREF(code); - op->func_code = code; - op->defaults_pyobjects = 0; - op->defaults = NULL; - op->defaults_tuple = NULL; - op->defaults_kwdict = NULL; - op->defaults_getter = NULL; - op->func_annotations = NULL; - PyObject_GC_Track(op); - return (PyObject *) op; -} -static int -__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) -{ - Py_CLEAR(m->func_closure); - Py_CLEAR(m->func.m_module); - Py_CLEAR(m->func_dict); - Py_CLEAR(m->func_name); - Py_CLEAR(m->func_qualname); - Py_CLEAR(m->func_doc); - Py_CLEAR(m->func_globals); - Py_CLEAR(m->func_code); - Py_CLEAR(m->func_classobj); - Py_CLEAR(m->defaults_tuple); - Py_CLEAR(m->defaults_kwdict); - Py_CLEAR(m->func_annotations); - if (m->defaults) { - PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); - int i; - for (i = 0; i < m->defaults_pyobjects; i++) - Py_XDECREF(pydefaults[i]); - PyMem_Free(m->defaults); - m->defaults = NULL; - } - return 0; -} -static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) -{ - PyObject_GC_UnTrack(m); - if (__Pyx_CyFunction_weakreflist(m) != NULL) - PyObject_ClearWeakRefs((PyObject *) m); - __Pyx_CyFunction_clear(m); - PyObject_GC_Del(m); -} -static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) -{ - Py_VISIT(m->func_closure); - Py_VISIT(m->func.m_module); - Py_VISIT(m->func_dict); - Py_VISIT(m->func_name); - Py_VISIT(m->func_qualname); - Py_VISIT(m->func_doc); - Py_VISIT(m->func_globals); - Py_VISIT(m->func_code); - Py_VISIT(m->func_classobj); - Py_VISIT(m->defaults_tuple); - Py_VISIT(m->defaults_kwdict); - if (m->defaults) { - PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); - int i; - for (i = 0; i < m->defaults_pyobjects; i++) - Py_VISIT(pydefaults[i]); - } - return 0; -} -static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type) -{ - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) { - Py_INCREF(func); - return func; - } - if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) { - if (type == NULL) - type = (PyObject *)(Py_TYPE(obj)); - return __Pyx_PyMethod_New(func, type, (PyObject *)(Py_TYPE(type))); - } - if (obj == Py_None) - obj = NULL; - return __Pyx_PyMethod_New(func, obj, type); -} -static PyObject* -__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) -{ -#if PY_MAJOR_VERSION >= 3 - return PyUnicode_FromFormat("<cyfunction %U at %p>", - op->func_qualname, (void *)op); -#else - return PyString_FromFormat("<cyfunction %s at %p>", - PyString_AsString(op->func_qualname), (void *)op); -#endif -} -#if CYTHON_COMPILING_IN_PYPY -static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyCFunctionObject* f = (PyCFunctionObject*)func; - PyCFunction meth = f->m_ml->ml_meth; - PyObject *self = f->m_self; - Py_ssize_t size; - switch (f->m_ml->ml_flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { - case METH_VARARGS: - if (likely(kw == NULL || PyDict_Size(kw) == 0)) - return (*meth)(self, arg); - break; - case METH_VARARGS | METH_KEYWORDS: - return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); - case METH_NOARGS: - if (likely(kw == NULL || PyDict_Size(kw) == 0)) { - size = PyTuple_GET_SIZE(arg); - if (likely(size == 0)) - return (*meth)(self, NULL); - PyErr_Format(PyExc_TypeError, - "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - case METH_O: - if (likely(kw == NULL || PyDict_Size(kw) == 0)) { - size = PyTuple_GET_SIZE(arg); - if (likely(size == 1)) { - PyObject *result, *arg0 = PySequence_ITEM(arg, 0); - if (unlikely(!arg0)) return NULL; - result = (*meth)(self, arg0); - Py_DECREF(arg0); - return result; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - default: - PyErr_SetString(PyExc_SystemError, "Bad call flags in " - "__Pyx_CyFunction_Call. METH_OLDARGS is no " - "longer supported!"); - return NULL; - } - PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", - f->m_ml->ml_name); - return NULL; -} -#else -static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { - return PyCFunction_Call(func, arg, kw); -} -#endif -static PyTypeObject __pyx_CyFunctionType_type = { - PyVarObject_HEAD_INIT(0, 0) - "cython_function_or_method", - sizeof(__pyx_CyFunctionObject), - 0, - (destructor) __Pyx_CyFunction_dealloc, - 0, - 0, - 0, -#if PY_MAJOR_VERSION < 3 - 0, -#else - 0, -#endif - (reprfunc) __Pyx_CyFunction_repr, - 0, - 0, - 0, - 0, - __Pyx_CyFunction_Call, - 0, - 0, - 0, - 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, - 0, - (traverseproc) __Pyx_CyFunction_traverse, - (inquiry) __Pyx_CyFunction_clear, - 0, -#if PY_VERSION_HEX < 0x030500A0 - offsetof(__pyx_CyFunctionObject, func_weakreflist), -#else - offsetof(PyCFunctionObject, m_weakreflist), -#endif - 0, - 0, - __pyx_CyFunction_methods, - __pyx_CyFunction_members, - __pyx_CyFunction_getsets, - 0, - 0, - __Pyx_CyFunction_descr_get, - 0, - offsetof(__pyx_CyFunctionObject, func_dict), - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, -#if PY_VERSION_HEX >= 0x030400a1 - 0, -#endif -}; -static int __pyx_CyFunction_init(void) { -#if !CYTHON_COMPILING_IN_PYPY - __pyx_CyFunctionType_type.tp_call = PyCFunction_Call; -#endif - __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); - if (__pyx_CyFunctionType == NULL) { - return -1; - } - return 0; -} -static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults = PyMem_Malloc(size); - if (!m->defaults) - return PyErr_NoMemory(); - memset(m->defaults, 0, size); - m->defaults_pyobjects = pyobjects; - return m->defaults; -} -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults_tuple = tuple; - Py_INCREF(tuple); -} -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults_kwdict = dict; - Py_INCREF(dict); -} -static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->func_annotations = dict; - Py_INCREF(dict); -} - -static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, - PyObject *qualname, PyObject *mkw, PyObject *modname, PyObject *doc) { - PyObject *ns; - if (metaclass) { - PyObject *prep = __Pyx_PyObject_GetAttrStr(metaclass, __pyx_n_s_prepare); - if (prep) { - PyObject *pargs = PyTuple_Pack(2, name, bases); - if (unlikely(!pargs)) { - Py_DECREF(prep); - return NULL; - } - ns = PyObject_Call(prep, pargs, mkw); - Py_DECREF(prep); - Py_DECREF(pargs); - } else { - if (unlikely(!PyErr_ExceptionMatches(PyExc_AttributeError))) - return NULL; - PyErr_Clear(); - ns = PyDict_New(); - } - } else { - ns = PyDict_New(); - } - if (unlikely(!ns)) - return NULL; - if (unlikely(PyObject_SetItem(ns, __pyx_n_s_module, modname) < 0)) goto bad; - if (unlikely(PyObject_SetItem(ns, __pyx_n_s_qualname, qualname) < 0)) goto bad; - if (unlikely(doc && PyObject_SetItem(ns, __pyx_n_s_doc, doc) < 0)) goto bad; - return ns; -bad: - Py_DECREF(ns); - return NULL; -} -static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, - PyObject *dict, PyObject *mkw, - int calculate_metaclass, int allow_py2_metaclass) { - PyObject *result, *margs; - PyObject *owned_metaclass = NULL; - if (allow_py2_metaclass) { - owned_metaclass = PyObject_GetItem(dict, __pyx_n_s_metaclass); - if (owned_metaclass) { - metaclass = owned_metaclass; - } else if (likely(PyErr_ExceptionMatches(PyExc_KeyError))) { - PyErr_Clear(); - } else { - return NULL; - } - } - if (calculate_metaclass && (!metaclass || PyType_Check(metaclass))) { - metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); - Py_XDECREF(owned_metaclass); - if (unlikely(!metaclass)) - return NULL; - owned_metaclass = metaclass; - } - margs = PyTuple_Pack(3, name, bases, dict); - if (unlikely(!margs)) { - result = NULL; - } else { - result = PyObject_Call(metaclass, margs, mkw); - Py_DECREF(margs); - } - Py_XDECREF(owned_metaclass); - return result; -} - -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - py_code = __pyx_find_code_object(c_line ? c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? c_line : py_line, py_code); - } - py_frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = py_line; - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { - const int neg_one = (int) -1, const_zero = (int) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(int) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); - } - } else { - if (sizeof(int) <= sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(int), - little, !is_unsigned); - } -} - -#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) -#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) -#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ - {\ - func_type value = func_value;\ - if (sizeof(target_type) < sizeof(func_type)) {\ - if (unlikely(value != (func_type) (target_type) value)) {\ - func_type zero = 0;\ - if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ - return (target_type) -1;\ - if (is_unsigned && unlikely(value < zero))\ - goto raise_neg_overflow;\ - else\ - goto raise_overflow;\ - }\ - }\ - return (target_type) value;\ - } - -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { - const int neg_one = (int) -1, const_zero = (int) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(int) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (int) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { - return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { - return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { - return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (int) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) digits[0]) - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) - case -2: - if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - } -#endif - if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - int val; - PyObject *v = __Pyx_PyNumber_Int(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (int) -1; - } - } else { - int val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (int) -1; - val = __Pyx_PyInt_As_int(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to int"); - return (int) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { - const long neg_one = (long) -1, const_zero = (long) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(long) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { - const long neg_one = (long) -1, const_zero = (long) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(long) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (long) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { - return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { - return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { - return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (long) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) digits[0]) - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) - case -2: - if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - } -#endif - if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - long val; - PyObject *v = __Pyx_PyNumber_Int(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (long) -1; - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to long"); - return (long) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long) -1; -} - -static int __Pyx_check_binary_version(void) { - char ctversion[4], rtversion[4]; - PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); - PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); - if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { - char message[200]; - PyOS_snprintf(message, sizeof(message), - "compiletime version %s of module '%.100s' " - "does not match runtime version %s", - ctversion, __Pyx_MODULE_NAME, rtversion); - return PyErr_WarnEx(NULL, message, 1); - } - return 0; -} - -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { - while (t->p) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} -static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { -#if PY_VERSION_HEX < 0x03030000 - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -#else - if (__Pyx_PyUnicode_READY(o) == -1) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (PyUnicode_IS_ASCII(o)) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else - return PyUnicode_AsUTF8AndSize(o, length); -#endif -#endif - } else -#endif -#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { - PyNumberMethods *m; - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (PyInt_Check(x) || PyLong_Check(x)) -#else - if (PyLong_Check(x)) -#endif - return __Pyx_NewRef(x); - m = Py_TYPE(x)->tp_as_number; -#if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = PyNumber_Int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = PyNumber_Long(x); - } -#else - if (m && m->nb_int) { - name = "int"; - res = PyNumber_Long(x); - } -#endif - if (res) { -#if PY_MAJOR_VERSION < 3 - if (!PyInt_Check(res) && !PyLong_Check(res)) { -#else - if (!PyLong_Check(res)) { -#endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - name, name, Py_TYPE(res)->tp_name); - Py_DECREF(res); - return NULL; - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) { - if (sizeof(Py_ssize_t) >= sizeof(long)) - return PyInt_AS_LONG(b); - else - return PyInt_AsSsize_t(x); - } -#endif - if (likely(PyLong_CheckExact(b))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)b)->ob_digit; - const Py_ssize_t size = Py_SIZE(b); - if (likely(__Pyx_sst_abs(size) <= 1)) { - ival = likely(size) ? digits[0] : 0; - if (size == -1) ival = -ival; - return ival; - } else { - switch (size) { - case 2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - } - } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - -#endif /* Py_PYTHON_H */ diff --git a/aiohttp/_multidict.pyx b/aiohttp/_multidict.pyx deleted file mode 100644 index a61f0ba..0000000 --- a/aiohttp/_multidict.pyx +++ /dev/null @@ -1,653 +0,0 @@ -import sys -from collections import abc -from collections.abc import Iterable, Set -from operator import itemgetter - - -_marker = object() - - -class upstr(str): - - """Case insensitive str.""" - - def __new__(cls, val='', - encoding=sys.getdefaultencoding(), errors='strict'): - if isinstance(val, (bytes, bytearray, memoryview)): - val = str(val, encoding, errors) - elif isinstance(val, str): - pass - else: - val = str(val) - val = val.upper() - return str.__new__(cls, val) - - def upper(self): - return self - - -cdef _eq(self, other): - cdef _Base typed_self - cdef _Base typed_other - cdef int is_left_base, is_right_base - - is_left_base = isinstance(self, _Base) - is_right_base = isinstance(other, _Base) - - if is_left_base and is_right_base: - return (<_Base>self)._items == (<_Base>other)._items - elif is_left_base and isinstance(other, abc.Mapping): - return (<_Base>self)._eq_to_mapping(other) - elif is_right_base and isinstance(self, abc.Mapping): - return (<_Base>other)._eq_to_mapping(self) - else: - return NotImplemented - - -cdef class _Pair: - cdef object _key - cdef object _value - - def __cinit__(self, key, value): - self._key = key - self._value = value - - def __richcmp__(self, other, op): - cdef _Pair left, right - if not isinstance(self, _Pair) or not isinstance(other, _Pair): - return NotImplemented - left = <_Pair>self - right = <_Pair>other - if op == 2: # == - return left._key == right._key and left._value == right._value - elif op == 3: # != - return left._key != right._key and left._value != right._value - -cdef class _Base: - - cdef list _items - cdef object _upstr - cdef object marker - - def __cinit__(self): - self._upstr = upstr - self.marker = _marker - - cdef str _upper(self, s): - if type(s) is self._upstr: - return <str>s - return s - - def getall(self, key, default=_marker): - """Return a list of all values matching the key.""" - return self._getall(self._upper(key), default) - - cdef _getall(self, str key, default): - cdef list res - cdef _Pair item - key = self._upper(key) - res = [] - for i in self._items: - item = <_Pair>i - if item._key == key: - res.append(item._value) - if res: - return res - if not res and default is not self.marker: - return default - raise KeyError('Key not found: %r' % key) - - def getone(self, key, default=_marker): - """Get first value matching the key.""" - return self._getone(self._upper(key), default) - - cdef _getone(self, str key, default): - cdef _Pair item - key = self._upper(key) - for i in self._items: - item = <_Pair>i - if item._key == key: - return item._value - if default is not self.marker: - return default - raise KeyError('Key not found: %r' % key) - - # Mapping interface # - - def __getitem__(self, key): - return self._getone(self._upper(key), self.marker) - - def get(self, key, default=None): - """Get first value matching the key. - - The method is alias for .getone(). - """ - return self._getone(self._upper(key), default) - - def __contains__(self, key): - return self._contains(self._upper(key)) - - cdef _contains(self, str key): - cdef _Pair item - key = self._upper(key) - for i in self._items: - item = <_Pair>i - if item._key == key: - return True - return False - - def __iter__(self): - return iter(self.keys()) - - def __len__(self): - return len(self._items) - - cpdef keys(self): - """Return a new view of the dictionary's keys.""" - return _KeysView.__new__(_KeysView, self._items) - - def items(self): - """Return a new view of the dictionary's items *(key, value) pairs).""" - return _ItemsView.__new__(_ItemsView, self._items) - - def values(self): - """Return a new view of the dictionary's values.""" - return _ValuesView.__new__(_ValuesView, self._items) - - def __repr__(self): - cdef _Pair item - lst = [] - for i in self._items: - item = <_Pair>i - lst.append("'{}': {!r}".format(item._key, item._value)) - body = ', '.join(lst) - return '<{}({})>'.format(self.__class__.__name__, body) - - cdef _eq_to_mapping(self, other): - cdef _Pair item - left_keys = set(self.keys()) - right_keys = set(other.keys()) - if left_keys != right_keys: - return False - if len(self._items) != len(right_keys): - return False - for i in self._items: - item = <_Pair>i - nv = other.get(item._key, self.marker) - if item._value != nv: - return False - return True - - def __richcmp__(self, other, op): - if op == 2: # == - return _eq(self, other) - elif op == 3: # != - ret = _eq(self, other) - if ret is NotImplemented: - return ret - else: - return not ret - else: - return NotImplemented - - -cdef class MultiDictProxy(_Base): - - def __init__(self, arg): - cdef MultiDict mdict - if not isinstance(arg, MultiDict): - raise TypeError( - 'MultiDictProxy requires MultiDict instance, not {}'.format( - type(arg))) - - mdict = arg - self._items = mdict._items - - def copy(self): - """Return a copy of itself.""" - return MultiDict(self._items) - -abc.Mapping.register(MultiDictProxy) - - -cdef class CIMultiDictProxy(MultiDictProxy): - - def __init__(self, arg): - cdef CIMultiDict mdict - if not isinstance(arg, CIMultiDict): - raise TypeError( - 'CIMultiDictProxy requires CIMultiDict instance, not {}'.format( - type(arg))) - - mdict = arg - self._items = mdict._items - - cdef str _upper(self, s): - if type(s) is self._upstr: - return <str>s - return s.upper() - - def copy(self): - """Return a copy of itself.""" - return CIMultiDict(self._items) - - -abc.Mapping.register(CIMultiDictProxy) - - -cdef class MultiDict(_Base): - """An ordered dictionary that can have multiple values for each key.""" - - def __init__(self, *args, **kwargs): - self._items = [] - - self._extend(args, kwargs, self.__class__.__name__, 1) - - cdef _extend(self, tuple args, dict kwargs, name, int do_add): - cdef _Pair item - cdef str key - - if len(args) > 1: - raise TypeError("{} takes at most 1 positional argument" - " ({} given)".format(name, len(args))) - - if args: - arg = args[0] - if isinstance(arg, _Base): - for i in (<_Base>arg)._items: - item = <_Pair>i - key = self._upper(item._key) - value = item._value - if do_add: - self._add(key, value) - else: - self._replace(key, value) - elif hasattr(arg, 'items'): - for i in arg.items(): - if isinstance(i, _Pair): - item = <_Pair>i - key = item._key - value = item._value - else: - key = self._upper(i[0]) - value = i[1] - if do_add: - self._add(key, value) - else: - self._replace(key, value) - else: - for i in arg: - if isinstance(i, _Pair): - item = <_Pair>i - key = item._key - value = item._value - else: - if not len(i) == 2: - raise TypeError( - "{} takes either dict or list of (key, value) " - "tuples".format(name)) - key = self._upper(i[0]) - value = i[1] - if do_add: - self._add(key, value) - else: - self._replace(key, value) - - - for key, value in kwargs.items(): - key = self._upper(key) - if do_add: - self._add(key, value) - else: - self._replace(key, value) - - cdef _add(self, str key, value): - self._items.append(_Pair.__new__(_Pair, key, value)) - - cdef _replace(self, str key, value): - self._remove(key, 0) - self._items.append(_Pair.__new__(_Pair, key, value)) - - def add(self, key, value): - """Add the key and value, not overwriting any previous value.""" - self._add(self._upper(key), value) - - def copy(self): - """Return a copy of itself.""" - cls = self.__class__ - return cls(self._items) - - def extend(self, *args, **kwargs): - """Extend current MultiDict with more values. - - This method must be used instead of update. - """ - self._extend(args, kwargs, "extend", 1) - - def clear(self): - """Remove all items from MultiDict""" - self._items.clear() - - # MutableMapping interface # - - def __setitem__(self, key, value): - self._replace(self._upper(key), value) - - def __delitem__(self, key): - self._remove(self._upper(key), True) - - cdef _remove(self, str key, int raise_key_error): - cdef _Pair item - cdef int found - found = False - for i in range(len(self._items) - 1, -1, -1): - item = <_Pair>self._items[i] - if item._key == key: - del self._items[i] - found = True - if not found and raise_key_error: - raise KeyError(key) - - def setdefault(self, key, default=None): - """Return value for key, set value to default if key is not present.""" - cdef str skey - cdef _Pair item - skey = self._upper(key) - for i in self._items: - item = <_Pair>i - if item._key == skey: - return item._value - self._add(skey, default) - return default - - def pop(self, key, default=_marker): - """Remove specified key and return the corresponding value. - - If key is not found, d is returned if given, otherwise - KeyError is raised. - - """ - cdef int found - cdef str skey - cdef object value - cdef _Pair item - skey = self._upper(key) - value = None - found = False - for i in range(len(self._items) - 1, -1, -1): - item = <_Pair>self._items[i] - if item._key == key: - value = item._value - del self._items[i] - found = True - if not found: - if default is self.marker: - raise KeyError(key) - else: - return default - else: - return value - - def popitem(self): - """Remove and return an arbitrary (key, value) pair.""" - cdef _Pair item - if self._items: - item = <_Pair>self._items.pop(0) - return (item._key, item._value) - else: - raise KeyError("empty multidict") - - def update(self, *args, **kwargs): - """Update the dictionary from *other*, overwriting existing keys.""" - self._extend(args, kwargs, "update", 0) - - -abc.MutableMapping.register(MultiDict) - - -cdef class CIMultiDict(MultiDict): - """An ordered dictionary that can have multiple values for each key.""" - - cdef str _upper(self, s): - if type(s) is self._upstr: - return <str>s - return s.upper() - - - -abc.MutableMapping.register(CIMultiDict) - - -cdef class _ViewBase: - - cdef list _items - - def __cinit__(self, list items): - self._items = items - - def __len__(self): - return len(self._items) - - -cdef class _ViewBaseSet(_ViewBase): - - def __richcmp__(self, other, op): - if op == 0: # < - if not isinstance(other, Set): - return NotImplemented - return len(self) < len(other) and self <= other - elif op == 1: # <= - if not isinstance(other, Set): - return NotImplemented - if len(self) > len(other): - return False - for elem in self: - if elem not in other: - return False - return True - elif op == 2: # == - if not isinstance(other, Set): - return NotImplemented - return len(self) == len(other) and self <= other - elif op == 3: # != - return not self == other - elif op == 4: # > - if not isinstance(other, Set): - return NotImplemented - return len(self) > len(other) and self >= other - elif op == 5: # >= - if not isinstance(other, Set): - return NotImplemented - if len(self) < len(other): - return False - for elem in other: - if elem not in self: - return False - return True - - def __and__(self, other): - if not isinstance(other, Iterable): - return NotImplemented - if not isinstance(other, Set): - other = set(other) - return set(self) & other - - def __or__(self, other): - if not isinstance(other, Iterable): - return NotImplemented - if not isinstance(other, Set): - other = set(other) - return set(self) | other - - def __sub__(self, other): - if not isinstance(other, Iterable): - return NotImplemented - if not isinstance(other, Set): - other = set(other) - return set(self) - other - - def __xor__(self, other): - if not isinstance(other, Set): - if not isinstance(other, Iterable): - return NotImplemented - other = set(other) - return set(self) ^ other - - -cdef class _ItemsIter: - cdef list _items - cdef int _current - cdef int _len - - def __cinit__(self, items): - self._items = items - self._current = 0 - self._len = len(self._items) - - def __iter__(self): - return self - - def __next__(self): - if self._current == self._len: - raise StopIteration - item = <_Pair>self._items[self._current] - self._current += 1 - return (item._key, item._value) - - -cdef class _ItemsView(_ViewBaseSet): - - def isdisjoint(self, other): - 'Return True if two sets have a null intersection.' - cdef _Pair item - for i in self._items: - item = <_Pair>i - t = (item._key, item._value) - if t in other: - return False - return True - - def __contains__(self, i): - cdef _Pair item - assert isinstance(i, tuple) or isinstance(i, list) - assert len(i) == 2 - item = _Pair.__new__(_Pair, i[0], i[1]) - return item in self._items - - def __iter__(self): - return _ItemsIter.__new__(_ItemsIter, self._items) - - def __repr__(self): - cdef _Pair item - lst = [] - for i in self._items: - item = <_Pair>i - lst.append("{!r}: {!r}".format(item._key, item._value)) - body = ', '.join(lst) - return '{}({})'.format(self.__class__.__name__, body) - - -abc.ItemsView.register(_ItemsView) - - -cdef class _ValuesIter: - cdef list _items - cdef int _current - cdef int _len - - def __cinit__(self, items): - self._items = items - self._current = 0 - self._len = len(self._items) - - def __iter__(self): - return self - - def __next__(self): - if self._current == self._len: - raise StopIteration - item = <_Pair>self._items[self._current] - self._current += 1 - return item._value - - -cdef class _ValuesView(_ViewBase): - - def __contains__(self, value): - cdef _Pair item - for i in self._items: - item = <_Pair>i - if item._value == value: - return True - return False - - def __iter__(self): - return _ValuesIter.__new__(_ValuesIter, self._items) - - def __repr__(self): - cdef _Pair item - lst = [] - for i in self._items: - item = <_Pair>i - lst.append("{!r}".format(item._value)) - body = ', '.join(lst) - return '{}({})'.format(self.__class__.__name__, body) - - -abc.ValuesView.register(_ValuesView) - - -cdef class _KeysIter: - cdef list _items - cdef int _current - cdef int _len - - def __cinit__(self, items): - self._items = items - self._current = 0 - self._len = len(self._items) - - def __iter__(self): - return self - - def __next__(self): - if self._current == self._len: - raise StopIteration - item = <_Pair>self._items[self._current] - self._current += 1 - return item._key - - -cdef class _KeysView(_ViewBaseSet): - - def isdisjoint(self, other): - 'Return True if two sets have a null intersection.' - cdef _Pair item - for i in self._items: - item = <_Pair>i - if item._key in other: - return False - return True - - def __contains__(self, value): - cdef _Pair item - for i in self._items: - item = <_Pair>i - if item._key == value: - return True - return False - - def __iter__(self): - return _KeysIter.__new__(_KeysIter, self._items) - - def __repr__(self): - cdef _Pair item - lst = [] - for i in self._items: - item = <_Pair>i - lst.append("{!r}".format(item._key)) - body = ', '.join(lst) - return '{}({})'.format(self.__class__.__name__, body) - - -abc.KeysView.register(_KeysView) diff --git a/aiohttp/_websocket.c b/aiohttp/_websocket.c index 241b441..03cc432 100644 --- a/aiohttp/_websocket.c +++ b/aiohttp/_websocket.c @@ -1,10 +1,11 @@ -/* Generated by Cython 0.23.4 */ +/* Generated by Cython 0.24.1 */ /* BEGIN: Cython Metadata { "distutils": { "depends": [] - } + }, + "module_name": "aiohttp._websocket" } END: Cython Metadata */ @@ -15,10 +16,10 @@ END: Cython Metadata */ #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) #error Cython requires Python 2.6+ or Python 3.2+. #else -#define CYTHON_ABI "0_23_4" +#define CYTHON_ABI "0_24_1" #include <stddef.h> #ifndef offsetof -#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall @@ -44,17 +45,23 @@ END: Cython Metadata */ #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION -#define CYTHON_COMPILING_IN_PYPY 1 -#define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 #else -#define CYTHON_COMPILING_IN_PYPY 0 -#define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 #endif #if !defined(CYTHON_USE_PYLONG_INTERNALS) && CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x02070000 -#define CYTHON_USE_PYLONG_INTERNALS 1 + #define CYTHON_USE_PYLONG_INTERNALS 1 +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #undef SHIFT + #undef BASE + #undef MASK #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) -#define Py_OptimizeFlag 0 + #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" @@ -90,6 +97,7 @@ END: Cython Metadata */ #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 #define __Pyx_PyUnicode_READY(op) (0) @@ -98,6 +106,7 @@ END: Cython Metadata */ #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) @@ -110,6 +119,17 @@ END: Cython Metadata */ #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 @@ -117,6 +137,9 @@ END: Cython Metadata */ #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif +#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) + #define PyObject_ASCII(o) PyObject_Repr(o) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -224,7 +247,17 @@ static CYTHON_INLINE float __PYX_NAN() { return value; } #endif +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#define __PYX_ERR(f_index, lineno, Ln_error) \ +{ \ + __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ +} #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) @@ -276,7 +309,7 @@ static CYTHON_INLINE float __PYX_NAN() { # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif -typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; +typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 @@ -350,7 +383,7 @@ static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_COMPILING_IN_CPYTHON @@ -359,6 +392,12 @@ static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#else +#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) +#endif +#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { @@ -449,6 +488,7 @@ static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; +static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; @@ -465,6 +505,7 @@ static const char *__pyx_f[] = { /*--- Type declarations ---*/ /* --- Runtime support code (head) --- */ +/* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif @@ -527,6 +568,7 @@ static const char *__pyx_f[] = { #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) +/* PyObjectGetAttrStr.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); @@ -542,23 +584,29 @@ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif +/* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); +/* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); +/* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); +/* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); +/* ArgTypeTest.proto */ static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); +/* CodeObjectCache.proto */ typedef struct { - int code_line; PyCodeObject* code_object; + int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; @@ -570,17 +618,23 @@ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int co static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); +/* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); +/* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); +/* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); +/* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); +/* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); +/* PyIdentifierFromString.proto */ #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) @@ -589,10 +643,13 @@ static int __Pyx_check_binary_version(void); #endif #endif +/* ModuleImport.proto */ static PyObject *__Pyx_ImportModule(const char *name); +/* TypeImport.proto */ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); +/* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); @@ -687,24 +744,24 @@ int __pyx_module_is_main_aiohttp___websocket = 0; /* Implementation of 'aiohttp._websocket' */ static PyObject *__pyx_builtin_range; -static char __pyx_k_i[] = "i"; -static char __pyx_k_data[] = "data"; -static char __pyx_k_main[] = "__main__"; -static char __pyx_k_mask[] = "mask"; -static char __pyx_k_test[] = "__test__"; -static char __pyx_k_range[] = "range"; -static char __pyx_k_in_buf[] = "in_buf"; -static char __pyx_k_data_len[] = "data_len"; -static char __pyx_k_mask_buf[] = "mask_buf"; -static char __pyx_k_uint32_msk[] = "uint32_msk"; -static char __pyx_k_uint64_msk[] = "uint64_msk"; -static char __pyx_k_aiohttp__websocket[] = "aiohttp._websocket"; -static char __pyx_k_websocket_mask_cython[] = "_websocket_mask_cython"; -static char __pyx_k_home_andrew_projects_aiohttp_ai[] = "/home/andrew/projects/aiohttp/aiohttp/_websocket.pyx"; +static const char __pyx_k_i[] = "i"; +static const char __pyx_k_data[] = "data"; +static const char __pyx_k_main[] = "__main__"; +static const char __pyx_k_mask[] = "mask"; +static const char __pyx_k_test[] = "__test__"; +static const char __pyx_k_range[] = "range"; +static const char __pyx_k_in_buf[] = "in_buf"; +static const char __pyx_k_data_len[] = "data_len"; +static const char __pyx_k_mask_buf[] = "mask_buf"; +static const char __pyx_k_uint32_msk[] = "uint32_msk"; +static const char __pyx_k_uint64_msk[] = "uint64_msk"; +static const char __pyx_k_aiohttp__websocket[] = "aiohttp._websocket"; +static const char __pyx_k_websocket_mask_cython[] = "_websocket_mask_cython"; +static const char __pyx_k_home_travis_build_KeepSafe_aioh[] = "/home/travis/build/KeepSafe/aiohttp/aiohttp/_websocket.pyx"; static PyObject *__pyx_n_s_aiohttp__websocket; static PyObject *__pyx_n_s_data; static PyObject *__pyx_n_s_data_len; -static PyObject *__pyx_kp_s_home_andrew_projects_aiohttp_ai; +static PyObject *__pyx_kp_s_home_travis_build_KeepSafe_aioh; static PyObject *__pyx_n_s_i; static PyObject *__pyx_n_s_in_buf; static PyObject *__pyx_n_s_main; @@ -734,9 +791,6 @@ static PyMethodDef __pyx_mdef_7aiohttp_10_websocket_1_websocket_mask_cython = {" static PyObject *__pyx_pw_7aiohttp_10_websocket_1_websocket_mask_cython(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_mask = 0; PyObject *__pyx_v_data = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("_websocket_mask_cython (wrapper)", 0); @@ -760,11 +814,11 @@ static PyObject *__pyx_pw_7aiohttp_10_websocket_1_websocket_mask_cython(PyObject case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_data)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_websocket_mask_cython", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_websocket_mask_cython", 1, 2, 2, 1); __PYX_ERR(0, 9, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_websocket_mask_cython") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_websocket_mask_cython") < 0)) __PYX_ERR(0, 9, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; @@ -777,14 +831,14 @@ static PyObject *__pyx_pw_7aiohttp_10_websocket_1_websocket_mask_cython(PyObject } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_websocket_mask_cython", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("_websocket_mask_cython", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 9, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("aiohttp._websocket._websocket_mask_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mask), (&PyBytes_Type), 1, "mask", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_data), (&PyByteArray_Type), 1, "data", 1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mask), (&PyBytes_Type), 1, "mask", 1))) __PYX_ERR(0, 9, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_data), (&PyByteArray_Type), 1, "data", 1))) __PYX_ERR(0, 9, __pyx_L1_error) __pyx_r = __pyx_pf_7aiohttp_10_websocket__websocket_mask_cython(__pyx_self, __pyx_v_mask, __pyx_v_data); /* function exit code */ @@ -813,9 +867,6 @@ static PyObject *__pyx_pf_7aiohttp_10_websocket__websocket_mask_cython(CYTHON_UN uint32_t *__pyx_t_6; Py_ssize_t __pyx_t_7; Py_ssize_t __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_websocket_mask_cython", 0); /* "aiohttp/_websocket.pyx":20 @@ -829,12 +880,12 @@ static PyObject *__pyx_pf_7aiohttp_10_websocket__websocket_mask_cython(CYTHON_UN if (unlikely(!Py_OptimizeFlag)) { if (unlikely(__pyx_v_mask == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 20, __pyx_L1_error) } - __pyx_t_1 = PyBytes_GET_SIZE(__pyx_v_mask); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyBytes_GET_SIZE(__pyx_v_mask); if (unlikely(__pyx_t_1 == -1)) __PYX_ERR(0, 20, __pyx_L1_error) if (unlikely(!((__pyx_t_1 == 4) != 0))) { PyErr_SetNone(PyExc_AssertionError); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 20, __pyx_L1_error) } } #endif @@ -846,7 +897,7 @@ static PyObject *__pyx_pf_7aiohttp_10_websocket__websocket_mask_cython(CYTHON_UN * in_buf = <unsigned char*>PyByteArray_AsString(data) * mask_buf = <const unsigned char*>PyBytes_AsString(mask) */ - __pyx_t_1 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_1 == -1)) __PYX_ERR(0, 22, __pyx_L1_error) __pyx_v_data_len = __pyx_t_1; /* "aiohttp/_websocket.pyx":23 @@ -856,7 +907,7 @@ static PyObject *__pyx_pf_7aiohttp_10_websocket__websocket_mask_cython(CYTHON_UN * mask_buf = <const unsigned char*>PyBytes_AsString(mask) * uint32_msk = (<uint32_t*>mask_buf)[0] */ - __pyx_t_2 = PyByteArray_AsString(__pyx_v_data); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyByteArray_AsString(__pyx_v_data); if (unlikely(__pyx_t_2 == NULL)) __PYX_ERR(0, 23, __pyx_L1_error) __pyx_v_in_buf = ((unsigned char *)__pyx_t_2); /* "aiohttp/_websocket.pyx":24 @@ -866,7 +917,7 @@ static PyObject *__pyx_pf_7aiohttp_10_websocket__websocket_mask_cython(CYTHON_UN * uint32_msk = (<uint32_t*>mask_buf)[0] * */ - __pyx_t_2 = PyBytes_AsString(__pyx_v_mask); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyBytes_AsString(__pyx_v_mask); if (unlikely(__pyx_t_2 == NULL)) __PYX_ERR(0, 24, __pyx_L1_error) __pyx_v_mask_buf = ((unsigned char const *)__pyx_t_2); /* "aiohttp/_websocket.pyx":25 @@ -1073,7 +1124,7 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_aiohttp__websocket, __pyx_k_aiohttp__websocket, sizeof(__pyx_k_aiohttp__websocket), 0, 0, 1, 1}, {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, {&__pyx_n_s_data_len, __pyx_k_data_len, sizeof(__pyx_k_data_len), 0, 0, 1, 1}, - {&__pyx_kp_s_home_andrew_projects_aiohttp_ai, __pyx_k_home_andrew_projects_aiohttp_ai, sizeof(__pyx_k_home_andrew_projects_aiohttp_ai), 0, 0, 1, 0}, + {&__pyx_kp_s_home_travis_build_KeepSafe_aioh, __pyx_k_home_travis_build_KeepSafe_aioh, sizeof(__pyx_k_home_travis_build_KeepSafe_aioh), 0, 0, 1, 0}, {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, {&__pyx_n_s_in_buf, __pyx_k_in_buf, sizeof(__pyx_k_in_buf), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, @@ -1087,7 +1138,7 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 45, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; @@ -1104,10 +1155,10 @@ static int __Pyx_InitCachedConstants(void) { * """Note, this function mutates it's `data` argument * """ */ - __pyx_tuple_ = PyTuple_Pack(8, __pyx_n_s_mask, __pyx_n_s_data, __pyx_n_s_data_len, __pyx_n_s_i, __pyx_n_s_in_buf, __pyx_n_s_mask_buf, __pyx_n_s_uint32_msk, __pyx_n_s_uint64_msk); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple_ = PyTuple_Pack(8, __pyx_n_s_mask, __pyx_n_s_data, __pyx_n_s_data_len, __pyx_n_s_i, __pyx_n_s_in_buf, __pyx_n_s_mask_buf, __pyx_n_s_uint32_msk, __pyx_n_s_uint64_msk); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); - __pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(2, 0, 8, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple_, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_andrew_projects_aiohttp_ai, __pyx_n_s_websocket_mask_cython, 9, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(2, 0, 8, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple_, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_travis_build_KeepSafe_aioh, __pyx_n_s_websocket_mask_cython, 9, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -1116,7 +1167,7 @@ static int __Pyx_InitCachedConstants(void) { } static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); return 0; __pyx_L1_error:; return -1; @@ -1131,9 +1182,6 @@ PyMODINIT_FUNC PyInit__websocket(void) #endif { PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); @@ -1145,23 +1193,24 @@ PyMODINIT_FUNC PyInit__websocket(void) } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__websocket(void)", 0); - if (__Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -1176,34 +1225,34 @@ PyMODINIT_FUNC PyInit__websocket(void) #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_aiohttp___websocket) { - if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "aiohttp._websocket")) { - if (unlikely(PyDict_SetItemString(modules, "aiohttp._websocket", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(PyDict_SetItemString(modules, "aiohttp._websocket", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ @@ -1215,14 +1264,14 @@ PyMODINIT_FUNC PyInit__websocket(void) #else sizeof(PyHeapTypeObject), #endif - 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 8; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(1, 9, __pyx_L1_error) + __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) __PYX_ERR(2, 8, __pyx_L1_error) + __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) __PYX_ERR(3, 15, __pyx_L1_error) /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "aiohttp/_websocket.pyx":9 @@ -1232,9 +1281,9 @@ PyMODINIT_FUNC PyInit__websocket(void) * """Note, this function mutates it's `data` argument * """ */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_10_websocket_1_websocket_mask_cython, NULL, __pyx_n_s_aiohttp__websocket); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_10_websocket_1_websocket_mask_cython, NULL, __pyx_n_s_aiohttp__websocket); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_websocket_mask_cython, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_websocket_mask_cython, __pyx_t_1) < 0) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "aiohttp/_websocket.pyx":1 @@ -1242,9 +1291,9 @@ PyMODINIT_FUNC PyInit__websocket(void) * * #from cpython cimport PyByteArray_AsString # cython still not exports that */ - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /*--- Wrapped vars code ---*/ @@ -1270,6 +1319,7 @@ PyMODINIT_FUNC PyInit__websocket(void) } /* --- Runtime support code --- */ +/* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -1286,6 +1336,7 @@ end: } #endif +/* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { @@ -1299,6 +1350,7 @@ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { return result; } +/* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, @@ -1324,6 +1376,7 @@ static void __Pyx_RaiseArgtupleInvalid( (num_expected == 1) ? "" : "s", num_found); } +/* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) @@ -1337,6 +1390,7 @@ static void __Pyx_RaiseDoubleKeywordsError( #endif } +/* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], @@ -1438,6 +1492,7 @@ bad: return -1; } +/* ArgTypeTest */ static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", @@ -1464,6 +1519,7 @@ static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, in return 0; } +/* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { @@ -1543,6 +1599,7 @@ static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { Py_INCREF(code_object); } +/* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" @@ -1623,6 +1680,7 @@ bad: Py_XDECREF(py_frame); } +/* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; @@ -1649,6 +1707,7 @@ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { } } +/* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ @@ -1670,10 +1729,7 @@ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { return (target_type) value;\ } -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" -#endif - +/* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; @@ -1749,7 +1805,7 @@ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) digits[0]) + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { @@ -1819,7 +1875,7 @@ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; - PyObject *v = __Pyx_PyNumber_Int(x); + PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; @@ -1842,7 +1898,7 @@ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { } } else { long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); @@ -1858,6 +1914,7 @@ raise_neg_overflow: return (long) -1; } +/* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; @@ -1933,7 +1990,7 @@ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) digits[0]) + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { @@ -2003,7 +2060,7 @@ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; - PyObject *v = __Pyx_PyNumber_Int(x); + PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; @@ -2026,7 +2083,7 @@ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { } } else { int val; - PyObject *tmp = __Pyx_PyNumber_Int(x); + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); @@ -2042,6 +2099,7 @@ raise_neg_overflow: return (int) -1; } +/* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); @@ -2057,6 +2115,7 @@ static int __Pyx_check_binary_version(void) { return 0; } +/* ModuleImport */ #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { @@ -2074,6 +2133,7 @@ bad: } #endif +/* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, @@ -2120,14 +2180,14 @@ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class #endif if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), - "%s.%s size changed, may indicate binary incompatibility", - module_name, class_name); + "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd", + module_name, class_name, basicsize, size); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, - "%.200s.%.200s has the wrong size, try recompiling", - module_name, class_name); + "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd", + module_name, class_name, basicsize, size); goto bad; } return (PyTypeObject *)result; @@ -2138,6 +2198,7 @@ bad: } #endif +/* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 @@ -2238,7 +2299,7 @@ static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } -static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; diff --git a/aiohttp/abc.py b/aiohttp/abc.py index 535b472..20c4d28 100644 --- a/aiohttp/abc.py +++ b/aiohttp/abc.py @@ -1,12 +1,13 @@ import asyncio import sys -from abc import ABCMeta, abstractmethod +from abc import ABC, abstractmethod +from http.cookies import SimpleCookie PY_35 = sys.version_info >= (3, 5) -class AbstractRouter(metaclass=ABCMeta): +class AbstractRouter(ABC): @asyncio.coroutine # pragma: no branch @abstractmethod @@ -14,20 +15,29 @@ class AbstractRouter(metaclass=ABCMeta): """Return MATCH_INFO for given request""" -class AbstractMatchInfo(metaclass=ABCMeta): +class AbstractMatchInfo(ABC): - @property # pragma: no branch + @asyncio.coroutine # pragma: no branch + @abstractmethod + def handler(self, request): + """Execute matched request handler""" + + @asyncio.coroutine # pragma: no branch @abstractmethod - def handler(self): - """Return handler for match info""" + def expect_handler(self, request): + """Expect handler for 100-continue processing""" @property # pragma: no branch @abstractmethod - def route(self): - """Return route for match info""" + def http_exception(self): + """HTTPException instance raised on router's resolving, or None""" + + @abstractmethod # pragma: no branch + def get_info(self): + """Return a dict with additional info useful for introspection""" -class AbstractView(metaclass=ABCMeta): +class AbstractView(ABC): def __init__(self, request): self._request = request @@ -36,13 +46,46 @@ class AbstractView(metaclass=ABCMeta): def request(self): return self._request - @asyncio.coroutine + @asyncio.coroutine # pragma: no branch @abstractmethod def __iter__(self): while False: # pragma: no cover yield None - if PY_35: + if PY_35: # pragma: no branch @abstractmethod def __await__(self): - return + return # pragma: no cover + + +class AbstractResolver(ABC): + + @asyncio.coroutine # pragma: no branch + @abstractmethod + def resolve(self, hostname): + """Return IP address for given hostname""" + + @asyncio.coroutine # pragma: no branch + @abstractmethod + def close(self): + """Release resolver""" + + +class AbstractCookieJar(ABC): + + def __init__(self, *, loop=None): + self._cookies = SimpleCookie() + self._loop = loop or asyncio.get_event_loop() + + @property + def cookies(self): + """The session cookies.""" + return self._cookies + + @abstractmethod + def update_cookies(self, cookies, response_url=None): + """Update cookies.""" + + @abstractmethod + def filter_cookies(self, request_url): + """Returns this jar's cookies filtered by their attributes.""" diff --git a/aiohttp/client.py b/aiohttp/client.py index 6d535b9..3af9cda 100644 --- a/aiohttp/client.py +++ b/aiohttp/client.py @@ -7,16 +7,17 @@ import os import sys import traceback import warnings -import http.cookies import urllib.parse +from multidict import MultiDictProxy, MultiDict, CIMultiDict, upstr + import aiohttp from .client_reqrep import ClientRequest, ClientResponse from .errors import WSServerHandshakeError -from .multidict import MultiDictProxy, MultiDict, CIMultiDict, upstr +from .helpers import CookieJar from .websocket import WS_KEY, WebSocketParser, WebSocketWriter from .websocket_client import ClientWebSocketResponse -from . import hdrs +from . import hdrs, helpers __all__ = ('ClientSession', 'request', 'get', 'options', 'head', @@ -35,7 +36,9 @@ class ClientSession: headers=None, skip_auto_headers=None, auth=None, request_class=ClientRequest, response_class=ClientResponse, - ws_response_class=ClientWebSocketResponse): + ws_response_class=ClientWebSocketResponse, + version=aiohttp.HttpVersion11, + cookie_jar=None): if connector is None: connector = aiohttp.TCPConnector(loop=loop) @@ -50,15 +53,15 @@ class ClientSession: if loop.get_debug(): self._source_traceback = traceback.extract_stack(sys._getframe(1)) - self._cookies = http.cookies.SimpleCookie() + if cookie_jar is None: + cookie_jar = CookieJar(loop=loop) + self._cookie_jar = cookie_jar - # For Backward compatability with `share_cookies` connectors - if connector._share_cookies: - self._update_cookies(connector.cookies) if cookies is not None: - self._update_cookies(cookies) + self._cookie_jar.update_cookies(cookies) self._connector = connector self._default_auth = auth + self._version = version # Convert to list of tuples if headers: @@ -97,12 +100,13 @@ class ClientSession: allow_redirects=True, max_redirects=10, encoding='utf-8', - version=aiohttp.HttpVersion11, + version=None, compress=None, chunked=None, expect100=False, read_until_eof=True): """Perform HTTP request.""" + return _RequestContextManager( self._request( method, @@ -131,19 +135,24 @@ class ClientSession: allow_redirects=True, max_redirects=10, encoding='utf-8', - version=aiohttp.HttpVersion11, + version=None, compress=None, chunked=None, expect100=False, read_until_eof=True): + if version is not None: + warnings.warn("HTTP version should be specified " + "by ClientSession constructor", DeprecationWarning) + else: + version = self._version + if self.closed: raise RuntimeError('Session is closed') redirects = 0 history = [] - if not isinstance(method, upstr): - method = upstr(method) + method = upstr(method) # Merge with default headers and transform to CIMultiDict headers = self._prepare_headers(headers) @@ -163,10 +172,13 @@ class ClientSession: skip_headers.add(upstr(i)) while True: + + cookies = self._cookie_jar.filter_cookies(url) + req = self._request_class( method, url, params=params, headers=headers, skip_auto_headers=skip_headers, data=data, - cookies=self.cookies, encoding=encoding, + cookies=cookies, encoding=encoding, auth=auth, version=version, compress=compress, chunked=chunked, expect100=expect100, loop=self._loop, response_class=self._response_class) @@ -186,10 +198,7 @@ class ClientSession: except OSError as exc: raise aiohttp.ClientOSError(*exc.args) from exc - self._update_cookies(resp.cookies) - # For Backward compatability with `share_cookie` connectors - if self._connector._share_cookies: - self._connector.update_cookies(resp.cookies) + self._cookie_jar.update_cookies(resp.cookies, resp.url) # redirects if resp.status in (301, 302, 303, 307) and allow_redirects: @@ -198,6 +207,13 @@ class ClientSession: if max_redirects and redirects >= max_redirects: resp.close() break + else: + # TODO: close the connection if BODY is large enough + # Redirect with big BODY is forbidden by HTTP protocol + # but malformed server may send illegal response. + # Small BODIES with text like "Not Found" are still + # perfectly fine and should be accepted. + yield from resp.release() # For 301 and 302, mimic IE behaviour, now changed in RFC. # Details: https://github.com/kennethreitz/requests/pull/269 @@ -218,6 +234,7 @@ class ClientSession: r_url = urllib.parse.urljoin(url, r_url) url = r_url + params = None yield from resp.release() continue @@ -232,7 +249,8 @@ class ClientSession: autoclose=True, autoping=True, auth=None, - origin=None): + origin=None, + headers=None): """Initiate websocket connection.""" return _WSRequestContextManager( self._ws_connect(url, @@ -241,7 +259,8 @@ class ClientSession: autoclose=autoclose, autoping=autoping, auth=auth, - origin=origin)) + origin=origin, + headers=headers)) @asyncio.coroutine def _ws_connect(self, url, *, @@ -250,16 +269,25 @@ class ClientSession: autoclose=True, autoping=True, auth=None, - origin=None): + origin=None, + headers=None): sec_key = base64.b64encode(os.urandom(16)) - headers = { + if headers is None: + headers = CIMultiDict() + + default_headers = { hdrs.UPGRADE: hdrs.WEBSOCKET, hdrs.CONNECTION: hdrs.UPGRADE, hdrs.SEC_WEBSOCKET_VERSION: '13', hdrs.SEC_WEBSOCKET_KEY: sec_key.decode(), } + + for key, value in default_headers.items(): + if key not in headers: + headers[key] = value + if protocols: headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = ','.join(protocols) if origin is not None: @@ -313,6 +341,7 @@ class ClientSession: break reader = resp.connection.reader.set_parser(WebSocketParser) + resp.connection.writer.set_tcp_nodelay(True) writer = WebSocketWriter(resp.connection.writer, use_mask=True) except Exception: resp.close() @@ -327,19 +356,6 @@ class ClientSession: autoping, self._loop) - def _update_cookies(self, cookies): - """Update shared cookies.""" - if isinstance(cookies, dict): - cookies = cookies.items() - - for name, value in cookies: - if isinstance(value, http.cookies.Morsel): - # use dict method because SimpleCookie class modifies value - # before Python 3.4 - dict.__setitem__(self.cookies, name, value) - else: - self.cookies[name] = value - def _prepare_headers(self, headers): """ Add default headers and transform it to CIMultiDict """ @@ -413,6 +429,9 @@ class ClientSession: if not self.closed: self._connector.close() self._connector = None + ret = helpers.create_future(self._loop) + ret.set_result(None) + return ret @property def closed(self): @@ -430,7 +449,12 @@ class ClientSession: @property def cookies(self): """The session cookies.""" - return self._cookies + return self._cookie_jar.cookies + + @property + def version(self): + """The session HTTP protocol version.""" + return self._version def detach(self): """Detach connector from session without closing the former. @@ -445,6 +469,15 @@ class ClientSession: def __exit__(self, exc_type, exc_val, exc_tb): self.close() + if PY_35: + @asyncio.coroutine + def __aenter__(self): + return self + + @asyncio.coroutine + def __aexit__(self, exc_type, exc_val, exc_tb): + yield from self.close() + if PY_35: from collections.abc import Coroutine base = Coroutine @@ -580,7 +613,7 @@ def request(method, url, *, allow_redirects=True, max_redirects=10, encoding='utf-8', - version=aiohttp.HttpVersion11, + version=None, compress=None, chunked=None, expect100=False, @@ -591,7 +624,7 @@ def request(method, url, *, response_class=None): """Constructs and sends a request. Returns response object. - :param str method: http method + :param str method: HTTP method :param str url: request url :param params: (optional) Dictionary or bytes to be sent in the query string of the new request @@ -604,7 +637,7 @@ def request(method, url, *, :type auth: aiohttp.helpers.BasicAuth :param bool allow_redirects: (optional) If set to False, do not follow redirects - :param version: Request http version. + :param version: Request HTTP version. :type version: aiohttp.protocol.HttpVersion :param bool compress: Set to True if request has to be compressed with deflate encoding. @@ -629,6 +662,7 @@ def request(method, url, *, >>> data = yield from resp.read() """ + warnings.warn("Use ClientSession().request() instead", DeprecationWarning) if connector is None: connector = aiohttp.TCPConnector(loop=loop, force_close=True) @@ -663,30 +697,37 @@ def request(method, url, *, def get(url, **kwargs): + warnings.warn("Use ClientSession().get() instead", DeprecationWarning) return request(hdrs.METH_GET, url, **kwargs) def options(url, **kwargs): + warnings.warn("Use ClientSession().options() instead", DeprecationWarning) return request(hdrs.METH_OPTIONS, url, **kwargs) def head(url, **kwargs): + warnings.warn("Use ClientSession().head() instead", DeprecationWarning) return request(hdrs.METH_HEAD, url, **kwargs) def post(url, **kwargs): + warnings.warn("Use ClientSession().post() instead", DeprecationWarning) return request(hdrs.METH_POST, url, **kwargs) def put(url, **kwargs): + warnings.warn("Use ClientSession().put() instead", DeprecationWarning) return request(hdrs.METH_PUT, url, **kwargs) def patch(url, **kwargs): + warnings.warn("Use ClientSession().patch() instead", DeprecationWarning) return request(hdrs.METH_PATCH, url, **kwargs) def delete(url, **kwargs): + warnings.warn("Use ClientSession().delete() instead", DeprecationWarning) return request(hdrs.METH_DELETE, url, **kwargs) @@ -694,6 +735,8 @@ def ws_connect(url, *, protocols=(), timeout=10.0, connector=None, auth=None, ws_response_class=ClientWebSocketResponse, autoclose=True, autoping=True, loop=None, origin=None, headers=None): + warnings.warn("Use ClientSession().ws_connect() instead", + DeprecationWarning) if loop is None: loop = asyncio.get_event_loop() diff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py index fac76af..1cf0916 100644 --- a/aiohttp/client_reqrep.py +++ b/aiohttp/client_reqrep.py @@ -15,12 +15,13 @@ try: except ImportError: import chardet +from multidict import (CIMultiDictProxy, MultiDictProxy, MultiDict, + CIMultiDict) + import aiohttp from . import hdrs, helpers, streams from .log import client_logger from .streams import EOF_MARKER, FlowControlStreamReader -from .multidict import (CIMultiDictProxy, MultiDictProxy, MultiDict, - CIMultiDict) from .multipart import MultipartWriter from .protocol import HttpMessage @@ -88,7 +89,7 @@ class ClientRequest: self.update_headers(headers) self.update_auto_headers(skip_auto_headers) self.update_cookies(cookies) - self.update_content_encoding() + self.update_content_encoding(data) self.update_auth(auth) self.update_body_from_data(data, skip_auto_headers) @@ -146,7 +147,7 @@ class ClientRequest: def update_version(self, version): """Convert request version to two elements tuple. - parser http version '1.1' => (1, 1) + parser HTTP version '1.1' => (1, 1) """ if isinstance(version, str): v = [l.strip() for l in version.split('.', 1)] @@ -229,8 +230,11 @@ class ClientRequest: self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip() - def update_content_encoding(self): + def update_content_encoding(self, data): """Set request content encoding.""" + if not data: + return + enc = self.headers.get(hdrs.CONTENT_ENCODING, '').lower() if enc: if self.compress is not False: @@ -251,9 +255,7 @@ class ClientRequest: return if not isinstance(auth, helpers.BasicAuth): - warnings.warn( - 'BasicAuth() tuple is required instead ', DeprecationWarning) - auth = helpers.BasicAuth(*auth) + raise TypeError('BasicAuth() tuple is required instead') self.headers[hdrs.AUTHORIZATION] = auth.encode() @@ -362,7 +364,7 @@ class ClientRequest: expect = True if expect: - self._continue = asyncio.Future(loop=self.loop) + self._continue = helpers.create_future(self.loop) @asyncio.coroutine def write_bytes(self, request, reader): @@ -373,6 +375,7 @@ class ClientRequest: try: if asyncio.iscoroutine(self.body): + request.transport.set_tcp_nodelay(True) exc = None value = None stream = self.body @@ -388,7 +391,7 @@ class ClientRequest: yield from request.write(exc.value, drain=True) break except: - self.response.close(True) + self.response.close() raise if isinstance(result, asyncio.Future): @@ -407,12 +410,14 @@ class ClientRequest: type(result)) elif isinstance(self.body, asyncio.StreamReader): + request.transport.set_tcp_nodelay(True) chunk = yield from self.body.read(streams.DEFAULT_LIMIT) while chunk: yield from request.write(chunk, drain=True) chunk = yield from self.body.read(streams.DEFAULT_LIMIT) elif isinstance(self.body, streams.DataQueue): + request.transport.set_tcp_nodelay(True) while True: try: chunk = yield from self.body.read() @@ -427,6 +432,7 @@ class ClientRequest: while chunk: request.write(chunk) chunk = self.body.read(self.chunked) + request.transport.set_tcp_nodelay(True) else: if isinstance(self.body, (bytes, bytearray)): @@ -434,6 +440,8 @@ class ClientRequest: for chunk in self.body: request.write(chunk) + request.transport.set_tcp_nodelay(True) + except Exception as exc: new_exc = aiohttp.ClientRequestError( 'Can not write request body for %s' % self.url) @@ -441,6 +449,7 @@ class ClientRequest: new_exc.__cause__ = exc reader.set_exception(new_exc) else: + assert request.transport.tcp_nodelay try: ret = request.write_eof() # NB: in asyncio 3.4.1+ StreamWriter.drain() is coroutine @@ -458,6 +467,7 @@ class ClientRequest: self._writer = None def send(self, writer, reader): + writer.set_tcp_cork(True) request = aiohttp.Request(writer, self.method, self.path, self.version) if self.compress: @@ -514,6 +524,7 @@ class ClientResponse: cookies = None # Response cookies (Set-Cookie) content = None # Payload stream headers = None # Response headers, CIMultiDictProxy + raw_headers = None # Response raw headers, a sequence of pairs _connection = None # current connection flow_control_class = FlowControlStreamReader # reader flow control @@ -558,8 +569,17 @@ class ClientResponse: def __repr__(self): out = io.StringIO() + ascii_encodable_url = self.url.encode('ascii', 'backslashreplace') \ + .decode('ascii') + if self.reason: + ascii_encodable_reason = self.reason.encode('ascii', + 'backslashreplace') \ + .decode('ascii') + else: + ascii_encodable_reason = self.reason print('<ClientResponse({}) [{} {}]>'.format( - self.url, self.status, self.reason), file=out) + ascii_encodable_url, self.status, ascii_encodable_reason), + file=out) print(self.headers, file=out) return out.getvalue() @@ -610,6 +630,7 @@ class ClientResponse: # headers self.headers = CIMultiDictProxy(message.headers) + self.raw_headers = tuple(message.raw_headers) # payload response_with_body = self._need_parse_response_body() @@ -650,12 +671,18 @@ class ClientResponse: @asyncio.coroutine def release(self): + if self._closed: + return try: content = self.content if content is not None and not content.at_eof(): chunk = yield from content.readany() while chunk is not EOF_MARKER or chunk: chunk = yield from content.readany() + except Exception: + self._connection.close() + self._connection = None + raise finally: self._closed = True if self._connection is not None: @@ -665,6 +692,12 @@ class ClientResponse: self._connection = None self._cleanup_writer() + def raise_for_status(self): + if 400 <= self.status: + raise aiohttp.HttpProcessingError( + code=self.status, + message=self.reason) + def _cleanup_writer(self): if self._writer is not None and not self._writer.done(): self._writer.cancel() diff --git a/aiohttp/connector.py b/aiohttp/connector.py index 919b6e8..9260599 100644 --- a/aiohttp/connector.py +++ b/aiohttp/connector.py @@ -3,7 +3,6 @@ import aiohttp import functools import http.cookies import ssl -import socket import sys import traceback import warnings @@ -14,13 +13,14 @@ from itertools import chain from math import ceil from types import MappingProxyType -from . import hdrs +from . import hdrs, helpers from .client import ClientRequest from .errors import ServerDisconnectedError from .errors import HttpProxyError, ProxyConnectionError from .errors import ClientOSError, ClientTimeoutError from .errors import FingerprintMismatch -from .helpers import BasicAuth +from .helpers import BasicAuth, is_ip_address +from .resolver import DefaultResolver __all__ = ('BaseConnector', 'TCPConnector', 'ProxyConnector', 'UnixConnector') @@ -99,6 +99,9 @@ class Connection(object): return self._transport is None +_default = object() + + class BaseConnector(object): """Base connector class. @@ -112,9 +115,19 @@ class BaseConnector(object): _closed = True # prevent AttributeError in __del__ if ctor was failed _source_traceback = None - def __init__(self, *, conn_timeout=None, keepalive_timeout=30, - share_cookies=False, force_close=False, limit=None, + def __init__(self, *, conn_timeout=None, keepalive_timeout=_default, + force_close=False, limit=None, loop=None): + + if force_close: + if keepalive_timeout is not None and \ + keepalive_timeout is not _default: + raise ValueError('keepalive_timeout cannot ' + 'be set if force_close is True') + else: + if keepalive_timeout is _default: + keepalive_timeout = 30 + if loop is None: loop = asyncio.get_event_loop() @@ -126,11 +139,6 @@ class BaseConnector(object): self._acquired = defaultdict(set) self._conn_timeout = conn_timeout self._keepalive_timeout = keepalive_timeout - if share_cookies: - warnings.warn( - 'Using `share_cookies` is deprecated. ' - 'Use Session object instead', DeprecationWarning) - self._share_cookies = share_cookies self._cleanup_handle = None self._force_close = force_close self._limit = limit @@ -222,14 +230,16 @@ class BaseConnector(object): def close(self): """Close all opened transports.""" + ret = helpers.create_future(self._loop) + ret.set_result(None) if self._closed: - return + return ret self._closed = True try: if hasattr(self._loop, 'is_closed'): if self._loop.is_closed(): - return + return ret for key, data in self._conns.items(): for transport, proto, t0 in data: @@ -245,6 +255,7 @@ class BaseConnector(object): self._conns.clear() self._acquired.clear() self._cleanup_handle = None + return ret @property def closed(self): @@ -279,7 +290,7 @@ class BaseConnector(object): limit = self._limit if limit is not None: - fut = asyncio.Future(loop=self._loop) + fut = helpers.create_future(self._loop) waiters = self._waiters[key] # The limit defines the maximum number of concurrent connections @@ -294,27 +305,33 @@ class BaseConnector(object): # This connection will now count towards the limit. waiters.append(fut) - yield from fut - - transport, proto = self._get(key) - if transport is None: - try: - if self._conn_timeout: - transport, proto = yield from asyncio.wait_for( - self._create_connection(req), - self._conn_timeout, loop=self._loop) - else: - transport, proto = yield from self._create_connection(req) - - except asyncio.TimeoutError as exc: - raise ClientTimeoutError( - 'Connection timeout to host {0[0]}:{0[1]} ssl:{0[2]}' - .format(key)) from exc - except OSError as exc: - raise ClientOSError( - exc.errno, - 'Cannot connect to host {0[0]}:{0[1]} ssl:{0[2]} [{1}]' - .format(key, exc.strerror)) from exc + try: + if limit is not None: + yield from fut + + transport, proto = self._get(key) + if transport is None: + try: + if self._conn_timeout: + transport, proto = yield from asyncio.wait_for( + self._create_connection(req), + self._conn_timeout, loop=self._loop) + else: + transport, proto = \ + yield from self._create_connection(req) + + except asyncio.TimeoutError as exc: + raise ClientTimeoutError( + 'Connection timeout to host {0[0]}:{0[1]} ssl:{0[2]}' + .format(key)) from exc + except OSError as exc: + raise ClientOSError( + exc.errno, + 'Cannot connect to host {0[0]}:{0[1]} ssl:{0[2]} [{1}]' + .format(key, exc.strerror)) from exc + except: + self._release_waiter(key) + raise self._acquired[key].add(transport) conn = Connection(self, key, req, transport, proto, self._loop) @@ -341,6 +358,14 @@ class BaseConnector(object): del self._conns[key] return None, None + def _release_waiter(self, key): + waiters = self._waiters[key] + while waiters: + waiter = waiters.pop(0) + if not waiter.done(): + waiter.set_result(None) + break + def _release(self, key, req, transport, protocol, *, should_close=False): if self._closed: # acquired connection is already released on connector closing @@ -355,12 +380,7 @@ class BaseConnector(object): pass else: if self._limit is not None and len(acquired) < self._limit: - waiters = self._waiters[key] - while waiters: - waiter = waiters.pop(0) - if not waiter.done(): - waiter.set_result(None) - break + self._release_waiter(key) resp = req.response @@ -400,15 +420,20 @@ class TCPConnector(BaseConnector): digest of the expected certificate in DER format to verify that the certificate the server presents matches. See also https://en.wikipedia.org/wiki/Transport_Layer_Security#Certificate_pinning - :param bool resolve: Set to True to do DNS lookup for host name. + :param bool resolve: (Deprecated) Set to True to do DNS lookup for + host name. + :param AbstractResolver resolver: Enable DNS lookups and use this + resolver + :param bool use_dns_cache: Use memory cache for DNS lookups. :param family: socket address family + :param local_addr: local :class:`tuple` of (host, port) to bind socket to :param args: see :class:`BaseConnector` :param kwargs: see :class:`BaseConnector` """ def __init__(self, *, verify_ssl=True, fingerprint=None, resolve=_marker, use_dns_cache=_marker, - family=0, ssl_context=None, + family=0, ssl_context=None, local_addr=None, resolver=None, **kwargs): super().__init__(**kwargs) @@ -443,10 +468,18 @@ class TCPConnector(BaseConnector): else: _use_dns_cache = False + self._resolver = resolver or DefaultResolver(loop=self._loop) + + if _use_dns_cache or resolver: + self._use_resolver = True + else: + self._use_resolver = False + self._use_dns_cache = _use_dns_cache self._cached_hosts = {} self._ssl_context = ssl_context self._family = family + self._local_addr = local_addr @property def verify_ssl(self): @@ -529,26 +562,24 @@ class TCPConnector(BaseConnector): @asyncio.coroutine def _resolve_host(self, host, port): + if not self._use_resolver or is_ip_address(host): + return [{'hostname': host, 'host': host, 'port': port, + 'family': self._family, 'proto': 0, 'flags': 0}] + + assert self._resolver + if self._use_dns_cache: key = (host, port) if key not in self._cached_hosts: - infos = yield from self._loop.getaddrinfo( - host, port, type=socket.SOCK_STREAM, family=self._family) - - hosts = [] - for family, _, proto, _, address in infos: - hosts.append( - {'hostname': host, - 'host': address[0], 'port': address[1], - 'family': family, 'proto': proto, - 'flags': socket.AI_NUMERICHOST}) - self._cached_hosts[key] = hosts - - return list(self._cached_hosts[key]) + self._cached_hosts[key] = yield from \ + self._resolver.resolve(host, port, family=self._family) + + return self._cached_hosts[key] else: - return [{'hostname': host, 'host': host, 'port': port, - 'family': self._family, 'proto': 0, 'flags': 0}] + res = yield from self._resolver.resolve( + host, port, family=self._family) + return res @asyncio.coroutine def _create_connection(self, req): @@ -572,7 +603,8 @@ class TCPConnector(BaseConnector): self._factory, host, port, ssl=sslcontext, family=hinfo['family'], proto=hinfo['proto'], flags=hinfo['flags'], - server_hostname=hinfo['hostname'] if sslcontext else None) + server_hostname=hinfo['hostname'] if sslcontext else None, + local_addr=self._local_addr) has_cert = transp.get_extra_info('sslcontext') if has_cert and self._fingerprint: sock = transp.get_extra_info('socket') @@ -601,7 +633,7 @@ class TCPConnector(BaseConnector): class ProxyConnector(TCPConnector): """Http Proxy connector. - :param str proxy: Proxy URL address. Only http proxy supported. + :param str proxy: Proxy URL address. Only HTTP proxy supported. :param proxy_auth: (optional) Proxy HTTP Basic Auth :type proxy_auth: aiohttp.helpers.BasicAuth :param args: see :class:`TCPConnector` diff --git a/aiohttp/errors.py b/aiohttp/errors.py index 3f19b6c..8d19cb0 100644 --- a/aiohttp/errors.py +++ b/aiohttp/errors.py @@ -1,4 +1,4 @@ -"""http related errors.""" +"""HTTP related errors.""" from asyncio import TimeoutError @@ -39,7 +39,7 @@ class ClientError(Exception): class ClientHttpProcessingError(ClientError): - """Base class for client http processing errors.""" + """Base class for client HTTP processing errors.""" class ClientRequestError(ClientHttpProcessingError): @@ -71,9 +71,9 @@ class ProxyConnectionError(ClientConnectionError): class HttpProcessingError(Exception): - """Http error. + """HTTP error. - Shortcut for raising http errors with custom code, message and headers. + Shortcut for raising HTTP errors with custom code, message and headers. :param int code: HTTP Error code. :param str message: (optional) Error message. @@ -98,7 +98,7 @@ class WSServerHandshakeError(HttpProcessingError): class HttpProxyError(HttpProcessingError): - """Http proxy error. + """HTTP proxy error. Raised in :class:`aiohttp.connector.ProxyConnector` if proxy responds with status other than ``200 OK`` @@ -145,6 +145,8 @@ class LineTooLong(BadHttpMessage): class InvalidHeader(BadHttpMessage): def __init__(self, hdr): + if isinstance(hdr, bytes): + hdr = hdr.decode('utf-8', 'surrogateescape') super().__init__('Invalid HTTP Header: {}'.format(hdr)) self.hdr = hdr diff --git a/aiohttp/file_sender.py b/aiohttp/file_sender.py new file mode 100644 index 0000000..428a9f3 --- /dev/null +++ b/aiohttp/file_sender.py @@ -0,0 +1,136 @@ +import asyncio +import mimetypes +import os +from . import hdrs +from .helpers import create_future +from .web_reqrep import StreamResponse + + +class FileSender: + """"A helper that can be used to send files. + """ + + def __init__(self, *, resp_factory=StreamResponse, chunk_size=256*1024): + self._response_factory = resp_factory + self._chunk_size = chunk_size + if bool(os.environ.get("AIOHTTP_NOSENDFILE")): + self._sendfile = self._sendfile_fallback + + def _sendfile_cb(self, fut, out_fd, in_fd, offset, + count, loop, registered): + if registered: + loop.remove_writer(out_fd) + try: + n = os.sendfile(out_fd, in_fd, offset, count) + if n == 0: # EOF reached + n = count + except (BlockingIOError, InterruptedError): + n = 0 + except Exception as exc: + fut.set_exception(exc) + return + + if n < count: + loop.add_writer(out_fd, self._sendfile_cb, fut, out_fd, in_fd, + offset + n, count - n, loop, True) + else: + fut.set_result(None) + + @asyncio.coroutine + def _sendfile_system(self, req, resp, fobj, count): + """ + Write `count` bytes of `fobj` to `resp` using + the ``sendfile`` system call. + + `req` should be a :obj:`aiohttp.web.Request` instance. + + `resp` should be a :obj:`aiohttp.web.StreamResponse` instance. + + `fobj` should be an open file object. + + `count` should be an integer > 0. + """ + transport = req.transport + + if transport.get_extra_info("sslcontext"): + yield from self._sendfile_fallback(req, resp, fobj, count) + return + + yield from resp.drain() + + loop = req.app.loop + # See https://github.com/KeepSafe/aiohttp/issues/958 for details + out_socket = transport.get_extra_info("socket").dup() + out_fd = out_socket.fileno() + in_fd = fobj.fileno() + fut = create_future(loop) + + try: + self._sendfile_cb(fut, out_fd, in_fd, 0, count, loop, False) + + yield from fut + finally: + out_socket.close() + + @asyncio.coroutine + def _sendfile_fallback(self, req, resp, fobj, count): + """ + Mimic the :meth:`_sendfile_system` method, but without using the + ``sendfile`` system call. This should be used on systems that don't + support the ``sendfile`` system call. + + To avoid blocking the event loop & to keep memory usage low, `fobj` is + transferred in chunks controlled by the `chunk_size` argument to + :class:`StaticRoute`. + """ + chunk_size = self._chunk_size + + chunk = fobj.read(chunk_size) + while chunk and count > chunk_size: + resp.write(chunk) + yield from resp.drain() + count = count - chunk_size + chunk = fobj.read(chunk_size) + + if chunk: + resp.write(chunk[:count]) + yield from resp.drain() + + if hasattr(os, "sendfile"): # pragma: no cover + _sendfile = _sendfile_system + else: # pragma: no cover + _sendfile = _sendfile_fallback + + @asyncio.coroutine + def send(self, req, filepath): + st = filepath.stat() + + modsince = req.if_modified_since + if modsince is not None and st.st_mtime <= modsince.timestamp(): + from .web_exceptions import HTTPNotModified + raise HTTPNotModified() + + ct, encoding = mimetypes.guess_type(str(filepath)) + if not ct: + ct = 'application/octet-stream' + + resp = self._response_factory() + resp.content_type = ct + if encoding: + resp.headers[hdrs.CONTENT_ENCODING] = encoding + resp.last_modified = st.st_mtime + + file_size = st.st_size + + resp.content_length = file_size + resp.set_tcp_cork(True) + try: + yield from resp.prepare(req) + + with filepath.open('rb') as f: + yield from self._sendfile(req, resp, f, file_size) + + finally: + resp.set_tcp_nodelay(True) + + return resp diff --git a/aiohttp/hdrs.py b/aiohttp/hdrs.py index 06c7936..cfccd3d 100644 --- a/aiohttp/hdrs.py +++ b/aiohttp/hdrs.py @@ -1,5 +1,5 @@ """HTTP Headers constants.""" -from .multidict import upstr +from multidict import upstr METH_ANY = upstr('*') METH_CONNECT = upstr('CONNECT') diff --git a/aiohttp/helpers.py b/aiohttp/helpers.py index 354f834..e518e70 100644 --- a/aiohttp/helpers.py +++ b/aiohttp/helpers.py @@ -2,24 +2,32 @@ import asyncio import base64 +import binascii import datetime import functools import io import os import re -from urllib.parse import quote, urlencode + from collections import namedtuple +from http.cookies import SimpleCookie, Morsel +from math import ceil +from pathlib import Path +from urllib.parse import quote, urlencode, urlsplit -from . import hdrs, multidict -from .errors import InvalidURL +import multidict +from . import hdrs +from .abc import AbstractCookieJar +from .errors import InvalidURL try: from asyncio import ensure_future except ImportError: ensure_future = asyncio.async -__all__ = ('BasicAuth', 'FormData', 'parse_mimetype', 'Timeout') +__all__ = ('BasicAuth', 'create_future', 'FormData', 'parse_mimetype', + 'Timeout', 'CookieJar') class BasicAuth(namedtuple('BasicAuth', ['login', 'password', 'encoding'])): @@ -39,12 +47,42 @@ class BasicAuth(namedtuple('BasicAuth', ['login', 'password', 'encoding'])): return super().__new__(cls, login, password, encoding) + @classmethod + def decode(cls, auth_header, encoding='latin1'): + """Create a :class:`BasicAuth` object from an ``Authorization`` HTTP + header.""" + split = auth_header.strip().split(' ') + if len(split) == 2: + if split[0].strip().lower() != 'basic': + raise ValueError('Unknown authorization method %s' % split[0]) + to_decode = split[1] + else: + raise ValueError('Could not parse authorization header.') + + try: + username, _, password = base64.b64decode( + to_decode.encode('ascii') + ).decode(encoding).partition(':') + except binascii.Error: + raise ValueError('Invalid base64 encoding.') + + return cls(username, password, encoding=encoding) + def encode(self): """Encode credentials.""" creds = ('%s:%s' % (self.login, self.password)).encode(self.encoding) return 'Basic %s' % base64.b64encode(creds).decode(self.encoding) +def create_future(loop): + """Compatiblity wrapper for the loop.create_future() call introduced in + 3.5.2.""" + if hasattr(loop, 'create_future'): + return loop.create_future() + else: + return asyncio.Future(loop=loop) + + class FormData: """Helper class for multipart/form-data and application/x-www-form-urlencoded body generation.""" @@ -204,7 +242,7 @@ def str_to_bytes(s, encoding='utf-8'): def guess_filename(obj, default=None): name = getattr(obj, 'name', None) if name and name[0] != '<' and name[-1] != '>': - return os.path.split(name)[-1] + return Path(name).name return default @@ -297,6 +335,8 @@ class AccessLogger: @staticmethod def _format_i(key, args): + if not args[0]: + return '(no headers)' return args[0].headers.get(multidict.upstr(key), '-') @staticmethod @@ -305,7 +345,8 @@ class AccessLogger: @staticmethod def _format_a(args): - return args[3].get_extra_info('peername')[0] + return args[3].get_extra_info('peername')[0] if args[3] is not None \ + else '-' @staticmethod def _format_t(args): @@ -356,7 +397,7 @@ class AccessLogger: :param message: Request object. May be None. :param environ: Environment dict. May be None. :param response: Response object. - :param transport: Tansport object. + :param transport: Tansport object. May be None :param float time: Time taken to serve the request. """ try: @@ -371,10 +412,10 @@ _marker = object() class reify: """Use as a class method decorator. It operates almost exactly like - the Python ``@property`` decorator, but it puts the result of the + the Python `@property` decorator, but it puts the result of the method it decorates into the instance dict after the first call, effectively replacing the function it decorates with an instance - variable. It is, in Python parlance, a non-data descriptor. + variable. It is, in Python parlance, a data descriptor. """ @@ -383,7 +424,7 @@ class reify: try: self.__doc__ = wrapped.__doc__ except: # pragma: no cover - pass + self.__doc__ = "" self.name = wrapped.__name__ def __get__(self, inst, owner, _marker=_marker): @@ -448,6 +489,41 @@ def requote_uri(uri): return quote(uri, safe=safe_without_percent) +_ipv4_pattern = ('^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}' + '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$') +_ipv6_pattern = ( + '^(?:(?:(?:[A-F0-9]{1,4}:){6}|(?=(?:[A-F0-9]{0,4}:){0,6}' + '(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)(([0-9A-F]{1,4}:){0,5}|:)' + '((:[0-9A-F]{1,4}){1,5}:|:)|::(?:[A-F0-9]{1,4}:){5})' + '(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}' + '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:[A-F0-9]{1,4}:){7}' + '[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}[A-F0-9]{0,4}$)' + '(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:)|(?:[A-F0-9]{1,4}:){7}' + ':|:(:[A-F0-9]{1,4}){7})$') +_ipv4_regex = re.compile(_ipv4_pattern) +_ipv6_regex = re.compile(_ipv6_pattern, flags=re.IGNORECASE) +_ipv4_regexb = re.compile(_ipv4_pattern.encode('ascii')) +_ipv6_regexb = re.compile(_ipv6_pattern.encode('ascii'), flags=re.IGNORECASE) + + +def is_ip_address(host): + if host is None: + return False + if isinstance(host, str): + if _ipv4_regex.match(host) or _ipv6_regex.match(host): + return True + else: + return False + elif isinstance(host, (bytes, bytearray, memoryview)): + if _ipv4_regexb.match(host) or _ipv6_regexb.match(host): + return True + else: + return False + else: + raise TypeError("{} [{}] is not a str or bytes" + .format(host, type(host))) + + class Timeout: """Timeout context manager. @@ -455,11 +531,11 @@ class Timeout: of code or in cases when asyncio.wait_for is not suitable. For example: >>> with aiohttp.Timeout(0.001): - >>> async with aiohttp.get('https://github.com') as r: - >>> await r.text() + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() - :param timeout: timeout value in seconds + :param timeout: timeout value in seconds or None to disable timeout logic :param loop: asyncio compatible event loop """ def __init__(self, timeout, *, loop=None): @@ -476,16 +552,273 @@ class Timeout: if self._task is None: raise RuntimeError('Timeout context manager should be used ' 'inside a task') - self._cancel_handler = self._loop.call_later( - self._timeout, self._cancel_task) + if self._timeout is not None: + self._cancel_handler = self._loop.call_later( + self._timeout, self._cancel_task) return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is asyncio.CancelledError and self._cancelled: + self._cancel_handler = None self._task = None - raise asyncio.TimeoutError - self._cancel_handler.cancel() + raise asyncio.TimeoutError from None + if self._timeout is not None: + self._cancel_handler.cancel() + self._cancel_handler = None self._task = None def _cancel_task(self): self._cancelled = self._task.cancel() + + +class CookieJar(AbstractCookieJar): + """Implements cookie storage adhering to RFC 6265.""" + + DATE_TOKENS_RE = re.compile( + "[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]*" + "(?P<token>[\x00-\x08\x0A-\x1F\d:a-zA-Z\x7F-\xFF]+)") + + DATE_HMS_TIME_RE = re.compile("(\d{1,2}):(\d{1,2}):(\d{1,2})") + + DATE_DAY_OF_MONTH_RE = re.compile("(\d{1,2})") + + DATE_MONTH_RE = re.compile( + "(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)", re.I) + + DATE_YEAR_RE = re.compile("(\d{2,4})") + + def __init__(self, *, unsafe=False, loop=None): + super().__init__(loop=loop) + self._host_only_cookies = set() + self._unsafe = unsafe + + def _expire_cookie(self, when, name, DAY=24*3600): + now = self._loop.time() + delta = when - now + if delta <= 0: + # expired + self._cookies.pop(name, None) + if delta > DAY: + # Huge timeouts (more than 24 days) breaks event loop + self._loop.call_at(ceil(now+DAY), self._expire_cookie, when, name) + else: + self._loop.call_at(ceil(when), self._expire_cookie, when, name) + + def update_cookies(self, cookies, response_url=None): + """Update cookies.""" + url_parsed = urlsplit(response_url or "") + hostname = url_parsed.hostname + + if not self._unsafe and is_ip_address(hostname): + # Don't accept cookies from IPs + return + + if isinstance(cookies, dict): + cookies = cookies.items() + + for name, value in cookies: + if isinstance(value, Morsel): + + if not self._add_morsel(name, value, hostname): + continue + + else: + self._cookies[name] = value + + cookie = self._cookies[name] + + if not cookie["domain"] and hostname is not None: + # Set the cookie's domain to the response hostname + # and set its host-only-flag + self._host_only_cookies.add(name) + cookie["domain"] = hostname + + if not cookie["path"] or not cookie["path"].startswith("/"): + # Set the cookie's path to the response path + path = url_parsed.path + if not path.startswith("/"): + path = "/" + else: + # Cut everything from the last slash to the end + path = "/" + path[1:path.rfind("/")] + cookie["path"] = path + + max_age = cookie["max-age"] + if max_age: + try: + delta_seconds = int(max_age) + self._expire_cookie(self._loop.time() + delta_seconds, + name) + except ValueError: + cookie["max-age"] = "" + + expires = cookie["expires"] + if not cookie["max-age"] and expires: + expire_time = self._parse_date(expires) + if expire_time: + self._expire_cookie(expire_time.timestamp(), + name) + else: + cookie["expires"] = "" + + # Remove the host-only flags of nonexistent cookies + self._host_only_cookies -= ( + self._host_only_cookies.difference(self._cookies.keys())) + + def _add_morsel(self, name, value, hostname): + """Add a Morsel to the cookie jar.""" + cookie_domain = value["domain"] + if cookie_domain.startswith("."): + # Remove leading dot + cookie_domain = cookie_domain[1:] + value["domain"] = cookie_domain + + if not cookie_domain or not hostname: + dict.__setitem__(self._cookies, name, value) + return True + + if not self._is_domain_match(cookie_domain, hostname): + # Setting cookies for different domains is not allowed + return False + + # use dict method because SimpleCookie class modifies value + # before Python 3.4 + dict.__setitem__(self._cookies, name, value) + return True + + def filter_cookies(self, request_url): + """Returns this jar's cookies filtered by their attributes.""" + url_parsed = urlsplit(request_url) + filtered = SimpleCookie() + + for name, cookie in self._cookies.items(): + cookie_domain = cookie["domain"] + + # Send shared cookies + if not cookie_domain: + dict.__setitem__(filtered, name, cookie) + continue + + hostname = url_parsed.hostname or "" + + if not self._unsafe and is_ip_address(hostname): + continue + + if name in self._host_only_cookies: + if cookie_domain != hostname: + continue + elif not self._is_domain_match(cookie_domain, hostname): + continue + + if not self._is_path_match(url_parsed.path, cookie["path"]): + continue + + is_secure = url_parsed.scheme in ("https", "wss") + + if cookie["secure"] and not is_secure: + continue + + dict.__setitem__(filtered, name, cookie) + + return filtered + + @staticmethod + def _is_domain_match(domain, hostname): + """Implements domain matching adhering to RFC 6265.""" + if hostname == domain: + return True + + if not hostname.endswith(domain): + return False + + non_matching = hostname[:-len(domain)] + + if not non_matching.endswith("."): + return False + + return not is_ip_address(hostname) + + @staticmethod + def _is_path_match(req_path, cookie_path): + """Implements path matching adhering to RFC 6265.""" + if req_path == cookie_path: + return True + + if not req_path.startswith(cookie_path): + return False + + if cookie_path.endswith("/"): + return True + + non_matching = req_path[len(cookie_path):] + + return non_matching.startswith("/") + + @classmethod + def _parse_date(cls, date_str): + """Implements date string parsing adhering to RFC 6265.""" + if not date_str: + return + + found_time = False + found_day_of_month = False + found_month = False + found_year = False + + hour = minute = second = 0 + day_of_month = 0 + month = "" + year = 0 + + for token_match in cls.DATE_TOKENS_RE.finditer(date_str): + + token = token_match.group("token") + + if not found_time: + time_match = cls.DATE_HMS_TIME_RE.match(token) + if time_match: + found_time = True + hour, minute, second = [ + int(s) for s in time_match.groups()] + continue + + if not found_day_of_month: + day_of_month_match = cls.DATE_DAY_OF_MONTH_RE.match(token) + if day_of_month_match: + found_day_of_month = True + day_of_month = int(day_of_month_match.group()) + continue + + if not found_month: + month_match = cls.DATE_MONTH_RE.match(token) + if month_match: + found_month = True + month = month_match.group() + continue + + if not found_year: + year_match = cls.DATE_YEAR_RE.match(token) + if year_match: + found_year = True + year = int(year_match.group()) + + if 70 <= year <= 99: + year += 1900 + elif 0 <= year <= 69: + year += 2000 + + if False in (found_day_of_month, found_month, found_year, found_time): + return + + if not 1 <= day_of_month <= 31: + return + + if year < 1601 or hour > 23 or minute > 59 or second > 59: + return + + dt = datetime.datetime.strptime( + "%s %d %d:%d:%d %d" % ( + month, day_of_month, hour, minute, second, year + ), "%b %d %H:%M:%S %Y") + + return dt.replace(tzinfo=datetime.timezone.utc) diff --git a/aiohttp/multidict.py b/aiohttp/multidict.py deleted file mode 100644 index 7037aa7..0000000 --- a/aiohttp/multidict.py +++ /dev/null @@ -1,385 +0,0 @@ -"""Multidict implementation. - -HTTP Headers and URL query string require specific data structure: -multidict. It behaves mostly like a dict but it can have -several values for the same key. -""" - - -from collections import abc -import os -import sys - -__all__ = ('MultiDictProxy', 'CIMultiDictProxy', - 'MultiDict', 'CIMultiDict', 'upstr') - -_marker = object() - - -class _upstr(str): - - """Case insensitive str.""" - - def __new__(cls, val='', - encoding=sys.getdefaultencoding(), errors='strict'): - if isinstance(val, (bytes, bytearray, memoryview)): - val = str(val, encoding, errors) - elif isinstance(val, str): - pass - else: - val = str(val) - val = val.upper() - return str.__new__(cls, val) - - def upper(self): - return self - - -class _Base: - - def getall(self, key, default=_marker): - """Return a list of all values matching the key.""" - res = [v for k, v in self._items if k == key] - if res: - return res - if not res and default is not _marker: - return default - raise KeyError('Key not found: %r' % key) - - def getone(self, key, default=_marker): - """Get first value matching the key.""" - for k, v in self._items: - if k == key: - return v - if default is not _marker: - return default - raise KeyError('Key not found: %r' % key) - - # Mapping interface # - - def __getitem__(self, key): - return self.getone(key, _marker) - - def get(self, key, default=None): - """Get first value matching the key. - - The method is alias for .getone(). - """ - return self.getone(key, default) - - def __iter__(self): - return iter(self.keys()) - - def __len__(self): - return len(self._items) - - def keys(self): - """Return a new view of the dictionary's keys.""" - return _KeysView(self._items) - - def items(self): - """Return a new view of the dictionary's items *(key, value) pairs).""" - return _ItemsView(self._items) - - def values(self): - """Return a new view of the dictionary's values.""" - return _ValuesView(self._items) - - def __eq__(self, other): - if not isinstance(other, abc.Mapping): - return NotImplemented - if isinstance(other, _Base): - return self._items == other._items - for k, v in self.items(): - nv = other.get(k, _marker) - if v != nv: - return False - return True - - def __contains__(self, key): - for k, v in self._items: - if k == key: - return True - return False - - def __repr__(self): - body = ', '.join("'{}': {!r}".format(k, v) for k, v in self.items()) - return '<{}({})>'.format(self.__class__.__name__, body) - - -class _CIBase(_Base): - - def getall(self, key, default=_marker): - """Return a list of all values matching the key.""" - return super().getall(key.upper(), default) - - def getone(self, key, default=_marker): - """Get first value matching the key.""" - return super().getone(key.upper(), default) - - def get(self, key, default=None): - """Get first value matching the key. - - The method is alias for .getone(). - """ - return super().get(key.upper(), default) - - def __getitem__(self, key): - return super().__getitem__(key.upper()) - - def __contains__(self, key): - return super().__contains__(key.upper()) - - -class _MultiDictProxy(_Base, abc.Mapping): - - def __init__(self, arg): - if not isinstance(arg, _MultiDict): - raise TypeError( - 'MultiDictProxy requires MultiDict instance, not {}'.format( - type(arg))) - - self._items = arg._items - - def copy(self): - """Return a copy of itself.""" - return _MultiDict(self.items()) - - -class _CIMultiDictProxy(_CIBase, _MultiDictProxy): - - def __init__(self, arg): - if not isinstance(arg, _CIMultiDict): - raise TypeError( - 'CIMultiDictProxy requires CIMultiDict instance, not {}' - .format(type(arg))) - - self._items = arg._items - - def copy(self): - """Return a copy of itself.""" - return _CIMultiDict(self.items()) - - -class _MultiDict(_Base, abc.MutableMapping): - - def __init__(self, *args, **kwargs): - self._items = [] - - self._extend(args, kwargs, self.__class__.__name__, self.add) - - def add(self, key, value): - """Add the key and value, not overwriting any previous value.""" - self._items.append((key, value)) - - def copy(self): - """Return a copy of itself.""" - cls = self.__class__ - return cls(self.items()) - - def extend(self, *args, **kwargs): - """Extend current MultiDict with more values. - - This method must be used instead of update. - """ - self._extend(args, kwargs, 'extend', self.add) - - def _extend(self, args, kwargs, name, method): - if len(args) > 1: - raise TypeError("{} takes at most 1 positional argument" - " ({} given)".format(name, len(args))) - if args: - arg = args[0] - if isinstance(args[0], _MultiDictProxy): - items = arg._items - elif isinstance(args[0], _MultiDict): - items = arg._items - elif hasattr(arg, 'items'): - items = arg.items() - else: - for item in arg: - if not len(item) == 2: - raise TypeError( - "{} takes either dict or list of (key, value) " - "tuples".format(name)) - items = arg - - for key, value in items: - method(key, value) - - for key, value in kwargs.items(): - method(key, value) - - def clear(self): - """Remove all items from MultiDict.""" - self._items.clear() - - # Mapping interface # - - def __setitem__(self, key, value): - self._replace(key, value) - - def __delitem__(self, key): - items = self._items - found = False - for i in range(len(items) - 1, -1, -1): - if items[i][0] == key: - del items[i] - found = True - if not found: - raise KeyError(key) - - def setdefault(self, key, default=None): - """Return value for key, set value to default if key is not present.""" - for k, v in self._items: - if k == key: - return v - self._items.append((key, default)) - return default - - def pop(self, key, default=_marker): - """Remove specified key and return the corresponding value. - - If key is not found, d is returned if given, otherwise - KeyError is raised. - - """ - value = None - found = False - for i in range(len(self._items) - 1, -1, -1): - if self._items[i][0] == key: - value = self._items[i][1] - del self._items[i] - found = True - if not found: - if default is _marker: - raise KeyError(key) - else: - return default - else: - return value - - def popitem(self): - """Remove and return an arbitrary (key, value) pair.""" - if self._items: - return self._items.pop(0) - else: - raise KeyError("empty multidict") - - def update(self, *args, **kwargs): - """Update the dictionary from *other*, overwriting existing keys.""" - self._extend(args, kwargs, 'update', self._replace) - - def _replace(self, key, value): - if key in self: - del self[key] - self.add(key, value) - - -class _CIMultiDict(_CIBase, _MultiDict): - - def add(self, key, value): - """Add the key and value, not overwriting any previous value.""" - super().add(key.upper(), value) - - def __setitem__(self, key, value): - super().__setitem__(key.upper(), value) - - def __delitem__(self, key): - super().__delitem__(key.upper()) - - def _replace(self, key, value): - super()._replace(key.upper(), value) - - def setdefault(self, key, default=None): - """Return value for key, set value to default if key is not present.""" - key = key.upper() - return super().setdefault(key, default) - - -class _ViewBase: - - def __init__(self, items): - self._items = items - - def __len__(self): - return len(self._items) - - -class _ItemsView(_ViewBase, abc.ItemsView): - - def __contains__(self, item): - assert isinstance(item, tuple) or isinstance(item, list) - assert len(item) == 2 - return item in self._items - - def __iter__(self): - yield from self._items - - def __repr__(self): - lst = [] - for item in self._items: - lst.append("{!r}: {!r}".format(item[0], item[1])) - body = ', '.join(lst) - return '{}({})'.format(self.__class__.__name__, body) - - -class _ValuesView(_ViewBase, abc.ValuesView): - - def __contains__(self, value): - for item in self._items: - if item[1] == value: - return True - return False - - def __iter__(self): - for item in self._items: - yield item[1] - - def __repr__(self): - lst = [] - for item in self._items: - lst.append("{!r}".format(item[1])) - body = ', '.join(lst) - return '{}({})'.format(self.__class__.__name__, body) - - -class _KeysView(_ViewBase, abc.KeysView): - - def __contains__(self, key): - for item in self._items: - if item[0] == key: - return True - return False - - def __iter__(self): - for item in self._items: - yield item[0] - - def __repr__(self): - lst = [] - for item in self._items: - lst.append("{!r}".format(item[0])) - body = ', '.join(lst) - return '{}({})'.format(self.__class__.__name__, body) - - -if bool(os.environ.get('AIOHTTP_NO_EXTENSIONS')): - MultiDictProxy = _MultiDictProxy - CIMultiDictProxy = _CIMultiDictProxy - MultiDict = _MultiDict - CIMultiDict = _CIMultiDict - upstr = _upstr -else: - try: - from ._multidict import (MultiDictProxy, - CIMultiDictProxy, - MultiDict, - CIMultiDict, - upstr) - except ImportError: # pragma: no cover - MultiDictProxy = _MultiDictProxy - CIMultiDictProxy = _CIMultiDictProxy - MultiDict = _MultiDict - CIMultiDict = _CIMultiDict - upstr = _upstr diff --git a/aiohttp/multipart.py b/aiohttp/multipart.py index 6d5cb3f..45dff95 100644 --- a/aiohttp/multipart.py +++ b/aiohttp/multipart.py @@ -11,9 +11,11 @@ import warnings import zlib from urllib.parse import quote, unquote, urlencode, parse_qsl from collections import deque, Mapping, Sequence +from pathlib import Path + +from multidict import CIMultiDict from .helpers import parse_mimetype -from .multidict import CIMultiDict from .protocol import HttpParser from .hdrs import ( CONTENT_DISPOSITION, @@ -212,6 +214,8 @@ class BodyPartReader(object): self._length = int(length) if length is not None else None self._read_bytes = 0 self._unread = deque() + self._prev_chunk = None + self._content_eof = 0 @asyncio.coroutine def __aiter__(self): @@ -257,7 +261,6 @@ class BodyPartReader(object): @asyncio.coroutine def read_chunk(self, size=chunk_size): """Reads body part content chunk of the specified size. - The body part must has `Content-Length` header with proper value. :param int size: chunk size @@ -265,18 +268,75 @@ class BodyPartReader(object): """ if self._at_eof: return b'' - assert self._length is not None, \ - 'Content-Length required for chunked read' - chunk_size = min(size, self._length - self._read_bytes) - chunk = yield from self._content.read(chunk_size) + if self._length: + chunk = yield from self._read_chunk_from_length(size) + else: + chunk = yield from self._read_chunk_from_stream(size) + self._read_bytes += len(chunk) if self._read_bytes == self._length: self._at_eof = True + if self._at_eof: assert b'\r\n' == (yield from self._content.readline()), \ 'reader did not read all the data or it is malformed' return chunk @asyncio.coroutine + def _read_chunk_from_length(self, size): + """Reads body part content chunk of the specified size. + The body part must has `Content-Length` header with proper value. + + :param int size: chunk size + + :rtype: bytearray + """ + assert self._length is not None, \ + 'Content-Length required for chunked read' + chunk_size = min(size, self._length - self._read_bytes) + chunk = yield from self._content.read(chunk_size) + return chunk + + @asyncio.coroutine + def _read_chunk_from_stream(self, size): + """Reads content chunk of body part with unknown length. + The `Content-Length` header for body part is not necessary. + + :param int size: chunk size + + :rtype: bytearray + """ + assert size >= len(self._boundary) + 2, \ + 'Chunk size must be greater or equal than boundary length + 2' + first_chunk = self._prev_chunk is None + if first_chunk: + self._prev_chunk = yield from self._content.read(size) + + chunk = yield from self._content.read(size) + self._content_eof += int(self._content.at_eof()) + assert self._content_eof < 3, "Reading after EOF" + window = self._prev_chunk + chunk + sub = b'\r\n' + self._boundary + if first_chunk: + idx = window.find(sub) + else: + idx = window.find(sub, max(0, len(self._prev_chunk) - len(sub))) + if idx >= 0: + # pushing boundary back to content + self._content.unread_data(window[idx:]) + if size > idx: + self._prev_chunk = self._prev_chunk[:idx] + chunk = window[len(self._prev_chunk):idx] + if not chunk: + self._at_eof = True + if 0 < len(chunk) < len(sub) and not self._content_eof: + self._prev_chunk += chunk + self._at_eof = False + return b'' + result = self._prev_chunk + self._prev_chunk = chunk + return result + + @asyncio.coroutine def readline(self): """Reads body part by line by line. @@ -450,6 +510,7 @@ class MultipartReader(object): self._content = content self._last_part = None self._at_eof = False + self._at_bof = True self._unread = [] @asyncio.coroutine @@ -484,10 +545,15 @@ class MultipartReader(object): @asyncio.coroutine def next(self): """Emits the next multipart body part.""" + # So, if we're at BOF, we need to skip till the boundary. if self._at_eof: return yield from self._maybe_release_last_part() - yield from self._read_boundary() + if self._at_bof: + yield from self._read_until_first_boundary() + self._at_bof = False + else: + yield from self._read_boundary() if self._at_eof: # we just read the last boundary, nothing to do there return self._last_part = yield from self.fetch_next_part() @@ -546,6 +612,20 @@ class MultipartReader(object): return (yield from self._content.readline()) @asyncio.coroutine + def _read_until_first_boundary(self): + while True: + chunk = yield from self._readline() + if chunk == b'': + raise ValueError("Could not find starting boundary %r" + % (self._boundary)) + chunk = chunk.rstrip() + if chunk == self._boundary: + return + elif chunk == self._boundary + b'--': + self._at_eof = True + return + + @asyncio.coroutine def _read_boundary(self): chunk = (yield from self._readline()).rstrip() if chunk == self._boundary: @@ -558,10 +638,10 @@ class MultipartReader(object): @asyncio.coroutine def _read_headers(self): - lines = [''] + lines = [b''] while True: chunk = yield from self._content.readline() - chunk = chunk.decode().strip() + chunk = chunk.strip() lines.append(chunk) if not chunk: break @@ -652,7 +732,7 @@ class BodyPartWriter(object): if isinstance(obj, io.IOBase): name = getattr(obj, 'name', None) if name is not None: - return os.path.basename(name) + return Path(name).name def serialize(self): """Yields byte chunks for body part.""" diff --git a/aiohttp/protocol.py b/aiohttp/protocol.py index 295306d..6214d0e 100644 --- a/aiohttp/protocol.py +++ b/aiohttp/protocol.py @@ -7,12 +7,12 @@ import re import string import sys import zlib -from abc import abstractmethod, ABCMeta +from abc import abstractmethod, ABC from wsgiref.handlers import format_date_time +from multidict import CIMultiDict, upstr import aiohttp from . import errors, hdrs -from .multidict import CIMultiDict, upstr from .log import internal_logger from .helpers import reify @@ -25,8 +25,7 @@ __all__ = ('HttpMessage', 'Request', 'Response', ASCIISET = set(string.printable) METHRE = re.compile('[A-Z0-9$-_.]+') VERSRE = re.compile('HTTP/(\d+).(\d+)') -HDRRE = re.compile('[\x00-\x1F\x7F()<>@,;:\[\]={} \t\\\\\"]') -CONTINUATION = (' ', '\t') +HDRRE = re.compile(b'[\x00-\x1F\x7F()<>@,;:\[\]={} \t\\\\\"]') EOF_MARKER = object() EOL_MARKER = object() STATUS_LINE_READY = object() @@ -43,12 +42,14 @@ RawStatusLineMessage = collections.namedtuple( RawRequestMessage = collections.namedtuple( 'RawRequestMessage', - ['method', 'path', 'version', 'headers', 'should_close', 'compression']) + ['method', 'path', 'version', 'headers', 'raw_headers', + 'should_close', 'compression']) RawResponseMessage = collections.namedtuple( 'RawResponseMessage', - ['version', 'code', 'reason', 'headers', 'should_close', 'compression']) + ['version', 'code', 'reason', 'headers', 'raw_headers', + 'should_close', 'compression']) class HttpParser: @@ -60,7 +61,7 @@ class HttpParser: self.max_field_size = max_field_size def parse_headers(self, lines): - """Parses RFC2822 headers from a stream. + """Parses RFC 5322 headers from a stream. Line continuations are supported. Returns list of header name and value pairs. Header name is in upper case. @@ -68,6 +69,7 @@ class HttpParser: close_conn = None encoding = None headers = CIMultiDict() + raw_headers = [] lines_idx = 1 line = lines[1] @@ -77,41 +79,44 @@ class HttpParser: # Parse initial header name : value pair. try: - name, value = line.split(':', 1) + bname, bvalue = line.split(b':', 1) except ValueError: raise errors.InvalidHeader(line) from None - name = name.strip(' \t').upper() - if HDRRE.search(name): - raise errors.InvalidHeader(name) + bname = bname.strip(b' \t').upper() + if HDRRE.search(bname): + raise errors.InvalidHeader(bname) # next line lines_idx += 1 line = lines[lines_idx] # consume continuation lines - continuation = line and line[0] in CONTINUATION + continuation = line and line[0] in (32, 9) # (' ', '\t') if continuation: - value = [value] + bvalue = [bvalue] while continuation: header_length += len(line) if header_length > self.max_field_size: raise errors.LineTooLong( 'limit request headers fields size') - value.append(line) + bvalue.append(line) # next line lines_idx += 1 line = lines[lines_idx] - continuation = line[0] in CONTINUATION - value = '\r\n'.join(value) + continuation = line[0] in (32, 9) # (' ', '\t') + bvalue = b'\r\n'.join(bvalue) else: if header_length > self.max_field_size: raise errors.LineTooLong( 'limit request headers fields size') - value = value.strip() + bvalue = bvalue.strip() + + name = bname.decode('utf-8', 'surrogateescape') + value = bvalue.decode('utf-8', 'surrogateescape') # keep-alive and encoding if name == hdrs.CONNECTION: @@ -126,8 +131,9 @@ class HttpParser: encoding = enc headers.add(name, value) + raw_headers.append((bname, bvalue)) - return headers, close_conn, encoding + return headers, raw_headers, close_conn, encoding class HttpPrefixParser: @@ -160,18 +166,17 @@ class HttpRequestParser(HttpParser): """ def __call__(self, out, buf): - # read http message (request line + headers) + # read HTTP message (request line + headers) try: raw_data = yield from buf.readuntil( b'\r\n\r\n', self.max_headers) except errors.LineLimitExceededParserError as exc: raise errors.LineTooLong(exc.limit) from None - lines = raw_data.decode( - 'utf-8', 'surrogateescape').split('\r\n') + lines = raw_data.split(b'\r\n') # request line - line = lines[0] + line = lines[0].decode('utf-8', 'surrogateescape') try: method, path, version = line.split(None, 2) except ValueError: @@ -193,7 +198,7 @@ class HttpRequestParser(HttpParser): raise errors.BadStatusLine(version) # read headers - headers, close, compression = self.parse_headers(lines) + headers, raw_headers, close, compression = self.parse_headers(lines) if close is None: # then the headers weren't set in the request if version <= HttpVersion10: # HTTP 1.0 must asks to not close close = True @@ -202,7 +207,8 @@ class HttpRequestParser(HttpParser): out.feed_data( RawRequestMessage( - method, path, version, headers, close, compression), + method, path, version, headers, raw_headers, + close, compression), len(raw_data)) out.feed_eof() @@ -214,17 +220,16 @@ class HttpResponseParser(HttpParser): Returns RawResponseMessage""" def __call__(self, out, buf): - # read http message (response line + headers) + # read HTTP message (response line + headers) try: raw_data = yield from buf.readuntil( b'\r\n\r\n', self.max_line_size + self.max_headers) except errors.LineLimitExceededParserError as exc: raise errors.LineTooLong(exc.limit) from None - lines = raw_data.decode( - 'utf-8', 'surrogateescape').split('\r\n') + lines = raw_data.split(b'\r\n') - line = lines[0] + line = lines[0].decode('utf-8', 'surrogateescape') try: version, status = line.split(None, 1) except ValueError: @@ -251,7 +256,7 @@ class HttpResponseParser(HttpParser): raise errors.BadStatusLine(line) # read headers - headers, close, compression = self.parse_headers(lines) + headers, raw_headers, close, compression = self.parse_headers(lines) if close is None: close = version <= HttpVersion10 @@ -259,7 +264,7 @@ class HttpResponseParser(HttpParser): out.feed_data( RawResponseMessage( version, status, reason.strip(), - headers, close, compression), + headers, raw_headers, close, compression), len(raw_data)) out.feed_eof() @@ -281,7 +286,8 @@ class HttpPayloadParser: length = 8 # payload decompression wrapper - if self.compression and self.message.compression: + if (self.response_with_body and + self.compression and self.message.compression): out = DeflateBuffer(out, self.message.compression) # payload parser @@ -476,7 +482,7 @@ def filter_pipe(filter, filter2, *, chunk = yield EOL_MARKER -class HttpMessage(metaclass=ABCMeta): +class HttpMessage(ABC): """HttpMessage allows to write headers and payload to a stream. For example, lets say we want to read file then compress it with deflate @@ -632,7 +638,7 @@ class HttpMessage(metaclass=ABCMeta): self.headers.add(name, value) def add_headers(self, *headers): - """Adds headers to a http message.""" + """Adds headers to a HTTP message.""" for name, value in headers: self.add_header(name, value) @@ -670,14 +676,18 @@ class HttpMessage(metaclass=ABCMeta): def _add_default_headers(self): # set the connection header + connection = None if self.upgrade: connection = 'upgrade' elif not self.closing if self.keepalive is None else self.keepalive: - connection = 'keep-alive' + if self.version == HttpVersion10: + connection = 'keep-alive' else: - connection = 'close' + if self.version == HttpVersion11: + connection = 'close' - self.headers[hdrs.CONNECTION] = connection + if connection is not None: + self.headers[hdrs.CONNECTION] = connection def write(self, chunk, *, drain=False, EOF_MARKER=EOF_MARKER, EOL_MARKER=EOL_MARKER): @@ -814,11 +824,11 @@ class HttpMessage(metaclass=ABCMeta): class Response(HttpMessage): - """Create http response message. + """Create HTTP response message. Transport is a socket stream transport. status is a response status code, status has to be integer value. http_version is a tuple that represents - http version, (1, 0) stands for HTTP/1.0 and (1, 1) is for HTTP/1.1 + HTTP version, (1, 0) stands for HTTP/1.0 and (1, 1) is for HTTP/1.1 """ HOP_HEADERS = () @@ -875,9 +885,9 @@ class Request(HttpMessage): def __init__(self, transport, method, path, http_version=HttpVersion11, close=False): - # set the default for HTTP 1.0 to be different + # set the default for HTTP 0.9 to be different # will only be overwritten with keep-alive header - if http_version < HttpVersion11: + if http_version < HttpVersion10: close = True super().__init__(transport, http_version, close) diff --git a/aiohttp/pytest_plugin.py b/aiohttp/pytest_plugin.py new file mode 100644 index 0000000..5d9a8f5 --- /dev/null +++ b/aiohttp/pytest_plugin.py @@ -0,0 +1,67 @@ +import asyncio +import contextlib + +import pytest + +from .test_utils import (TestClient, loop_context, setup_test_loop, + teardown_test_loop) + + +@contextlib.contextmanager +def _passthrough_loop_context(loop): + if loop: + # loop already exists, pass it straight through + yield loop + else: + # this shadows loop_context's standard behavior + loop = setup_test_loop() + yield loop + teardown_test_loop(loop) + + +def pytest_pycollect_makeitem(collector, name, obj): + """ + Fix pytest collecting for coroutines. + """ + if collector.funcnamefilter(name) and asyncio.iscoroutinefunction(obj): + return list(collector._genfunctions(name, obj)) + + +def pytest_pyfunc_call(pyfuncitem): + """ + Run coroutines in an event loop instead of a normal function call. + """ + if asyncio.iscoroutinefunction(pyfuncitem.function): + existing_loop = pyfuncitem.funcargs.get('loop', None) + with _passthrough_loop_context(existing_loop) as _loop: + testargs = {arg: pyfuncitem.funcargs[arg] + for arg in pyfuncitem._fixtureinfo.argnames} + + task = _loop.create_task(pyfuncitem.obj(**testargs)) + _loop.run_until_complete(task) + + return True + + +@pytest.yield_fixture +def loop(): + with loop_context() as _loop: + yield _loop + + +@pytest.yield_fixture +def test_client(loop): + client = None + + @asyncio.coroutine + def _create_from_app_factory(app_factory, *args, **kwargs): + nonlocal client + app = app_factory(loop, *args, **kwargs) + client = TestClient(app) + yield from client.start_server() + return client + + yield _create_from_app_factory + + if client: + client.close() diff --git a/aiohttp/resolver.py b/aiohttp/resolver.py new file mode 100644 index 0000000..b40dfa6 --- /dev/null +++ b/aiohttp/resolver.py @@ -0,0 +1,74 @@ +import socket +import asyncio +from .abc import AbstractResolver + +try: + import aiodns +except ImportError: + aiodns = None + + +class DefaultResolver(AbstractResolver): + """Use Executor for synchronous getaddrinfo() calls, which defaults to + concurrent.futures.ThreadPoolExecutor. + """ + + def __init__(self, loop=None): + if loop is None: + loop = asyncio.get_event_loop() + self._loop = loop + + @asyncio.coroutine + def resolve(self, host, port=0, family=socket.AF_INET): + infos = yield from self._loop.getaddrinfo( + host, port, type=socket.SOCK_STREAM, family=family) + + hosts = [] + for family, _, proto, _, address in infos: + hosts.append( + {'hostname': host, + 'host': address[0], 'port': address[1], + 'family': family, 'proto': proto, + 'flags': socket.AI_NUMERICHOST}) + + return hosts + + @asyncio.coroutine + def close(self): + pass + + +class AsyncResolver(AbstractResolver): + """Use the `aiodns` package to make asynchronous DNS lookups""" + + def __init__(self, loop=None, *args, **kwargs): + if loop is None: + loop = asyncio.get_event_loop() + + if aiodns is None: + raise RuntimeError("Resolver requires aiodns library") + + self._loop = loop + self._resolver = aiodns.DNSResolver(*args, loop=loop, **kwargs) + + @asyncio.coroutine + def resolve(self, host, port=0, family=socket.AF_INET): + if family == socket.AF_INET6: + qtype = 'AAAA' + else: + qtype = 'A' + + hosts = [] + resp = yield from self._resolver.query(host, qtype) + + for rr in resp: + hosts.append( + {'hostname': host, + 'host': rr.host, 'port': port, + 'family': family, 'proto': 0, + 'flags': socket.AI_NUMERICHOST}) + return hosts + + @asyncio.coroutine + def close(self): + return self._resolver.cancel() diff --git a/aiohttp/server.py b/aiohttp/server.py index c160b14..21c7a0d 100644 --- a/aiohttp/server.py +++ b/aiohttp/server.py @@ -1,4 +1,4 @@ -"""simple http server.""" +"""simple HTTP server.""" import asyncio import http.server @@ -10,7 +10,7 @@ from math import ceil import aiohttp from aiohttp import errors, streams, hdrs, helpers -from aiohttp.log import server_logger +from aiohttp.log import access_logger, server_logger from aiohttp.helpers import ensure_future __all__ = ('ServerHttpProtocol',) @@ -41,9 +41,9 @@ EMPTY_PAYLOAD = streams.EmptyStreamReader() class ServerHttpProtocol(aiohttp.StreamProtocol): - """Simple http protocol implementation. + """Simple HTTP protocol implementation. - ServerHttpProtocol handles incoming http request. It reads request line, + ServerHttpProtocol handles incoming HTTP request. It reads request line, request headers and request payload and calls handle_request() method. By default it always returns with 404 response. @@ -73,6 +73,12 @@ class ServerHttpProtocol(aiohttp.StreamProtocol): :param str access_log_format: access log format string :param loop: Optional event loop + + :param int max_line_size: Optional maximum header line size + + :param int max_field_size: Optional maximum header field size + + :param int max_headers: Optional maximum header size """ _request_count = 0 _request_handler = None @@ -81,18 +87,18 @@ class ServerHttpProtocol(aiohttp.StreamProtocol): _keep_alive_handle = None # keep alive timer handle _timeout_handle = None # slow request timer handle - _request_prefix = aiohttp.HttpPrefixParser() # http method parser - _request_parser = aiohttp.HttpRequestParser() # default request parser - def __init__(self, *, loop=None, keep_alive=75, # NGINX default value is 75 secs keep_alive_on=True, timeout=0, logger=server_logger, - access_log=None, + access_log=access_logger, access_log_format=helpers.AccessLogger.LOG_FORMAT, debug=False, log=None, + max_line_size=8190, + max_headers=32768, + max_field_size=8190, **kwargs): super().__init__( loop=loop, @@ -103,6 +109,12 @@ class ServerHttpProtocol(aiohttp.StreamProtocol): self._timeout = timeout # slow request timeout self._loop = loop if loop is not None else asyncio.get_event_loop() + self._request_prefix = aiohttp.HttpPrefixParser() + self._request_parser = aiohttp.HttpRequestParser( + max_line_size=max_line_size, + max_field_size=max_field_size, + max_headers=max_headers) + self.logger = log or logger self.debug = debug self.access_log = access_log @@ -229,7 +241,7 @@ class ServerHttpProtocol(aiohttp.StreamProtocol): payload = None try: - # read http request method + # read HTTP request method prefix = reader.set_parser(self._request_prefix) yield from prefix.read() @@ -252,7 +264,14 @@ class ServerHttpProtocol(aiohttp.StreamProtocol): self._timeout_handle = None # request may not have payload - if (message.headers.get(hdrs.CONTENT_LENGTH, 0) or + try: + content_length = int( + message.headers.get(hdrs.CONTENT_LENGTH, 0)) + except ValueError: + content_length = 0 + + if (content_length > 0 or + message.method == 'CONNECT' or hdrs.SEC_WEBSOCKET_KEY1 in message.headers or 'chunked' in message.headers.get( hdrs.TRANSFER_ENCODING, '')): @@ -319,7 +338,7 @@ class ServerHttpProtocol(aiohttp.StreamProtocol): payload=None, exc=None, headers=None, reason=None): """Handle errors. - Returns http response with specific status code. Logs additional + Returns HTTP response with specific status code. Logs additional information. It always closes current connection.""" now = self._loop.time() try: @@ -369,7 +388,7 @@ class ServerHttpProtocol(aiohttp.StreamProtocol): self.keep_alive(False) def handle_request(self, message, payload): - """Handle a single http request. + """Handle a single HTTP request. Subclass should override this method. By default it always returns 404 response. diff --git a/aiohttp/streams.py b/aiohttp/streams.py index a732c85..abc8be0 100644 --- a/aiohttp/streams.py +++ b/aiohttp/streams.py @@ -5,6 +5,7 @@ import functools import traceback from .log import internal_logger +from . import helpers __all__ = ( 'EofStream', 'StreamReader', 'DataQueue', 'ChunksQueue', @@ -51,14 +52,15 @@ class AsyncStreamReaderMixin: def iter_chunked(self, n): """Returns an asynchronous iterator that yields chunks of size n. - .. versionadded:: Python-3.5 available for Python 3.5+ only + Python-3.5 available for Python 3.5+ only """ return AsyncStreamIterator(lambda: self.read(n)) def iter_any(self): - """Returns an asynchronous iterator that yields slices of data as they come. + """Returns an asynchronous iterator that yields slices of data + as they come. - .. versionadded:: Python-3.5 available for Python 3.5+ only + Python-3.5 available for Python 3.5+ only """ return AsyncStreamIterator(self.readany) @@ -149,12 +151,24 @@ class StreamReader(asyncio.StreamReader, AsyncStreamReaderMixin): return assert self._eof_waiter is None - self._eof_waiter = asyncio.Future(loop=self._loop) + self._eof_waiter = helpers.create_future(self._loop) try: yield from self._eof_waiter finally: self._eof_waiter = None + def unread_data(self, data): + """ rollback reading some data from stream, inserting it to buffer head. + """ + if not data: + return + + if self._buffer_offset: + self._buffer[0] = self._buffer[0][self._buffer_offset:] + self._buffer_offset = 0 + self._buffer.appendleft(data) + self._buffer_size += len(data) + def feed_data(self, data): assert not self._eof, 'feed_data after feed_eof' @@ -179,7 +193,7 @@ class StreamReader(asyncio.StreamReader, AsyncStreamReaderMixin): if self._waiter is not None: raise RuntimeError('%s() called while another coroutine is ' 'already waiting for incoming data' % func_name) - return asyncio.Future(loop=self._loop) + return helpers.create_future(self._loop) @asyncio.coroutine def readline(self): @@ -428,7 +442,7 @@ class DataQueue: raise self._exception assert not self._waiter - self._waiter = asyncio.Future(loop=self._loop) + self._waiter = helpers.create_future(self._loop) try: yield from self._waiter except (asyncio.CancelledError, asyncio.TimeoutError): diff --git a/aiohttp/test_utils.py b/aiohttp/test_utils.py index 562a67f..2c6aa17 100644 --- a/aiohttp/test_utils.py +++ b/aiohttp/test_utils.py @@ -4,22 +4,33 @@ import cgi import contextlib import gc import email.parser +import functools import http.server import json import logging import io import os import re +import socket import ssl import sys import threading import traceback import urllib.parse +import unittest +from unittest import mock import asyncio import aiohttp -from aiohttp import server -from aiohttp import helpers +from multidict import CIMultiDict + +from . import server +from . import helpers +from . import ClientSession +from . import hdrs +from .protocol import HttpVersion +from .protocol import RawRequestMessage +from .signals import Signal def run_briefly(loop): @@ -121,7 +132,7 @@ def run_server(loop, *, listen_addr=('127.0.0.1', 0), listen_addr, ssl=sslcontext) server = thread_loop.run_until_complete(server_coroutine) - waiter = asyncio.Future(loop=thread_loop) + waiter = helpers.create_future(thread_loop) loop.call_soon_threadsafe( fut.set_result, (thread_loop, waiter, server.sockets[0].getsockname())) @@ -143,7 +154,7 @@ def run_server(loop, *, listen_addr=('127.0.0.1', 0), thread_loop.close() gc.collect() - fut = asyncio.Future(loop=loop) + fut = helpers.create_future(loop) server_thread = threading.Thread(target=run, args=(loop, fut)) server_thread.start() @@ -304,3 +315,333 @@ class Router: # keep-alive if response.keep_alive(): self._srv.keep_alive(True) + + +def unused_port(): + """ return a port that is unused on the current host. """ + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(('127.0.0.1', 0)) + return s.getsockname()[1] + + +class TestClient: + """ + A test client implementation, for a aiohttp.web.Application. + + :param app: the aiohttp.web application passed to create_test_server + + :type app: aiohttp.web.Application + + :param protocol: http or https + + :type protocol: str + + TestClient can also be used as a contextmanager, returning + the instance of itself instantiated. + """ + _address = '127.0.0.1' + + def __init__(self, app, protocol="http"): + self.app = app + self._loop = loop = app.loop + self.port = unused_port() + self._handler = app.make_handler() + self._server = None + if not loop.is_running(): + loop.run_until_complete(self.start_server()) + self._session = ClientSession( + loop=self._loop, + cookie_jar=aiohttp.CookieJar(unsafe=True, + loop=self._loop)) + self._root = '{}://{}:{}'.format(protocol, self._address, self.port) + self._closed = False + + @asyncio.coroutine + def start_server(self): + self._server = yield from self._loop.create_server( + self._handler, self._address, self.port + ) + + @property + def session(self): + """a raw handler to the aiohttp.ClientSession. unlike the methods on + the TestClient, client session requests do not automatically + include the host in the url queried, and will require an + absolute path to the resource. + """ + return self._session + + def request(self, method, path, *args, **kwargs): + """ routes a request to the http server. + the interface is identical to asyncio.request, + except the loop kwarg is overriden + by the instance used by the application. + """ + return self._session.request( + method, self._root + path, *args, **kwargs + ) + + def get(self, path, *args, **kwargs): + """Perform an HTTP GET request. """ + return self.request(hdrs.METH_GET, path, *args, **kwargs) + + def post(self, path, *args, **kwargs): + """Perform an HTTP POST request. """ + return self.request(hdrs.METH_POST, path, *args, **kwargs) + + def options(self, path, *args, **kwargs): + """Perform an HTTP OPTIONS request. """ + return self.request(hdrs.METH_OPTIONS, path, *args, **kwargs) + + def head(self, path, *args, **kwargs): + """Perform an HTTP HEAD request. """ + return self.request(hdrs.METH_HEAD, path, *args, **kwargs) + + def put(self, path, *args, **kwargs): + """Perform an HTTP PUT request.""" + return self.request(hdrs.METH_PUT, path, *args, **kwargs) + + def patch(self, path, *args, **kwargs): + """Perform an HTTP PATCH request.""" + return self.request(hdrs.METH_PATCH, path, *args, **kwargs) + + def delete(self, path, *args, **kwargs): + """Perform an HTTP PATCH request.""" + return self.request(hdrs.METH_DELETE, path, *args, **kwargs) + + def ws_connect(self, path, *args, **kwargs): + """Initiate websocket connection. the api is identical to + aiohttp.ClientSession.ws_connect. + """ + return self._session.ws_connect( + self._root + path, *args, **kwargs + ) + + def close(self): + """ close all fixtures created by the test client. + After that point, the TestClient is no longer + usable. + + This is an idempotent function: running close + multiple times will not have any additional effects. + + close is also run when the object is garbage collected, + and on exit when used as a context manager. + """ + if not self._closed: + loop = self._loop + loop.run_until_complete(self._session.close()) + self._server.close() + loop.run_until_complete(self._server.wait_closed()) + loop.run_until_complete(self.app.shutdown()) + loop.run_until_complete(self._handler.finish_connections()) + loop.run_until_complete(self.app.cleanup()) + self._closed = True + + def __del__(self): + self.close() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + +class AioHTTPTestCase(unittest.TestCase): + """A base class to allow for unittest web applications using + aiohttp. + + provides the following: + + * self.client (aiohttp.test_utils.TestClient): an aiohttp test client. + * self.loop (asyncio.BaseEventLoop): the event loop in which the + application and server are running. + * self.app (aiohttp.web.Application): the application returned by + self.get_app() + + note that the TestClient's methods are asynchronous: you will have to + execute function on the test client using asynchronous methods. + """ + + def get_app(self, loop): + """ + this method should be overriden + to return the aiohttp.web.Application + object to test. + + :param loop: the event_loop to use + :type loop: asyncio.BaseEventLoop + """ + pass + + def setUp(self): + self.loop = setup_test_loop() + self.app = self.get_app(self.loop) + self.client = TestClient(self.app) + + def tearDown(self): + del self.client + teardown_test_loop(self.loop) + + +def unittest_run_loop(func): + """a decorator that should be used with asynchronous methods of an + AioHTTPTestCase. Handles executing an asynchronous function, using + the self.loop of the AioHTTPTestCase. + """ + + @functools.wraps(func) + def new_func(self): + return self.loop.run_until_complete(func(self)) + + return new_func + + +@contextlib.contextmanager +def loop_context(): + """a contextmanager that creates an event_loop, for test purposes. + handles the creation and cleanup of a test loop. + """ + loop = setup_test_loop() + yield loop + teardown_test_loop(loop) + + +def setup_test_loop(): + """create and return an asyncio.BaseEventLoop + instance. The caller should also call teardown_test_loop, + once they are done with the loop. + """ + loop = asyncio.new_event_loop() + asyncio.set_event_loop(None) + return loop + + +def teardown_test_loop(loop): + """teardown and cleanup an event_loop created + by setup_test_loop. + + :param loop: the loop to teardown + :type loop: asyncio.BaseEventLoop + """ + is_closed = getattr(loop, 'is_closed') + if is_closed is not None: + closed = is_closed() + else: + closed = loop._closed + if not closed: + loop.call_soon(loop.stop) + loop.run_forever() + loop.close() + gc.collect() + asyncio.set_event_loop(None) + + +def _create_app_mock(): + app = mock.Mock() + app._debug = False + app.on_response_prepare = Signal(app) + return app + + +def _create_transport(sslcontext=None): + transport = mock.Mock() + + def get_extra_info(key): + if key == 'sslcontext': + return sslcontext + else: + return None + + transport.get_extra_info.side_effect = get_extra_info + return transport + + +_not_set = object() + + +def make_mocked_request(method, path, headers=CIMultiDict(), *, + version=HttpVersion(1, 1), closing=False, + app=None, + reader=_not_set, + writer=_not_set, + transport=_not_set, + payload=_not_set, + sslcontext=None, + secure_proxy_ssl_header=None): + """Creates mocked web.Request testing purposes. Useful in unit tests, + when spinning full web server is overkill or specific conditions and + errors is hard to trigger. + + :param method: str, that represents HTTP method, like; GET, POST. + :type method: str + + :param path: str, The URL including *PATH INFO* without the host or scheme + :type path: multidict.CIMultiDict + + :param headers: str, The URL including *PATH INFO* without the host + or scheme + :type headers: str + + :param version: namedtuple with encoded HTTP version + :type version: aiohttp.protocol.HttpVersion + + :param closing: flag idicates that connection should be closed after + response. + :type closing: bool + + :param app: the aiohttp.web application attached for fake request + :type app: aiohttp.web.Application + + :param reader: object for storing and managing incoming data + :type reader: aiohttp.parsers.StreamParser + + :param writer: object for managing outcoming data + :type wirter: aiohttp.parsers.StreamWriter + + :param transport: asyncio transport instance + :type transport: asyncio.transports.Transport + + :param payload: raw payload reader object + :type payload: aiohttp.streams.FlowControlStreamReader + + :param sslcontext: ssl.SSLContext object, for HTTPS connection + :type sslcontext: ssl.SSLContext + + :param secure_proxy_ssl_header: A tuple representing a HTTP header/value + combination that signifies a request is secure. + :type secure_proxy_ssl_header: tuple + """ + + if version < HttpVersion(1, 1): + closing = True + message = RawRequestMessage(method, path, version, headers, + [(k.encode('utf-8'), v.encode('utf-8')) + for k, v in headers.items()], + closing, False) + if app is None: + app = _create_app_mock() + + if reader is _not_set: + reader = mock.Mock() + + if writer is _not_set: + writer = mock.Mock() + + if transport is _not_set: + transport = _create_transport(sslcontext) + + if payload is _not_set: + payload = mock.Mock() + + from .web import Request + req = Request(app, message, payload, + transport, reader, writer, + secure_proxy_ssl_header=secure_proxy_ssl_header) + + assert req.app is app + assert req.content is payload + assert req.transport is transport + + return req diff --git a/aiohttp/web.py b/aiohttp/web.py index 61ea36e..753be84 100644 --- a/aiohttp/web.py +++ b/aiohttp/web.py @@ -1,21 +1,24 @@ +import asyncio +import warnings +import sys + + +from . import hdrs from . import web_reqrep from . import web_exceptions from . import web_urldispatcher from . import web_ws +from .abc import AbstractRouter, AbstractMatchInfo +from .log import web_logger +from .protocol import HttpVersion # noqa +from .server import ServerHttpProtocol +from .signals import Signal, PreSignal, PostSignal from .web_reqrep import * # noqa from .web_exceptions import * # noqa from .web_urldispatcher import * # noqa from .web_ws import * # noqa -from .protocol import HttpVersion # noqa -from .signals import Signal, PreSignal, PostSignal - - -import asyncio - -from . import hdrs -from .abc import AbstractRouter, AbstractMatchInfo -from .log import web_logger -from .server import ServerHttpProtocol +from argparse import ArgumentParser +from importlib import import_module __all__ = (web_reqrep.__all__ + @@ -62,7 +65,7 @@ class RequestHandler(ServerHttpProtocol): now = self._loop.time() app = self._app - request = Request( + request = web_reqrep.Request( app, message, payload, self.transport, self.reader, self.writer, secure_proxy_ssl_header=self._secure_proxy_ssl_header) @@ -76,9 +79,9 @@ class RequestHandler(ServerHttpProtocol): resp = None request._match_info = match_info expect = request.headers.get(hdrs.EXPECT) - if expect and expect.lower() == "100-continue": + if expect: resp = ( - yield from match_info.route.handle_expect_header(request)) + yield from match_info.expect_handler(request)) if resp is None: handler = match_info.handler @@ -86,11 +89,11 @@ class RequestHandler(ServerHttpProtocol): handler = yield from factory(app, handler) resp = yield from handler(request) - assert isinstance(resp, StreamResponse), \ + assert isinstance(resp, web_reqrep.StreamResponse), \ ("Handler {!r} should return response instance, " "got {!r} [middlewares {!r}]").format( match_info.handler, type(resp), self._middlewares) - except HTTPException as exc: + except web_exceptions.HTTPException as exc: resp = exc resp_msg = yield from resp.prepare(request) @@ -139,6 +142,14 @@ class RequestHandlerFactory: del self._connections[handler] @asyncio.coroutine + def _connections_cleanup(self): + sleep = 0.05 + while self._connections: + yield from asyncio.sleep(sleep, loop=self._loop) + if sleep < 5: + sleep = sleep * 2 + + @asyncio.coroutine def finish_connections(self, timeout=None): # try to close connections in 90% of graceful timeout timeout90 = None @@ -148,18 +159,10 @@ class RequestHandlerFactory: for handler in self._connections.keys(): handler.closing(timeout=timeout90) - @asyncio.coroutine - def cleanup(): - sleep = 0.05 - while self._connections: - yield from asyncio.sleep(sleep, loop=self._loop) - if sleep < 5: - sleep = sleep * 2 - if timeout: try: yield from asyncio.wait_for( - cleanup(), timeout, loop=self._loop) + self._connections_cleanup(), timeout, loop=self._loop) except asyncio.TimeoutError: self._app.logger.warning( "Not all connections are closed (pending: %d)", @@ -190,13 +193,12 @@ class Application(dict): if loop is None: loop = asyncio.get_event_loop() if router is None: - router = UrlDispatcher() + router = web_urldispatcher.UrlDispatcher() assert isinstance(router, AbstractRouter), router self._debug = debug self._router = router self._handler_factory = handler_factory - self._finish_callbacks = [] self._loop = loop self.logger = logger @@ -207,6 +209,8 @@ class Application(dict): self._on_pre_signal = PreSignal() self._on_post_signal = PostSignal() self._on_response_prepare = Signal(self) + self._on_shutdown = Signal(self) + self._on_cleanup = Signal(self) @property def debug(self): @@ -225,6 +229,14 @@ class Application(dict): return self._on_post_signal @property + def on_shutdown(self): + return self._on_shutdown + + @property + def on_cleanup(self): + return self._on_cleanup + + @property def router(self): return self._router @@ -241,25 +253,33 @@ class Application(dict): self, self.router, loop=self.loop, **kwargs) @asyncio.coroutine + def shutdown(self): + """Causes on_shutdown signal + + Should be called before cleanup() + """ + yield from self.on_shutdown.send(self) + + @asyncio.coroutine + def cleanup(self): + """Causes on_cleanup signal + + Should be called after shutdown() + """ + yield from self.on_cleanup.send(self) + + @asyncio.coroutine def finish(self): - callbacks = self._finish_callbacks - self._finish_callbacks = [] + """Finalize an application. - for (cb, args, kwargs) in callbacks: - try: - res = cb(self, *args, **kwargs) - if (asyncio.iscoroutine(res) or - isinstance(res, asyncio.Future)): - yield from res - except Exception as exc: - self._loop.call_exception_handler({ - 'message': "Error in finish callback", - 'exception': exc, - 'application': self, - }) + Deprecated alias for .cleanup() + """ + warnings.warn("Use .cleanup() instead", DeprecationWarning) + yield from self.cleanup() def register_on_finish(self, func, *args, **kwargs): - self._finish_callbacks.insert(0, (func, args, kwargs)) + warnings.warn("Use .on_cleanup.append() instead", DeprecationWarning) + self.on_cleanup.append(lambda app: func(app, *args, **kwargs)) def copy(self): raise NotImplementedError @@ -270,3 +290,87 @@ class Application(dict): def __repr__(self): return "<Application>" + + +def run_app(app, *, host='0.0.0.0', port=None, + shutdown_timeout=60.0, ssl_context=None, + print=print, backlog=128): + """Run an app locally""" + if port is None: + if not ssl_context: + port = 8080 + else: + port = 8443 + + loop = app.loop + + handler = app.make_handler() + srv = loop.run_until_complete(loop.create_server(handler, host, port, + ssl=ssl_context, + backlog=backlog)) + + scheme = 'https' if ssl_context else 'http' + print("======== Running on {scheme}://{host}:{port}/ ========\n" + "(Press CTRL+C to quit)".format( + scheme=scheme, host=host, port=port)) + + try: + loop.run_forever() + except KeyboardInterrupt: # pragma: no branch + pass + finally: + srv.close() + loop.run_until_complete(srv.wait_closed()) + loop.run_until_complete(app.shutdown()) + loop.run_until_complete(handler.finish_connections(shutdown_timeout)) + loop.run_until_complete(app.cleanup()) + loop.close() + + +def main(argv): + arg_parser = ArgumentParser( + description="aiohttp.web Application server", + prog="aiohttp.web" + ) + arg_parser.add_argument( + "entry_func", + help=("Callable returning the `aiohttp.web.Application` instance to " + "run. Should be specified in the 'module:function' syntax."), + metavar="entry-func" + ) + arg_parser.add_argument( + "-H", "--hostname", + help="TCP/IP hostname to serve on (default: %(default)r)", + default="localhost" + ) + arg_parser.add_argument( + "-P", "--port", + help="TCP/IP port to serve on (default: %(default)r)", + type=int, + default="8080" + ) + args, extra_argv = arg_parser.parse_known_args(argv) + + # Import logic + mod_str, _, func_str = args.entry_func.partition(":") + if not func_str or not mod_str: + arg_parser.error( + "'entry-func' not in 'module:function' syntax" + ) + if mod_str.startswith("."): + arg_parser.error("relative module names not supported") + try: + module = import_module(mod_str) + except ImportError: + arg_parser.error("module %r not found" % mod_str) + try: + func = getattr(module, func_str) + except AttributeError: + arg_parser.error("module %r has no attribute %r" % (mod_str, func_str)) + + app = func(extra_argv) + run_app(app, host=args.hostname, port=args.port) + arg_parser.exit(message="Stopped\n") + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/aiohttp/web_exceptions.py b/aiohttp/web_exceptions.py index adc8cbb..254f073 100644 --- a/aiohttp/web_exceptions.py +++ b/aiohttp/web_exceptions.py @@ -45,6 +45,7 @@ __all__ = ( 'HTTPPreconditionRequired', 'HTTPTooManyRequests', 'HTTPRequestHeaderFieldsTooLarge', + 'HTTPUnavailableForLegalReasons', 'HTTPServerError', 'HTTPInternalServerError', 'HTTPNotImplemented', @@ -286,6 +287,18 @@ class HTTPRequestHeaderFieldsTooLarge(HTTPClientError): status_code = 431 +class HTTPUnavailableForLegalReasons(HTTPClientError): + status_code = 451 + + def __init__(self, link=None, *, headers=None, reason=None, + body=None, text=None, content_type=None): + super().__init__(headers=headers, reason=reason, + body=body, text=text, content_type=content_type) + if link: + self.headers['Link'] = '<%s>; rel="blocked-by"' % link + self.link = link + + ############################################################ # 5xx Server Error ############################################################ diff --git a/aiohttp/web_reqrep.py b/aiohttp/web_reqrep.py index 7f5494a..f3b195f 100644 --- a/aiohttp/web_reqrep.py +++ b/aiohttp/web_reqrep.py @@ -16,12 +16,13 @@ from email.utils import parsedate from types import MappingProxyType from urllib.parse import urlsplit, parse_qsl, unquote +from multidict import (CIMultiDictProxy, + CIMultiDict, + MultiDictProxy, + MultiDict) + from . import hdrs from .helpers import reify -from .multidict import (CIMultiDictProxy, - CIMultiDict, - MultiDictProxy, - MultiDict) from .protocol import Response as ResponseImpl, HttpVersion10, HttpVersion11 from .streams import EOF_MARKER @@ -99,29 +100,20 @@ class Request(dict, HeadersMixin): hdrs.METH_TRACE, hdrs.METH_DELETE} def __init__(self, app, message, payload, transport, reader, writer, *, - _HOST=hdrs.HOST, secure_proxy_ssl_header=None): + secure_proxy_ssl_header=None): self._app = app - self._version = message.version + self._message = message self._transport = transport self._reader = reader self._writer = writer - self._method = message.method - self._host = message.headers.get(_HOST) - self._path_qs = message.path self._post = None self._post_files_cache = None - self._headers = CIMultiDictProxy(message.headers) - if self._version < HttpVersion10: - self._keep_alive = False - else: - self._keep_alive = not message.should_close # matchdict, route_name, handler # or information about traversal lookup self._match_info = None # initialized after route resolving self._payload = payload - self._cookies = None self._read_bytes = None self._has_body = not payload.at_eof() @@ -139,48 +131,48 @@ class Request(dict, HeadersMixin): secure_proxy_ssl_header = self._secure_proxy_ssl_header if secure_proxy_ssl_header is not None: header, value = secure_proxy_ssl_header - if self._headers.get(header) == value: + if self.headers.get(header) == value: return 'https' return 'http' - @property + @reify def method(self): """Read only property for getting HTTP method. The value is upper-cased str like 'GET', 'POST', 'PUT' etc. """ - return self._method + return self._message.method - @property + @reify def version(self): """Read only property for getting HTTP version of request. Returns aiohttp.protocol.HttpVersion instance. """ - return self._version + return self._message.version - @property + @reify def host(self): """Read only property for getting *HOST* header of request. Returns str or None if HTTP request has no HOST header. """ - return self._host + return self._message.headers.get(hdrs.HOST) - @property + @reify def path_qs(self): """The URL including PATH_INFO and the query string. E.g, /app/blog?id=10 """ - return self._path_qs + return self._message.path @reify def _splitted_path(self): - url = '{}://{}{}'.format(self.scheme, self.host, self._path_qs) + url = '{}://{}{}'.format(self.scheme, self.host, self.path_qs) return urlsplit(url) - @property + @reify def raw_path(self): """ The URL including raw *PATH INFO* without the host or scheme. Warning, the path is unquoted and may contains non valid URL characters @@ -224,12 +216,17 @@ class Request(dict, HeadersMixin): raise RuntimeError("POST is not available before post()") return self._post - @property + @reify def headers(self): """A case-insensitive multidict proxy with all headers.""" - return self._headers + return CIMultiDictProxy(self._message.headers) - @property + @reify + def raw_headers(self): + """A sequence of pars for all headers.""" + return tuple(self._message.raw_headers) + + @reify def if_modified_since(self, _IF_MODIFIED_SINCE=hdrs.IF_MODIFIED_SINCE): """The value of If-Modified-Since HTTP header, or None. @@ -243,10 +240,13 @@ class Request(dict, HeadersMixin): tzinfo=datetime.timezone.utc) return None - @property + @reify def keep_alive(self): """Is keepalive enabled by client?""" - return self._keep_alive + if self.version < HttpVersion10: + return False + else: + return not self._message.should_close @property def match_info(self): @@ -263,24 +263,16 @@ class Request(dict, HeadersMixin): """Transport used for request processing.""" return self._transport - @property + @reify def cookies(self): """Return request cookies. A read-only dictionary-like object. """ - if self._cookies is None: - raw = self.headers.get(hdrs.COOKIE, '') - parsed = http.cookies.SimpleCookie(raw) - self._cookies = MappingProxyType( - {key: val.value for key, val in parsed.items()}) - return self._cookies - - @property - def payload(self): - """Return raw payload stream.""" - warnings.warn('use Request.content instead', DeprecationWarning) - return self._payload + raw = self.headers.get(hdrs.COOKIE, '') + parsed = http.cookies.SimpleCookie(raw) + return MappingProxyType( + {key: val.value for key, val in parsed.items()}) @property def content(self): @@ -326,10 +318,15 @@ class Request(dict, HeadersMixin): return bytes_body.decode(encoding) @asyncio.coroutine - def json(self, *, loader=json.loads): + def json(self, *, loads=json.loads, loader=None): """Return BODY as JSON.""" + if loader is not None: + warnings.warn( + "Using loader argument is deprecated, use loads instead", + DeprecationWarning) + loads = loader body = yield from self.text() - return loader(body) + return loads(body) @asyncio.coroutine def post(self): @@ -396,8 +393,10 @@ class Request(dict, HeadersMixin): raise NotImplementedError def __repr__(self): + ascii_encodable_path = self.path.encode('ascii', 'backslashreplace') \ + .decode('ascii') return "<{} {} {} >".format(self.__class__.__name__, - self.method, self.path) + self.method, ascii_encodable_path) ############################################################ @@ -480,6 +479,10 @@ class StreamResponse(HeadersMixin): # Backwards compatibility for when force was a bool <0.17. if type(force) == bool: force = ContentCoding.deflate if force else ContentCoding.identity + elif force is not None: + assert isinstance(force, ContentCoding), ("force should one of " + "None, bool or " + "ContentEncoding") self._compression = True self._compression_force = force @@ -654,21 +657,21 @@ class StreamResponse(HeadersMixin): else: return None - def _start_compression(self, request): - def _start(coding): - if coding != ContentCoding.identity: - self.headers[hdrs.CONTENT_ENCODING] = coding.value - self._resp_impl.add_compression_filter(coding.value) - self.content_length = None + def _do_start_compression(self, coding): + if coding != ContentCoding.identity: + self.headers[hdrs.CONTENT_ENCODING] = coding.value + self._resp_impl.add_compression_filter(coding.value) + self.content_length = None + def _start_compression(self, request): if self._compression_force: - _start(self._compression_force) + self._do_start_compression(self._compression_force) else: accept_encoding = request.headers.get( hdrs.ACCEPT_ENCODING, '').lower() for coding in ContentCoding: if coding.value in accept_encoding: - _start(coding) + self._do_start_compression(coding) return def start(self, request): @@ -845,11 +848,15 @@ class Response(StreamResponse): self.body = text.encode(self.charset) + def should_send_body(self): + return (self._req.method != hdrs.METH_HEAD and + self._status not in [204, 304]) + @asyncio.coroutine def write_eof(self): try: body = self._body - if body is not None: + if body is not None and self.should_send_body(): self.write(body) finally: self.set_tcp_nodelay(True) diff --git a/aiohttp/web_urldispatcher.py b/aiohttp/web_urldispatcher.py index 3bfcaaa..600b194 100644 --- a/aiohttp/web_urldispatcher.py +++ b/aiohttp/web_urldispatcher.py @@ -3,68 +3,110 @@ import asyncio import keyword import collections -import mimetypes import re import os import sys import inspect +import warnings from collections.abc import Sized, Iterable, Container +from pathlib import Path from urllib.parse import urlencode, unquote from types import MappingProxyType +from multidict import upstr + from . import hdrs from .abc import AbstractRouter, AbstractMatchInfo, AbstractView +from .file_sender import FileSender from .protocol import HttpVersion11 -from .web_exceptions import HTTPMethodNotAllowed, HTTPNotFound, HTTPNotModified +from .web_exceptions import (HTTPMethodNotAllowed, HTTPNotFound, + HTTPExpectationFailed) from .web_reqrep import StreamResponse -from .multidict import upstr __all__ = ('UrlDispatcher', 'UrlMappingMatchInfo', + 'AbstractResource', 'Resource', 'PlainResource', 'DynamicResource', + 'ResourceAdapter', + 'AbstractRoute', 'ResourceRoute', 'Route', 'PlainRoute', 'DynamicRoute', 'StaticRoute', 'View') PY_35 = sys.version_info >= (3, 5) -class UrlMappingMatchInfo(dict, AbstractMatchInfo): +class AbstractResource(Sized, Iterable): - def __init__(self, match_dict, route): - super().__init__(match_dict) - self._route = route + def __init__(self, *, name=None): + self._name = name @property - def handler(self): - return self._route.handler + def name(self): + return self._name - @property - def route(self): - return self._route + @abc.abstractmethod # pragma: no branch + def url(self, **kwargs): + """Construct url for resource with additional params.""" - def __repr__(self): - return "<MatchInfo {}: {}>".format(super().__repr__(), self._route) + @asyncio.coroutine + @abc.abstractmethod # pragma: no branch + def resolve(self, method, path): + """Resolve resource + Return (UrlMappingMatchInfo, allowed_methods) pair.""" -@asyncio.coroutine -def _defaultExpectHandler(request): - """Default handler for Except: 100-continue""" - if request.version == HttpVersion11: - request.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n") + @abc.abstractmethod + def get_info(self): + """Return a dict with additional info useful for introspection""" + + @staticmethod + def _append_query(url, query): + if query is not None: + return url + "?" + urlencode(query) + else: + return url -class Route(metaclass=abc.ABCMeta): +class AbstractRoute(abc.ABC): + METHODS = hdrs.METH_ALL | {hdrs.METH_ANY} + + def __init__(self, method, handler, *, + expect_handler=None, + resource=None): - def __init__(self, method, handler, name, *, expect_handler=None): if expect_handler is None: expect_handler = _defaultExpectHandler + assert asyncio.iscoroutinefunction(expect_handler), \ 'Coroutine is expected, got {!r}'.format(expect_handler) + method = upstr(method) + if method not in self.METHODS: + raise ValueError("{} is not allowed HTTP method".format(method)) + + assert callable(handler), handler + if asyncio.iscoroutinefunction(handler): + pass + elif inspect.isgeneratorfunction(handler): + warnings.warn("Bare generators are deprecated, " + "use @coroutine wrapper", DeprecationWarning) + elif (isinstance(handler, type) and + issubclass(handler, AbstractView)): + pass + else: + @asyncio.coroutine + def handler_wrapper(*args, **kwargs): + result = old_handler(*args, **kwargs) + if asyncio.iscoroutine(result): + result = yield from result + return result + old_handler = handler + handler = handler_wrapper + self._method = method self._handler = handler - self._name = name self._expect_handler = expect_handler + self._resource = resource @property def method(self): @@ -75,13 +117,17 @@ class Route(metaclass=abc.ABCMeta): return self._handler @property + @abc.abstractmethod def name(self): - return self._name + """Optional route's name, always equals to resource's name.""" - @abc.abstractmethod # pragma: no branch - def match(self, path): - """Return dict with info for given path or - None if route cannot process path.""" + @property + def resource(self): + return self._resource + + @abc.abstractmethod + def get_info(self): + """Return a dict with additional info useful for introspection""" @abc.abstractmethod # pragma: no branch def url(self, **kwargs): @@ -91,12 +137,247 @@ class Route(metaclass=abc.ABCMeta): def handle_expect_header(self, request): return (yield from self._expect_handler(request)) - @staticmethod - def _append_query(url, query): - if query is not None: - return url + "?" + urlencode(query) + +class UrlMappingMatchInfo(dict, AbstractMatchInfo): + + def __init__(self, match_dict, route): + super().__init__(match_dict) + self._route = route + + @property + def handler(self): + return self._route.handler + + @property + def route(self): + return self._route + + @property + def expect_handler(self): + return self._route.handle_expect_header + + @property + def http_exception(self): + return None + + def get_info(self): + return self._route.get_info() + + def __repr__(self): + return "<MatchInfo {}: {}>".format(super().__repr__(), self._route) + + +class MatchInfoError(UrlMappingMatchInfo): + + def __init__(self, http_exception): + self._exception = http_exception + super().__init__({}, SystemRoute(self._exception)) + + @property + def http_exception(self): + return self._exception + + def __repr__(self): + return "<MatchInfoError {}: {}>".format(self._exception.status, + self._exception.reason) + + +@asyncio.coroutine +def _defaultExpectHandler(request): + """Default handler for Expect header. + + Just send "100 Continue" to client. + raise HTTPExpectationFailed if value of header is not "100-continue" + """ + expect = request.headers.get(hdrs.EXPECT) + if request.version == HttpVersion11: + if expect.lower() == "100-continue": + request.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n") else: - return url + raise HTTPExpectationFailed(text="Unknown Expect: %s" % expect) + + +class ResourceAdapter(AbstractResource): + + def __init__(self, route): + assert isinstance(route, Route), \ + 'Instance of Route class is required, got {!r}'.format(route) + super().__init__(name=route.name) + self._route = route + route._resource = self + + def url(self, **kwargs): + return self._route.url(**kwargs) + + @asyncio.coroutine + def resolve(self, method, path): + route_method = self._route.method + allowed_methods = set() + match_dict = self._route.match(path) + if match_dict is not None: + allowed_methods.add(route_method) + if route_method == hdrs.METH_ANY or route_method == method: + return (UrlMappingMatchInfo(match_dict, self._route), + allowed_methods) + return None, allowed_methods + + def get_info(self): + return self._route.get_info() + + def __len__(self): + return 1 + + def __iter__(self): + yield self._route + + +class Resource(AbstractResource): + + def __init__(self, *, name=None): + super().__init__(name=name) + self._routes = [] + + def add_route(self, method, handler, *, + expect_handler=None): + + for route in self._routes: + if route.method == method or route.method == hdrs.METH_ANY: + raise RuntimeError("Added route will never be executed, " + "method {route.method} is " + "already registered".format(route=route)) + + route = ResourceRoute(method, handler, self, + expect_handler=expect_handler) + self.register_route(route) + return route + + def register_route(self, route): + assert isinstance(route, ResourceRoute), \ + 'Instance of Route class is required, got {!r}'.format(route) + self._routes.append(route) + + @asyncio.coroutine + def resolve(self, method, path): + allowed_methods = set() + + match_dict = self._match(path) + if match_dict is None: + return None, allowed_methods + + for route in self._routes: + route_method = route.method + allowed_methods.add(route_method) + + if route_method == method or route_method == hdrs.METH_ANY: + return UrlMappingMatchInfo(match_dict, route), allowed_methods + else: + return None, allowed_methods + + def __len__(self): + return len(self._routes) + + def __iter__(self): + return iter(self._routes) + + +class PlainResource(Resource): + + def __init__(self, path, *, name=None): + super().__init__(name=name) + self._path = path + + def _match(self, path): + # string comparison is about 10 times faster than regexp matching + if self._path == path: + return {} + else: + return None + + def get_info(self): + return {'path': self._path} + + def url(self, *, query=None): + return self._append_query(self._path, query) + + def __repr__(self): + name = "'" + self.name + "' " if self.name is not None else "" + return "<PlainResource {name} {path}".format(name=name, + path=self._path) + + +class DynamicResource(Resource): + + def __init__(self, pattern, formatter, *, name=None): + super().__init__(name=name) + self._pattern = pattern + self._formatter = formatter + + def _match(self, path): + match = self._pattern.match(path) + if match is None: + return None + else: + return {key: unquote(value) for key, value in + match.groupdict().items()} + + def get_info(self): + return {'formatter': self._formatter, + 'pattern': self._pattern} + + def url(self, *, parts, query=None): + url = self._formatter.format_map(parts) + return self._append_query(url, query) + + def __repr__(self): + name = "'" + self.name + "' " if self.name is not None else "" + return ("<DynamicResource {name} {formatter}" + .format(name=name, formatter=self._formatter)) + + +class ResourceRoute(AbstractRoute): + """A route with resource""" + + def __init__(self, method, handler, resource, *, + expect_handler=None): + super().__init__(method, handler, expect_handler=expect_handler, + resource=resource) + + def __repr__(self): + return "<ResourceRoute [{method}] {resource} -> {handler!r}".format( + method=self.method, resource=self._resource, + handler=self.handler) + + @property + def name(self): + return self._resource.name + + def url(self, **kwargs): + """Construct url for route with additional params.""" + return self._resource.url(**kwargs) + + def get_info(self): + return self._resource.get_info() + + _append_query = staticmethod(Resource._append_query) + + +class Route(AbstractRoute): + """Old fashion route""" + + def __init__(self, method, handler, name, *, expect_handler=None): + super().__init__(method, handler, expect_handler=expect_handler) + self._name = name + + @property + def name(self): + return self._name + + @abc.abstractmethod + def match(self, path): + """Return dict with info for given path or + None if route cannot process path.""" + + _append_query = staticmethod(Resource._append_query) class PlainRoute(Route): @@ -115,6 +396,9 @@ class PlainRoute(Route): def url(self, *, query=None): return self._append_query(self._path, query) + def get_info(self): + return {'path': self._path} + def __repr__(self): name = "'" + self.name + "' " if self.name is not None else "" return "<PlainRoute {name}[{method}] {path} -> {handler!r}".format( @@ -141,6 +425,10 @@ class DynamicRoute(Route): url = self._formatter.format_map(parts) return self._append_query(url, query) + def get_info(self): + return {'formatter': self._formatter, + 'pattern': self._pattern} + def __repr__(self): name = "'" + self.name + "' " if self.name is not None else "" return ("<DynamicRoute {name}[{method}] {formatter} -> {handler!r}" @@ -159,16 +447,19 @@ class StaticRoute(Route): 'GET', self.handle, name, expect_handler=expect_handler) self._prefix = prefix self._prefix_len = len(self._prefix) - self._directory = os.path.abspath(directory) + os.sep - self._chunk_size = chunk_size - self._response_factory = response_factory - - if not os.path.isdir(self._directory): + try: + directory = Path(directory) + if str(directory).startswith('~'): + directory = Path(os.path.expanduser(str(directory))) + directory = directory.resolve() + if not directory.is_dir(): + raise ValueError('Not a directory') + except (FileNotFoundError, ValueError) as error: raise ValueError( - "No directory exists at '{}'".format(self._directory)) - - if bool(os.environ.get("AIOHTTP_NOSENDFILE")): - self._sendfile = self._sendfile_fallback + "No directory exists at '{}'".format(directory)) from error + self._directory = directory + self._file_sender = FileSender(resp_factory=response_factory, + chunk_size=chunk_size) def match(self, path): if not path.startswith(self._prefix): @@ -176,132 +467,37 @@ class StaticRoute(Route): return {'filename': path[self._prefix_len:]} def url(self, *, filename, query=None): + if isinstance(filename, Path): + filename = str(filename) while filename.startswith('/'): filename = filename[1:] url = self._prefix + filename return self._append_query(url, query) - def _sendfile_cb(self, fut, out_fd, in_fd, offset, count, loop, - registered): - if registered: - loop.remove_writer(out_fd) - try: - n = os.sendfile(out_fd, in_fd, offset, count) - if n == 0: # EOF reached - n = count - except (BlockingIOError, InterruptedError): - n = 0 - except Exception as exc: - fut.set_exception(exc) - return - - if n < count: - loop.add_writer(out_fd, self._sendfile_cb, fut, out_fd, in_fd, - offset + n, count - n, loop, True) - else: - fut.set_result(None) - - @asyncio.coroutine - def _sendfile_system(self, req, resp, fobj, count): - """ - Write `count` bytes of `fobj` to `resp` starting from `offset` using - the ``sendfile`` system call. - - `req` should be a :obj:`aiohttp.web.Request` instance. - - `resp` should be a :obj:`aiohttp.web.StreamResponse` instance. - - `fobj` should be an open file object. - - `offset` should be an integer >= 0. - - `count` should be an integer > 0. - """ - transport = req.transport - - if transport.get_extra_info("sslcontext"): - yield from self._sendfile_fallback(req, resp, fobj, count) - return - - yield from resp.drain() - - loop = req.app.loop - out_fd = transport.get_extra_info("socket").fileno() - in_fd = fobj.fileno() - fut = asyncio.Future(loop=loop) - - self._sendfile_cb(fut, out_fd, in_fd, 0, count, loop, False) - - yield from fut - - @asyncio.coroutine - def _sendfile_fallback(self, req, resp, fobj, count): - """ - Mimic the :meth:`_sendfile_system` method, but without using the - ``sendfile`` system call. This should be used on systems that don't - support the ``sendfile`` system call. - - To avoid blocking the event loop & to keep memory usage low, `fobj` is - transferred in chunks controlled by the `chunk_size` argument to - :class:`StaticRoute`. - """ - chunk_size = self._chunk_size - - chunk = fobj.read(chunk_size) - while chunk and count > chunk_size: - resp.write(chunk) - yield from resp.drain() - count = count - chunk_size - chunk = fobj.read(chunk_size) - - if chunk: - resp.write(chunk[:count]) - yield from resp.drain() - - if hasattr(os, "sendfile"): # pragma: no cover - _sendfile = _sendfile_system - else: # pragma: no cover - _sendfile = _sendfile_fallback + def get_info(self): + return {'directory': self._directory, + 'prefix': self._prefix} @asyncio.coroutine def handle(self, request): filename = request.match_info['filename'] - filepath = os.path.abspath(os.path.join(self._directory, filename)) - if not filepath.startswith(self._directory): - raise HTTPNotFound() - if not os.path.exists(filepath) or not os.path.isfile(filepath): - raise HTTPNotFound() - - st = os.stat(filepath) - - modsince = request.if_modified_since - if modsince is not None and st.st_mtime <= modsince.timestamp(): - raise HTTPNotModified() - - ct, encoding = mimetypes.guess_type(filepath) - if not ct: - ct = 'application/octet-stream' - - resp = self._response_factory() - resp.content_type = ct - if encoding: - resp.headers[hdrs.CONTENT_ENCODING] = encoding - resp.last_modified = st.st_mtime - - file_size = st.st_size - - resp.content_length = file_size - resp.set_tcp_cork(True) try: - yield from resp.prepare(request) - - with open(filepath, 'rb') as f: - yield from self._sendfile(request, resp, f, file_size) - - finally: - resp.set_tcp_nodelay(True) + filepath = self._directory.joinpath(filename).resolve() + filepath.relative_to(self._directory) + except (ValueError, FileNotFoundError) as error: + # relatively safe + raise HTTPNotFound() from error + except Exception as error: + # perm error or other kind! + request.app.logger.exception(error) + raise HTTPNotFound() from error + + # Make sure that filepath is a file + if not filepath.is_file(): + raise HTTPNotFound() - return resp + ret = yield from self._file_sender.send(request, filepath) + return ret def __repr__(self): name = "'" + self.name + "' " if self.name is not None else "" @@ -312,10 +508,9 @@ class StaticRoute(Route): class SystemRoute(Route): - def __init__(self, status, reason): - super().__init__(hdrs.METH_ANY, None, None) - self._status = status - self._reason = reason + def __init__(self, http_exception): + super().__init__(hdrs.METH_ANY, self._handler, None) + self._http_exception = http_exception def url(self, **kwargs): raise RuntimeError(".url() is not allowed for SystemRoute") @@ -323,59 +518,23 @@ class SystemRoute(Route): def match(self, path): return None - @property - def status(self): - return self._status - - @property - def reason(self): - return self._reason - - def __repr__(self): - return "<SystemRoute {status}: {reason}>".format(status=self._status, - reason=self._reason) - - -class _NotFoundMatchInfo(UrlMappingMatchInfo): - - route = SystemRoute(404, 'Not Found') - - def __init__(self): - super().__init__({}, None) - - @property - def handler(self): - return self._not_found + def get_info(self): + return {'http_exception': self._http_exception} @asyncio.coroutine - def _not_found(self, request): - raise HTTPNotFound() - - def __repr__(self): - return "<MatchInfo: not found>" - - -class _MethodNotAllowedMatchInfo(UrlMappingMatchInfo): - - route = SystemRoute(405, 'Method Not Allowed') - - def __init__(self, method, allowed_methods): - super().__init__({}, None) - self._method = method - self._allowed_methods = allowed_methods + def _handler(self, request): + raise self._http_exception @property - def handler(self): - return self._not_allowed + def status(self): + return self._http_exception.status - @asyncio.coroutine - def _not_allowed(self, request): - raise HTTPMethodNotAllowed(self._method, self._allowed_methods) + @property + def reason(self): + return self._http_exception.reason def __repr__(self): - return ("<MatchInfo: method {} is not allowed (allowed methods: {}>" - .format(self._method, - ', '.join(sorted(self._allowed_methods)))) + return "<SystemRoute {self.status}: {self.reason}>".format(self=self) class View(AbstractView): @@ -395,25 +554,42 @@ class View(AbstractView): return (yield from self.__iter__()) def _raise_allowed_methods(self): - allowed_methods = {m for m in hdrs.METH_ALL if hasattr(self, m)} + allowed_methods = { + m for m in hdrs.METH_ALL if hasattr(self, m.lower())} raise HTTPMethodNotAllowed(self.request.method, allowed_methods) -class RoutesView(Sized, Iterable, Container): +class ResourcesView(Sized, Iterable, Container): + + def __init__(self, resources): + self._resources = resources + + def __len__(self): + return len(self._resources) + + def __iter__(self): + yield from self._resources - __slots__ = '_urls' + def __contains__(self, resource): + return resource in self._resources - def __init__(self, urls): - self._urls = urls + +class RoutesView(Sized, Iterable, Container): + + def __init__(self, resources): + self._routes = [] + for resource in resources: + for route in resource: + self._routes.append(route) def __len__(self): - return len(self._urls) + return len(self._routes) def __iter__(self): - yield from self._urls + yield from self._routes def __contains__(self, route): - return route in self._urls + return route in self._routes class UrlDispatcher(AbstractRouter, collections.abc.Mapping): @@ -425,14 +601,10 @@ class UrlDispatcher(AbstractRouter, collections.abc.Mapping): ROUTE_RE = re.compile(r'(\{[_a-zA-Z][^{}]*(?:\{[^{}]*\}[^{}]*)*\})') NAME_SPLIT_RE = re.compile('[.:-]') - METHODS = {hdrs.METH_ANY, hdrs.METH_POST, - hdrs.METH_GET, hdrs.METH_PUT, hdrs.METH_DELETE, - hdrs.METH_PATCH, hdrs.METH_HEAD, hdrs.METH_OPTIONS} - def __init__(self): super().__init__() - self._urls = [] - self._routes = {} + self._resources = [] + self._named_resources = {} @asyncio.coroutine def resolve(self, request): @@ -440,47 +612,56 @@ class UrlDispatcher(AbstractRouter, collections.abc.Mapping): method = request.method allowed_methods = set() - for route in self._urls: - match_dict = route.match(path) - if match_dict is None: - continue - - route_method = route.method - if route_method == method or route_method == hdrs.METH_ANY: - # Unquote separate matching parts - match_dict = {key: unquote(value) for key, value in - match_dict.items()} - return UrlMappingMatchInfo(match_dict, route) - - allowed_methods.add(route_method) + for resource in self._resources: + match_dict, allowed = yield from resource.resolve(method, path) + if match_dict is not None: + return match_dict + else: + allowed_methods |= allowed else: if allowed_methods: - return _MethodNotAllowedMatchInfo(method, allowed_methods) + return MatchInfoError(HTTPMethodNotAllowed(method, + allowed_methods)) else: - return _NotFoundMatchInfo() + return MatchInfoError(HTTPNotFound()) def __iter__(self): - return iter(self._routes) + return iter(self._named_resources) def __len__(self): - return len(self._routes) + return len(self._named_resources) def __contains__(self, name): - return name in self._routes + return name in self._named_resources def __getitem__(self, name): - return self._routes[name] + return self._named_resources[name] + + def resources(self): + return ResourcesView(self._resources) def routes(self): - return RoutesView(self._urls) + return RoutesView(self._resources) + + def named_resources(self): + return MappingProxyType(self._named_resources) def named_routes(self): - return MappingProxyType(self._routes) + # NB: it's ambiguous but it's really resources. + warnings.warn("Use .named_resources instead", DeprecationWarning) + return self.named_resources() def register_route(self, route): - assert isinstance(route, Route), 'Instance of Route class is required.' + warnings.warn("Use resource-based interface", DeprecationWarning) + resource = ResourceAdapter(route) + self._reg_resource(resource) + + def _reg_resource(self, resource): + assert isinstance(resource, AbstractResource), \ + 'Instance of AbstractResource class is required, got {!r}'.format( + resource) - name = route.name + name = resource.name if name is not None: parts = self.NAME_SPLIT_RE.split(name) @@ -490,38 +671,20 @@ class UrlDispatcher(AbstractRouter, collections.abc.Mapping): 'the name should be a sequence of ' 'python identifiers separated ' 'by dash, dot or column'.format(name)) - if name in self._routes: + if name in self._named_resources: raise ValueError('Duplicate {!r}, ' 'already handled by {!r}' - .format(name, self._routes[name])) - self._routes[name] = route - self._urls.append(route) - - def add_route(self, method, path, handler, - *, name=None, expect_handler=None): + .format(name, self._named_resources[name])) + self._named_resources[name] = resource + self._resources.append(resource) + def add_resource(self, path, *, name=None): if not path.startswith('/'): raise ValueError("path should be started with /") - - assert callable(handler), handler - if asyncio.iscoroutinefunction(handler): - pass - elif inspect.isgeneratorfunction(handler): - pass - elif isinstance(handler, type) and issubclass(handler, AbstractView): - pass - else: - handler = asyncio.coroutine(handler) - - method = upstr(method) - if method not in self.METHODS: - raise ValueError("{} is not allowed HTTP method".format(method)) - if not ('{' in path or '}' in path or self.ROUTE_RE.search(path)): - route = PlainRoute( - method, handler, name, path, expect_handler=expect_handler) - self.register_route(route) - return route + resource = PlainResource(path, name=name) + self._reg_resource(resource) + return resource pattern = '' formatter = '' @@ -549,11 +712,15 @@ class UrlDispatcher(AbstractRouter, collections.abc.Mapping): except re.error as exc: raise ValueError( "Bad pattern '{}': {}".format(pattern, exc)) from None - route = DynamicRoute( - method, handler, name, compiled, - formatter, expect_handler=expect_handler) - self.register_route(route) - return route + resource = DynamicResource(compiled, formatter, name=name) + self._reg_resource(resource) + return resource + + def add_route(self, method, path, handler, + *, name=None, expect_handler=None): + resource = self.add_resource(path, name=name) + return resource.add_route(method, handler, + expect_handler=expect_handler) def add_static(self, prefix, path, *, name=None, expect_handler=None, chunk_size=256*1024, response_factory=StreamResponse): diff --git a/aiohttp/web_ws.py b/aiohttp/web_ws.py index d28907a..3d46ed5 100644 --- a/aiohttp/web_ws.py +++ b/aiohttp/web_ws.py @@ -1,5 +1,6 @@ import sys import asyncio +import json import warnings from . import hdrs @@ -285,6 +286,15 @@ class WebSocketResponse(StreamResponse): msg.data)) return msg.data + @asyncio.coroutine + def receive_json(self, *, loads=json.loads): + msg = yield from self.receive() + if msg.tp != MsgType.text: + raise TypeError( + "Received message {}:{!r} is not str".format(msg.tp, msg.data) + ) + return msg.json(loads=loads) + def write(self, data): raise RuntimeError("Cannot call .write() for websocket") diff --git a/aiohttp/websocket.py b/aiohttp/websocket.py index f508b55..395456f 100644 --- a/aiohttp/websocket.py +++ b/aiohttp/websocket.py @@ -4,6 +4,7 @@ import base64 import binascii import collections import hashlib +import json import os import random import sys @@ -33,6 +34,8 @@ CLOSE_POLICY_VIOLATION = 1008 CLOSE_MESSAGE_TOO_BIG = 1009 CLOSE_MANDATORY_EXTENSION = 1010 CLOSE_INTERNAL_ERROR = 1011 +CLOSE_SERVICE_RESTART = 1012 +CLOSE_TRY_AGAIN_LATER = 1013 ALLOWED_CLOSE_CODES = ( CLOSE_OK, @@ -44,6 +47,8 @@ ALLOWED_CLOSE_CODES = ( CLOSE_MESSAGE_TOO_BIG, CLOSE_MANDATORY_EXTENSION, CLOSE_INTERNAL_ERROR, + CLOSE_SERVICE_RESTART, + CLOSE_TRY_AGAIN_LATER, ) WS_KEY = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11' @@ -53,7 +58,6 @@ WS_HDRS = (hdrs.UPGRADE, hdrs.SEC_WEBSOCKET_KEY, hdrs.SEC_WEBSOCKET_PROTOCOL) -Message = collections.namedtuple('Message', ['tp', 'data', 'extra']) UNPACK_LEN2 = Struct('!H').unpack_from UNPACK_LEN3 = Struct('!Q').unpack_from @@ -65,6 +69,18 @@ PACK_CLOSE_CODE = Struct('!H').pack MSG_SIZE = 2 ** 14 +_MessageBase = collections.namedtuple('Message', ['tp', 'data', 'extra']) + + +class Message(_MessageBase): + def json(self, *, loads=json.loads): + """Return parsed JSON data. + + .. versionadded:: 0.22 + """ + return loads(self.data) + + class WebSocketError(Exception): """WebSocket protocol parser error.""" @@ -341,7 +357,7 @@ class WebSocketWriter: def do_handshake(method, headers, transport, protocols=()): """Prepare WebSocket handshake. - It return http response code, response headers, websocket parser, + It return HTTP response code, response headers, websocket parser, websocket writer. It does not perform any IO. `protocols` is a sequence of known protocols. On successful handshake, @@ -378,7 +394,7 @@ def do_handshake(method, headers, transport, protocols=()): # No overlap found: Return no protocol as per spec ws_logger.warning( 'Client protocols %r don’t overlap server-known ones %r', - protocols, req_protocols) + req_protocols, protocols) # check supported version version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, '') diff --git a/aiohttp/worker.py b/aiohttp/worker.py index 1086dc2..e2c707d 100644 --- a/aiohttp/worker.py +++ b/aiohttp/worker.py @@ -9,7 +9,7 @@ import gunicorn.workers.base as base from aiohttp.helpers import ensure_future -__all__ = ('GunicornWebWorker',) +__all__ = ('GunicornWebWorker', 'GunicornUVLoopWebWorker') class GunicornWebWorker(base.Worker): @@ -39,15 +39,13 @@ class GunicornWebWorker(base.Worker): sys.exit(self.exit_code) - def make_handler(self, app, host, port): + def make_handler(self, app): if hasattr(self.cfg, 'debug'): is_debug = self.cfg.debug else: is_debug = self.log.loglevel == logging.DEBUG return app.make_handler( - host=host, - port=port, logger=self.log, debug=is_debug, timeout=self.cfg.timeout, @@ -67,6 +65,9 @@ class GunicornWebWorker(base.Worker): self.pid, len(handler.connections)) server.close() + # send on_shutdown event + yield from self.wsgi.shutdown() + # stop alive connections tasks = [ handler.finish_connections( @@ -80,7 +81,7 @@ class GunicornWebWorker(base.Worker): @asyncio.coroutine def _run(self): for sock in self.sockets: - handler = self.make_handler(self.wsgi, *sock.cfg_addr) + handler = self.make_handler(self.wsgi) srv = yield from self.loop.create_server(handler, sock=sock.sock) self.servers[srv] = handler @@ -108,14 +109,26 @@ class GunicornWebWorker(base.Worker): yield from self.close() - def init_signal(self): - # init new signaling - self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit) - self.loop.add_signal_handler(signal.SIGTERM, self.handle_exit) - self.loop.add_signal_handler(signal.SIGINT, self.handle_quit) - self.loop.add_signal_handler(signal.SIGWINCH, self.handle_winch) - self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1) - self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort) + def init_signals(self): + # Set up signals through the event loop API. + + self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit, + signal.SIGQUIT, None) + + self.loop.add_signal_handler(signal.SIGTERM, self.handle_exit, + signal.SIGTERM, None) + + self.loop.add_signal_handler(signal.SIGINT, self.handle_quit, + signal.SIGINT, None) + + self.loop.add_signal_handler(signal.SIGWINCH, self.handle_winch, + signal.SIGWINCH, None) + + self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1, + signal.SIGUSR1, None) + + self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort, + signal.SIGABRT, None) # Don't let SIGTERM and SIGUSR1 disturb active requests # by interrupting system calls @@ -128,3 +141,20 @@ class GunicornWebWorker(base.Worker): def handle_abort(self, sig, frame): self.alive = False self.exit_code = 1 + + +class GunicornUVLoopWebWorker(GunicornWebWorker): + + def init_process(self): + import uvloop + + # Close any existing event loop before setting a + # new policy. + asyncio.get_event_loop().close() + + # Setup uvloop policy, so that every + # asyncio.get_event_loop() will create an instance + # of uvloop event loop. + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + + super().init_process() diff --git a/debian/.git-dpm b/debian/.git-dpm index 74f7871..6933e41 100644 --- a/debian/.git-dpm +++ b/debian/.git-dpm @@ -1,11 +1,11 @@ # see git-dpm(1) from git-dpm package -f3d021a7a071ff6577d692043f9eab18f1a9eb1c -f3d021a7a071ff6577d692043f9eab18f1a9eb1c -f3d021a7a071ff6577d692043f9eab18f1a9eb1c -f3d021a7a071ff6577d692043f9eab18f1a9eb1c -python-aiohttp_0.17.4.orig.tar.gz -22115d5390dfb4fe2ff719ae0ac4b036748f8b9e -475034 +ac7dc8763eab3a6fb487bf163136605530a73bb9 +ac7dc8763eab3a6fb487bf163136605530a73bb9 +ac7dc8763eab3a6fb487bf163136605530a73bb9 +ac7dc8763eab3a6fb487bf163136605530a73bb9 +python-aiohttp_0.22.4.orig.tar.gz +baecb084c0d08ff5f9ddad544bf674d7a2e7f65b +475257 debianTag="debian/%e%v" patchedTag="patched/%e%v" upstreamTag="upstream/%e%u" diff --git a/debian/changelog b/debian/changelog index bfe52cc..15ee4c8 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,16 @@ +python-aiohttp (0.22.4-1) unstable; urgency=medium + + [ Ondřej Nový ] + * Fixed VCS URL (https) + + [ Piotr Ożarowski ] + * New upstream release + - Add dependency on python3-multidict + * Backport changes in test/test_connector.py from upstream master branch + * Standards-Version bumped to 3.9.8 (no changes needed) + + -- Piotr Ożarowski <piotr@debian.org> Thu, 28 Jul 2016 23:32:19 +0200 + python-aiohttp (0.20.2-1) unstable; urgency=medium * New upstream release. diff --git a/debian/control b/debian/control index cf795a5..f75a5a5 100644 --- a/debian/control +++ b/debian/control @@ -11,14 +11,15 @@ Build-Depends: debhelper (>= 9), python3-all-dbg (>= 3.4~), python3-setuptools, python3-sphinx, + python3-multidict, cython3, # for tests: python3-pytest, python3-chardet, python3-gunicorn -Standards-Version: 3.9.6 +Standards-Version: 3.9.8 Homepage: https://aiohttp.readthedocs.org -Vcs-Git: git://anonscm.debian.org/python-modules/packages/python-aiohttp.git +Vcs-Git: https://anonscm.debian.org/git/python-modules/packages/python-aiohttp.git Vcs-Browser: https://anonscm.debian.org/cgit/python-modules/packages/python-aiohttp.git X-Python3-Version: >= 3.4 diff --git a/debian/patches/series b/debian/patches/series new file mode 100644 index 0000000..c1f788c --- /dev/null +++ b/debian/patches/series @@ -0,0 +1 @@ +test_connector.patch diff --git a/debian/patches/test_connector.patch b/debian/patches/test_connector.patch new file mode 100644 index 0000000..d1db412 --- /dev/null +++ b/debian/patches/test_connector.patch @@ -0,0 +1,202 @@ +diff --git a/tests/test_connector.py b/tests/test_connector.py +index c8cffea..fddd387 100644 +--- a/tests/test_connector.py ++++ b/tests/test_connector.py +@@ -14,8 +14,9 @@ import aiohttp + from aiohttp import web + from aiohttp import client + from aiohttp import helpers +-from aiohttp.client import ClientResponse ++from aiohttp.client import ClientResponse, ClientRequest + from aiohttp.connector import Connection ++from aiohttp.test_utils import unused_port + + + class TestBaseConnector(unittest.TestCase): +@@ -257,11 +258,9 @@ class TestBaseConnector(unittest.TestCase): + tr, proto = unittest.mock.Mock(), unittest.mock.Mock() + proto.is_connected.return_value = True + +- class Req: +- host = 'host' +- port = 80 +- ssl = False +- response = unittest.mock.Mock() ++ req = ClientRequest('GET', 'http://host:80', ++ loop=self.loop, ++ response_class=unittest.mock.Mock()) + + conn = aiohttp.BaseConnector(loop=self.loop) + key = ('host', 80, False) +@@ -270,7 +269,7 @@ class TestBaseConnector(unittest.TestCase): + conn._create_connection.return_value = helpers.create_future(self.loop) + conn._create_connection.return_value.set_result((tr, proto)) + +- connection = self.loop.run_until_complete(conn.connect(Req())) ++ connection = self.loop.run_until_complete(conn.connect(req)) + self.assertFalse(conn._create_connection.called) + self.assertEqual(connection._transport, tr) + self.assertEqual(connection._protocol, proto) +@@ -483,11 +482,9 @@ class TestBaseConnector(unittest.TestCase): + tr, proto = unittest.mock.Mock(), unittest.mock.Mock() + proto.is_connected.return_value = True + +- class Req: +- host = 'host' +- port = 80 +- ssl = False +- response = unittest.mock.Mock() ++ req = ClientRequest('GET', 'http://host:80', ++ loop=self.loop, ++ response_class=unittest.mock.Mock()) + + conn = aiohttp.BaseConnector(loop=self.loop, limit=1) + key = ('host', 80, False) +@@ -497,7 +494,7 @@ class TestBaseConnector(unittest.TestCase): + self.loop) + conn._create_connection.return_value.set_result((tr, proto)) + +- connection1 = yield from conn.connect(Req()) ++ connection1 = yield from conn.connect(req) + self.assertEqual(connection1._transport, tr) + + self.assertEqual(1, len(conn._acquired[key])) +@@ -507,7 +504,7 @@ class TestBaseConnector(unittest.TestCase): + @asyncio.coroutine + def f(): + nonlocal acquired +- connection2 = yield from conn.connect(Req()) ++ connection2 = yield from conn.connect(req) + acquired = True + self.assertEqual(1, len(conn._acquired[key])) + connection2.release() +@@ -531,11 +528,9 @@ class TestBaseConnector(unittest.TestCase): + tr, proto = unittest.mock.Mock(), unittest.mock.Mock() + proto.is_connected.return_value = True + +- class Req: +- host = 'host' +- port = 80 +- ssl = False +- response = unittest.mock.Mock() ++ req = ClientRequest('GET', 'http://host:80', ++ loop=self.loop, ++ response_class=unittest.mock.Mock()) + + conn = aiohttp.BaseConnector(loop=self.loop, limit=1) + key = ('host', 80, False) +@@ -545,14 +540,14 @@ class TestBaseConnector(unittest.TestCase): + self.loop) + conn._create_connection.return_value.set_result((tr, proto)) + +- connection = yield from conn.connect(Req()) ++ connection = yield from conn.connect(req) + self.assertEqual(connection._transport, tr) + + self.assertEqual(1, len(conn._acquired[key])) + + with self.assertRaises(asyncio.TimeoutError): + # limit exhausted +- yield from asyncio.wait_for(conn.connect(Req), 0.01, ++ yield from asyncio.wait_for(conn.connect(req), 0.01, + loop=self.loop) + connection.close() + self.loop.run_until_complete(go()) +@@ -583,11 +578,10 @@ class TestBaseConnector(unittest.TestCase): + proto = unittest.mock.Mock() + proto.is_connected.return_value = True + +- class Req: +- host = 'host' +- port = 80 +- ssl = False +- response = unittest.mock.Mock(_should_close=False) ++ req = ClientRequest('GET', 'http://host:80', ++ loop=self.loop, ++ response_class=unittest.mock.Mock( ++ _should_close=False)) + + max_connections = 2 + num_connections = 0 +@@ -629,7 +623,7 @@ class TestBaseConnector(unittest.TestCase): + return + num_requests += 1 + if not start: +- connection = yield from conn.connect(Req()) ++ connection = yield from conn.connect(req) + yield from asyncio.sleep(0, loop=self.loop) + connection.release() + tasks = [ +@@ -652,11 +646,9 @@ class TestBaseConnector(unittest.TestCase): + tr, proto = unittest.mock.Mock(), unittest.mock.Mock() + proto.is_connected.return_value = True + +- class Req: +- host = 'host' +- port = 80 +- ssl = False +- response = unittest.mock.Mock() ++ req = ClientRequest('GET', 'http://host:80', ++ loop=self.loop, ++ response_class=unittest.mock.Mock()) + + conn = aiohttp.BaseConnector(loop=self.loop, limit=1) + key = ('host', 80, False) +@@ -666,7 +658,7 @@ class TestBaseConnector(unittest.TestCase): + self.loop) + conn._create_connection.return_value.set_result((tr, proto)) + +- connection = yield from conn.connect(Req()) ++ connection = yield from conn.connect(req) + + self.assertEqual(1, len(conn._acquired)) + conn.close() +@@ -723,19 +715,12 @@ class TestHttpClientConnector(unittest.TestCase): + self.loop.close() + gc.collect() + +- def find_unused_port(self): +- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +- s.bind(('127.0.0.1', 0)) +- port = s.getsockname()[1] +- s.close() +- return port +- + @asyncio.coroutine + def create_server(self, method, path, handler): + app = web.Application(loop=self.loop) + app.router.add_route(method, path, handler) + +- port = self.find_unused_port() ++ port = unused_port() + self.handler = app.make_handler(keep_alive_on=False) + srv = yield from self.loop.create_server( + self.handler, '127.0.0.1', port) +@@ -785,7 +770,7 @@ class TestHttpClientConnector(unittest.TestCase): + self.create_server('get', '/', handler) + ) + +- port = self.find_unused_port() ++ port = unused_port() + conn = aiohttp.TCPConnector(loop=self.loop, + local_addr=('127.0.0.1', port)) + +@@ -845,14 +830,12 @@ class TestHttpClientConnector(unittest.TestCase): + resolver = unittest.mock.MagicMock() + connector = aiohttp.TCPConnector(resolver=resolver, loop=self.loop) + +- class Req: +- host = '127.0.0.1' +- port = 80 +- ssl = False +- response = unittest.mock.Mock() ++ req = ClientRequest('GET', 'http://127.0.0.1:{}'.format(unused_port()), ++ loop=self.loop, ++ response_class=unittest.mock.Mock()) + + with self.assertRaises(OSError): +- self.loop.run_until_complete(connector.connect(Req())) ++ self.loop.run_until_complete(connector.connect(req)) + + resolver.resolve.assert_not_called() + diff --git a/debian/rules b/debian/rules index 4e5e3cf..8c932a6 100755 --- a/debian/rules +++ b/debian/rules @@ -4,8 +4,6 @@ export PYBUILD_NAME = aiohttp # enable pytest also here to make backports easier export PYBUILD_TEST_PYTEST=1 export PYBUILD_TEST_ARGS={dir}/tests -export PYBUILD_TEST_ARGS_python3.5=$(PYBUILD_TEST_ARGS) -k-test_client_functional_oldstyle -export PYBUILD_TEST_ARGS_python3.5-dbg=$(PYBUILD_TEST_ARGS_python3.5) %: dh $@ --with python3,sphinxdoc --buildsystem pybuild @@ -13,3 +11,6 @@ export PYBUILD_TEST_ARGS_python3.5-dbg=$(PYBUILD_TEST_ARGS_python3.5) override_dh_auto_clean: rm -rf .cache dh_auto_clean + +override_dh_strip: + dh_strip --no-automatic-dbgsym diff --git a/docs/abc.rst b/docs/abc.rst new file mode 100644 index 0000000..8556221 --- /dev/null +++ b/docs/abc.rst @@ -0,0 +1,126 @@ +.. _aiohttp-abc: + +Abstract Base Classes +===================== + +.. module:: aiohttp.abc + +.. currentmodule:: aiohttp.abc + +Abstract routing +---------------- + +aiohttp has abstract classes for managing web interfaces. + +The most part of :mod:`aiohttp.web` is not intended to be inherited +but few of them are. + +aiohttp.web is built on top of few concepts: *application*, *router*, +*request* and *response*. + +*router* is a *pluggable* part: a library user may build a *router* +from scratch, all other parts should work with new router seamlessly. + +:class:`AbstractRouter` has the only mandatory method: +:meth:`AbstractRouter.resolve` coroutine. It should return an +:class:`AbstractMatchInfo` instance. + +If the requested URL handler is found +:meth:`AbstractMatchInfo.handler` is a :term:`web-handler` for +requested URL and :attr:`AbstractMatchInfo.http_exception` is ``None``. + +Otherwise :attr:`AbstractMatchInfo.http_exception` is an instance of +:exc:`~aiohttp.web.HTTPException` like *404: NotFound* or *405: Method +Not Allowed*. :meth:`AbstractMatchInfo.handler` raises +:attr:`~AbstractMatchInfo.http_exception` on call. + + +.. class:: AbstractRouter + + Abstract router, :class:`aiohttp.web.Application` accepts it as + *router* parameter and returns as + :attr:`aiohttp.web.Application.router`. + + .. coroutinemethod:: resolve(request) + + Performs URL resolving. It's an abstract method, should be + overridden in *router* implementation. + + :param request: :class:`aiohttp.web.Request` instance for + resolving, the request has + :attr:`aiohttp.web.Request.match_info` equals to + ``None`` at resolving stage. + + :return: :class:`AbstractMatchInfo` instance. + + +.. class:: AbstractMatchInfo + + Abstract *match info*, returned by :meth:`AbstractRouter` call. + + .. attribute:: http_exception + + :exc:`aiohttp.web.HTTPException` if no match was found, ``None`` + otherwise. + + .. coroutinemethod:: handler(request) + + Abstract method performing :term:`web-handler` processing. + + :param request: :class:`aiohttp.web.Request` instance for + resolving, the request has + :attr:`aiohttp.web.Request.match_info` equals to + ``None`` at resolving stage. + :return: :class:`aiohttp.web.StreamResponse` or descendants. + + :raise: :class:`aiohttp.web.HTTPException` on error + + .. coroutinemethod:: expect_handler(request) + + Abstract method for handling *100-continue* processing. + + +Abstract Class Based Views +-------------------------- + +For *class based view* support aiohttp has abstract +:class:`AbstractView` class which is *awaitable* (may be uses like +``await Cls()`` or ``yield from Cls()`` and has a *request* as an +attribute. + +.. class:: AbstractView + + An abstract class, base for all *class based views* implementations. + + Methods ``__iter__`` and ``__await__`` should be overridden. + + .. attribute:: request + + :class:`aiohttp.web.Request` instance for performing the request. + + +Abstract Cookie Jar +------------------- + +.. class:: AbstractCookieJar(*, loop=None) + + An abstract class for cookie storage. + + :param loop: an :ref:`event loop<asyncio-event-loop>` instance. + + If param is ``None`` :func:`asyncio.get_event_loop` + used for getting default event loop, but we strongly + recommend to use explicit loops everywhere. + + + .. attribute:: cookies + + :class:`http.cookies.SimpleCookie` instance for storing cookies info. + + .. method:: update_cookies(cookies, response_url=None) + + Update cookies. + + .. method:: filter_cookies(request_url) + + Returns this jar's cookies filtered by their attributes. diff --git a/docs/aiohttp_doctools.py b/docs/aiohttp_doctools.py deleted file mode 100644 index fb21066..0000000 --- a/docs/aiohttp_doctools.py +++ /dev/null @@ -1,27 +0,0 @@ -from sphinx.domains.python import PyModulelevel, PyClassmember -from sphinx import addnodes - - -class PyCoroutineMixin(object): - def handle_signature(self, sig, signode): - ret = super(PyCoroutineMixin, self).handle_signature(sig, signode) - signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine ')) - return ret - - -class PyCoroutineFunction(PyCoroutineMixin, PyModulelevel): - def run(self): - self.name = 'py:function' - return PyModulelevel.run(self) - - -class PyCoroutineMethod(PyCoroutineMixin, PyClassmember): - def run(self): - self.name = 'py:method' - return PyClassmember.run(self) - - -def setup(app): - app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction) - app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod) - return {'version': '1.0', 'parallel_read_safe': True} diff --git a/docs/api.rst b/docs/api.rst index 18446de..e9f6d46 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -42,14 +42,6 @@ aiohttp.parsers module :undoc-members: :show-inheritance: -aiohttp.protocol module ------------------------ - -.. automodule:: aiohttp.protocol - :members: - :undoc-members: - :show-inheritance: - aiohttp.signals module ---------------------- @@ -66,6 +58,7 @@ aiohttp.streams module :undoc-members: :show-inheritance: + aiohttp.websocket module ------------------------ @@ -82,4 +75,5 @@ aiohttp.wsgi module :undoc-members: :show-inheritance: + .. disqus:: diff --git a/docs/client.rst b/docs/client.rst index 25e4c5c..f30503b 100644 --- a/docs/client.rst +++ b/docs/client.rst @@ -18,23 +18,27 @@ Begin by importing the aiohttp module:: Now, let's try to get a web-page. For example let's get GitHub's public time-line :: - r = await aiohttp.get('https://api.github.com/events') + async with aiohttp.ClientSession() as session: + async with session.get('https://api.github.com/events') as resp: + print(resp.status) + print(await resp.text()) -Now, we have a :class:`ClientResponse` object called ``r``. We can get all the -information we need from this object. -The mandatory parameter of :func:`get` coroutine is an HTTP url. +Now, we have a :class:`ClientSession` called ``session`` and +a :class:`ClientResponse` object called ``resp``. We can get all the +information we need from the response. The mandatory parameter of +:meth:`ClientSession.get` coroutine is an HTTP url. -In order to make an HTTP POST request use :func:`post` coroutine:: +In order to make an HTTP POST request use :meth:`ClientSession.post` coroutine:: - r = await aiohttp.post('http://httpbin.org/post', data=b'data') + session.post('http://httpbin.org/post', data=b'data') Other HTTP methods are available as well:: - r = await aiohttp.put('http://httpbin.org/put', data=b'data') - r = await aiohttp.delete('http://httpbin.org/delete') - r = await aiohttp.head('http://httpbin.org/get') - r = await aiohttp.options('http://httpbin.org/get') - r = await aiohttp.patch('http://httpbin.org/patch', data=b'data') + session.put('http://httpbin.org/put', data=b'data') + session.delete('http://httpbin.org/delete') + session.head('http://httpbin.org/get') + session.options('http://httpbin.org/get') + session.patch('http://httpbin.org/patch', data=b'data') Passing Parameters In URLs @@ -43,33 +47,36 @@ Passing Parameters In URLs You often want to send some sort of data in the URL's query string. If you were constructing the URL by hand, this data would be given as key/value pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``. -Requests allows you to provide these arguments as a dictionary, using the +Requests allows you to provide these arguments as a :class:`dict`, using the ``params`` keyword argument. As an example, if you wanted to pass ``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the following code:: - payload = {'key1': 'value1', 'key2': 'value2'} - async with aiohttp.get('http://httpbin.org/get', - params=payload) as r: - assert r.url == 'http://httpbin.org/get?key2=value2&key1=value1' + params = {'key1': 'value1', 'key2': 'value2'} + async with session.get('http://httpbin.org/get', + params=params) as resp: + assert resp.url == 'http://httpbin.org/get?key2=value2&key1=value1' You can see that the URL has been correctly encoded by printing the URL. +For sending data with multiple values for the same key +:class:`MultiDict` may be used as well. + It is also possible to pass a list of 2 item tuples as parameters, in that case you can specify multiple values for each key:: - payload = [('key', 'value1'), ('key', 'value2')] - async with aiohttp.get('http://httpbin.org/get', - params=payload) as r: + params = [('key', 'value1'), ('key', 'value2')] + async with session.get('http://httpbin.org/get', + params=params) as r: assert r.url == 'http://httpbin.org/get?key=value2&key=value1' -You can also pass ``str`` content as param, but beware - content is not encoded -by library. Note that ``+`` is not encoded:: +You can also pass :class:`str` content as param, but beware - content +is not encoded by library. Note that ``+`` is not encoded:: - async with aiohttp.get('http://httpbin.org/get', - params='key=value+1') as r: - assert r.url = 'http://httpbin.org/get?key=value+1' + async with session.get('http://httpbin.org/get', + params='key=value+1') as r: + assert r.url == 'http://httpbin.org/get?key=value+1' Response Content ---------------- @@ -77,8 +84,8 @@ Response Content We can read the content of the server's response. Consider the GitHub time-line again:: - r = await aiohttp.get('https://api.github.com/events') - print(await r.text()) + async with session.get('https://api.github.com/events') as resp: + print(await resp.text()) will printout something like:: @@ -87,7 +94,7 @@ will printout something like:: ``aiohttp`` will automatically decode the content from the server. You can specify custom encoding for the :meth:`~ClientResponse.text` method:: - await r.text(encoding='windows-1251') + await resp.text(encoding='windows-1251') Binary Response Content @@ -95,7 +102,7 @@ Binary Response Content You can also access the response body as bytes, for non-text requests:: - print(await r.read()) + print(await resp.read()) :: @@ -110,8 +117,8 @@ JSON Response Content There's also a built-in JSON decoder, in case you're dealing with JSON data:: - async with aiohttp.get('https://api.github.com/events') as r: - print(await r.json()) + async with session.get('https://api.github.com/events') as resp: + print(await resp.json()) In case that JSON decoding fails, :meth:`~ClientResponse.json` will raise an exception. It is possible to specify custom encoding and @@ -127,19 +134,19 @@ convenient you should use them carefully. All these methods load the whole response in memory. For example if you want to download several gigabyte sized files, these methods will load all the data in memory. Instead you can use the :attr:`~ClientResponse.content` -attribute. It is an instance of the ``aiohttp.StreamReader`` +attribute. It is an instance of the :class:`aiohttp.StreamReader` class. The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you:: - async with aiohttp.get('https://api.github.com/events') as r: - await r.content.read(10) + async with session.get('https://api.github.com/events') as resp: + await resp.content.read(10) In general, however, you should use a pattern like this to save what is being streamed to a file:: with open(filename, 'wb') as fd: while True: - chunk = await r.content.read(chunk_size) + chunk = await resp.content.read(chunk_size) if not chunk: break fd.write(chunk) @@ -157,12 +164,12 @@ behavior and proper connection pooling. The easiest way to correctly response releasing is ``async with`` statement:: - async with client.get(url) as resp: + async with session.get(url) as resp: pass But explicit :meth:`~ClientResponse.release` call also may be used:: - await r.release() + await resp.release() But it's not necessary if you use :meth:`~ClientResponse.read`, :meth:`~ClientResponse.json` and :meth:`~ClientResponse.text` methods. @@ -184,7 +191,7 @@ example:: payload = {'some': 'data'} headers = {'content-type': 'application/json'} - await aiohttp.post(url, + await session.post(url, data=json.dumps(payload), headers=headers) @@ -193,13 +200,18 @@ Custom Cookies -------------- To send your own cookies to the server, you can use the *cookies* -parameter:: +parameter of :class:`ClientSession` constructor:: url = 'http://httpbin.org/cookies' - cookies = dict(cookies_are='working') + async with ClientSession({'cookies_are': 'working'}) as session: + async with session.get(url) as resp: + assert await resp.json() == {"cookies": + {"cookies_are": "working"}} - async with aiohttp.get(url, cookies=cookies) as r: - assert await r.json() == {"cookies": {"cookies_are": "working"}} +.. note:: + ``httpbin.org/cookies`` endpoint returns request cookies + in JSON-encoded body. + To access session cookies see :attr:`ClientSession.cookies`. More complicated POST requests @@ -210,9 +222,9 @@ To do this, simply pass a dictionary to the *data* argument. Your dictionary of data will automatically be form-encoded when the request is made:: payload = {'key1': 'value1', 'key2': 'value2'} - async with aiohttp.post('http://httpbin.org/post', - data=payload) as r: - print(await r.text()) + async with session.post('http://httpbin.org/post', + data=payload) as resp: + print(await resp.text()) :: @@ -235,7 +247,8 @@ For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data:: url = 'https://api.github.com/some/endpoint' payload = {'some': 'data'} - r = await aiohttp.post(url, data=json.dumps(payload)) + async with session.post(url, data=json.dumps(payload)) as resp: + ... POST a Multipart-Encoded File @@ -246,7 +259,7 @@ To upload Multipart-encoded files:: url = 'http://httpbin.org/post' files = {'file': open('report.xls', 'rb')} - await aiohttp.post(url, data=files) + await session.post(url, data=files) You can set the filename, content_type explicitly:: @@ -257,7 +270,7 @@ You can set the filename, content_type explicitly:: filename='report.xls', content_type='application/vnd.ms-excel') - await aiohttp.post(url, data=data) + await session.post(url, data=data) If you pass a file object as data parameter, aiohttp will stream it to the server automatically. Check :class:`~aiohttp.streams.StreamReader` @@ -275,7 +288,7 @@ send large files without reading them into memory. As a simple case, simply provide a file-like object for your body:: with open('massive-body', 'rb') as f: - await aiohttp.post('http://some.url/streamed', data=f) + await session.post('http://some.url/streamed', data=f) Or you can provide an :ref:`coroutine<coroutine>` that yields bytes objects:: @@ -307,13 +320,13 @@ calculate the file SHA1 hash:: if not chunk: break h.update(chunk) - s.feed_data(chunk) + stream.feed_data(chunk) return h.hexdigest() - resp = aiohttp.get('http://httpbin.org/post') + resp = session.get('http://httpbin.org/post') stream = StreamReader() - loop.create_task(aiohttp.post('http://httpbin.org/post', data=stream)) + loop.create_task(session.post('http://httpbin.org/post', data=stream)) file_hash = await feed_stream(resp, stream) @@ -322,8 +335,8 @@ Because the response content attribute is a :class:`~aiohttp.streams.StreamReader`, you can chain get and post requests together (aka HTTP pipelining):: - r = await aiohttp.request('get', 'http://python.org') - await aiohttp.post('http://httpbin.org/post', + r = await session.get('http://python.org') + await session.post('http://httpbin.org/post', data=r.content) @@ -335,13 +348,14 @@ the request function with ``compress=False`` and set the used compression algorithm name (usually deflate or zlib) as the value of the ``Content-Encoding`` header:: - @asyncio.coroutine - def my_coroutine( my_data): + async def my_coroutine(session, headers, my_data): data = zlib.compress(my_data) headers = {'Content-Encoding': 'deflate'} - yield from aiohttp.post( - 'http://httpbin.org/post', data=data, headers=headers, - compress=False) + async with session.post('http://httpbin.org/post', + data=data, + headers=headers, + compress=False): + pass .. _aiohttp-client-session: @@ -349,42 +363,61 @@ algorithm name (usually deflate or zlib) as the value of the Keep-Alive, connection pooling and cookie sharing ------------------------------------------------- -To share cookies between multiple requests you can create an -:class:`~aiohttp.client.ClientSession` object:: +:class:`~aiohttp.ClientSession` may be used for sharing cookies +between multiple requests:: - session = aiohttp.ClientSession() - await session.post( - 'http://httpbin.org/cookies/set/my_cookie/my_value') - async with session.get('http://httpbin.org/cookies') as r: - json = await r.json() - assert json['cookies']['my_cookie'] == 'my_value' + async with aiohttp.ClientSession() as session: + await session.get( + 'http://httpbin.org/cookies/set?my_cookie=my_value') + assert session.cookies['my_cookie'].value == 'my_value' + async with session.get('http://httpbin.org/cookies') as r: + json_body = await r.json() + assert json_body['cookies']['my_cookie'] == 'my_value' You also can set default headers for all session requests:: - session = aiohttp.ClientSession( - headers={"Authorization": "Basic bG9naW46cGFzcw=="}) - async with s.get("http://httpbin.org/headers") as r: - json = yield from r.json() - assert json['headers']['Authorization'] == 'Basic bG9naW46cGFzcw==' + async with aiohttp.ClientSession( + headers={"Authorization": "Basic bG9naW46cGFzcw=="}) as session: + async with session.get("http://httpbin.org/headers") as r: + json_body = await r.json() + assert json_body['headers']['Authorization'] == \ + 'Basic bG9naW46cGFzcw==' + +:class:`~aiohttp.ClientSession` supports keep-alive requests +and connection pooling out-of-the-box. + +.. _aiohttp-client-cookie-safety: + +Cookie safety +------------- + +By default :class:`~aiohttp.ClientSession` uses strict version of +:class:`~aiohttp.CookieJar`. :rfc:`2109` explicitly forbids cookie +accepting from URLs with IP address instead of DNS name +(e.g. `http://127.0.0.1:80/cookie`). + +It's good but sometimes for testing we need to enable support for such +cookies. It should be done by passing `usafe=True` to +:class:`~aiohttp.CookieJar` constructor:: -By default aiohttp does not use connection pooling. In other words -multiple calls to :func:`~aiohttp.client.request` will start a new -connection to host each. :class:`~aiohttp.client.ClientSession` -object will do connection pooling for you. + + jar = aiohttp.CookieJar(unsafe=True) + session = aiohttp.ClientSession(cookie_jar=jar) Connectors ---------- To tweak or change *transport* layer of requests you can pass a custom -**Connector** to :func:`aiohttp.request` and family. For example:: +*connector* to :class:`~aiohttp.ClientSession` and family. For example:: conn = aiohttp.TCPConnector() - r = await aiohttp.get('http://python.org', connector=conn) + session = aiohttp.ClientSession(connector=aiohttp.TCPConnector()) -:class:`ClientSession` constructor also accepts *connector* instance:: - session = aiohttp.ClientSession(connector=aiohttp.TCPConnector()) +.. seealso:: :ref:`aiohttp-client-reference-connectors` section for + more information about different connector types and + configuration options. Limiting connection pool size @@ -392,17 +425,30 @@ Limiting connection pool size To limit amount of simultaneously opened connection to the same endpoint (``(host, port, is_ssl)`` triple) you can pass *limit* -parameter to **connector**:: +parameter to *connector*:: conn = aiohttp.TCPConnector(limit=30) The example limits amount of parallel connections to `30`. +Resolving using custom nameservers +---------------------------------- + +In order to specify the nameservers to when resolving the hostnames, +aiodns is required. + + from aiohttp.resolver import AsyncResolver + + + resolver = AsyncResolver(nameservers=["8.8.8.8", "8.8.4.4"]) + conn = aiohttp.TCPConnector(resolver=resolver) + + SSL control for TCP sockets --------------------------- -:class:`aiohttp.connector.TCPConnector` constructor accepts mutually +:class:`~aiohttp.TCPConnector` constructor accepts mutually exclusive *verify_ssl* and *ssl_context* params. By default it uses strict checks for HTTPS protocol. Certification @@ -455,27 +501,28 @@ Unix domain sockets ------------------- If your HTTP server uses UNIX domain sockets you can use -:class:`aiohttp.connector.UnixConnector`:: +:class:`~aiohttp.UnixConnector`:: conn = aiohttp.UnixConnector(path='/path/to/socket') - r = await aiohttp.get('http://python.org', connector=conn) + session = aiohttp.ClientSession(connector=conn) Proxy support ------------- aiohttp supports proxy. You have to use -:class:`aiohttp.connector.ProxyConnector`:: +:class:`~aiohttp.ProxyConnector`:: conn = aiohttp.ProxyConnector(proxy="http://some.proxy.com") - r = await aiohttp.get('http://python.org', - connector=conn) + session = aiohttp.ClientSession(connector=conn) + async with session.get('http://python.org') as resp: + print(resp.status) -:class:`~aiohttp.connector.ProxyConnector` also supports proxy authorization:: +:class:`~aiohttp.ProxyConnector` also supports proxy authorization:: conn = aiohttp.ProxyConnector( - proxy="http://some.proxy.com", - proxy_auth=aiohttp.BasicAuth('user', 'pass')) + proxy="http://some.proxy.com", + proxy_auth=aiohttp.BasicAuth('user', 'pass')) session = aiohttp.ClientSession(connector=conn) async with session.get('http://python.org') as r: assert r.status == 200 @@ -484,9 +531,6 @@ Authentication credentials can be passed in proxy URL:: conn = aiohttp.ProxyConnector( proxy="http://user:pass@some.proxy.com") - session = aiohttp.ClientSession(connector=conn) - async with session.get('http://python.org') as r: - assert r.status == 200 Response Status Codes @@ -494,16 +538,17 @@ Response Status Codes We can check the response status code:: - async with aiohttp.get('http://httpbin.org/get') as r: - assert r.status == 200 + async with session.get('http://httpbin.org/get') as resp: + assert resp.status == 200 Response Headers ---------------- -We can view the server's response headers using a multidict:: +We can view the server's response :attr:`ClientResponse.headers` using +a :class:`CIMultiDictProxy`:: - >>> r.headers + >>> resp.headers {'ACCESS-CONTROL-ALLOW-ORIGIN': '*', 'CONTENT-TYPE': 'application/json', 'DATE': 'Tue, 15 Jul 2014 16:49:51 GMT', @@ -519,12 +564,25 @@ key as HTTP protocol does. So, we can access the headers using any capitalization we want:: - >>> r.headers['Content-Type'] + >>> resp.headers['Content-Type'] 'application/json' - >>> r.headers.get('content-type') + >>> resp.headers.get('content-type') 'application/json' +All headers converted from binary data using UTF-8 with +``surrogateescape`` option. That works fine on most cases but +sometimes unconverted data is needed if a server uses nonstandard +encoding. While these headers are malformed from :rfc:`7230` +perspective they are may be retrieved by using +:attr:`ClientResponse.raw_headers` property:: + + >>> resp.raw_headers + ((b'SERVER', b'nginx'), + (b'DATE', b'Sat, 09 Jan 2016 20:28:40 GMT'), + (b'CONTENT-TYPE', b'text/html; charset=utf-8'), + (b'CONTENT-LENGTH', b'12150'), + (b'CONNECTION', b'keep-alive')) Response Cookies ---------------- @@ -532,8 +590,8 @@ Response Cookies If a response contains some Cookies, you can quickly access them:: url = 'http://example.com/some/cookie/setting/url' - async with aiohttp.get(url) as r: - print(r.cookies['example_cookie_name']) + async with session.get(url) as resp: + print(resp.cookies['example_cookie_name']) .. note:: @@ -549,10 +607,10 @@ Response History If a request was redirected, it is possible to view previous responses using the :attr:`~ClientResponse.history` attribute:: - >>> r = await aiohttp.get('http://example.com/some/redirect/') - >>> r + >>> resp = await session.get('http://example.com/some/redirect/') + >>> resp <ClientResponse(http://example.com/some/other/url/) [200]> - >>> r.history + >>> resp.history (<ClientResponse(http://example.com/some/redirect/) [301]>,) If no redirects occurred or ``allow_redirects`` is set to ``False``, @@ -564,9 +622,6 @@ history will be an empty sequence. WebSockets ---------- -.. versionadded:: 0.15 - - :mod:`aiohttp` works with client websockets out-of-the-box. You have to use the :meth:`aiohttp.ClientSession.ws_connect` coroutine @@ -590,13 +645,6 @@ methods:: elif msg.tp == aiohttp.MsgType.error: break -If you prefer to establish *websocket client connection* without -explicit :class:`~aiohttp.ClientSession` instance please use -:func:`ws_connect()`:: - - async with aiohttp.ws_connect('http://example.org/websocket') as ws: - ... - You **must** use the only websocket task for both reading (e.g ``await ws.receive()`` or ``async for msg in ws:``) and writing but may have @@ -607,27 +655,13 @@ multiple writer tasks which can only send data asynchronously (by Timeouts -------- -You should use :func:`asyncio.wait_for()` coroutine if you want to limit -time to wait for a response from a server:: - - >>> asyncio.wait_for(aiohttp.get('http://github.com'), - ... 0.001) - Traceback (most recent call last)\: - File "<stdin>", line 1, in <module> - asyncio.TimeoutError() - -Or wrap your client call in :class:`Timeout` context manager:: +The example wraps a client call in :class:`Timeout` context +manager, adding timeout for both connecting and response body +reading procedures:: with aiohttp.Timeout(0.001): async with aiohttp.get('https://github.com') as r: await r.text() -.. warning:: - - *timeout* is not a time limit on the entire response download; - rather, an exception is raised if the server has not issued a - response for *timeout* seconds (more precisely, if no bytes have been - received on the underlying socket for *timeout* seconds). - .. disqus:: diff --git a/docs/client_reference.rst b/docs/client_reference.rst index 38da9bb..3c0e59d 100644 --- a/docs/client_reference.rst +++ b/docs/client_reference.rst @@ -13,8 +13,11 @@ Client Session Client session is the recommended interface for making HTTP requests. -Session encapsulates *connection pool* (*connector* instance) and -supports keepalives by default. +Session encapsulates a *connection pool* (*connector* instance) and +supports keepalives by default. Unless you are connecting to a large, +unknown number of different servers over the lifetime of your +application, it is suggested you use a single session for the +lifetime of your application to benefit from connection pooling. Usage example:: @@ -24,20 +27,23 @@ Usage example:: async def fetch(client): async with client.get('http://python.org') as resp: assert resp.status == 200 - print(await resp.text()) + return await resp.text() with aiohttp.ClientSession() as client: - asyncio.get_event_loop().run_until_complete(fetch(client)) + html = asyncio.get_event_loop().run_until_complete(fetch(client)) + print(html) .. versionadded:: 0.17 -The client session supports context manager protocol for self closing. +The client session supports the context manager protocol for self closing. -.. class:: ClientSession(*, connector=None, loop=None, cookies=None,\ +.. class:: ClientSession(*, connector=None, loop=None, cookies=None, \ headers=None, skip_auto_headers=None, \ - auth=None, request_class=ClientRequest,\ + auth=None, request_class=ClientRequest, \ response_class=ClientResponse, \ - ws_response_class=ClientWebSocketResponse) + ws_response_class=ClientWebSocketResponse, + version=aiohttp.HttpVersion11, + cookie_jar=None) The class for creating client sessions and making requests. @@ -89,6 +95,21 @@ The client session supports context manager protocol for self closing. .. versionadded:: 0.16 + :param version: supported HTTP version, ``HTTP 1.1`` by default. + + .. versionadded:: 0.21 + + :param cookie_jar: Cookie Jar, :class:`AbstractCookieJar` instance. + + By default every session instance has own private cookie jar for + automatic cookies processing but user may redefine this behavior + by providing own jar implementation. + + One example is not processing cookies at all when working in + proxy mode. + + .. versionadded:: 0.22 + .. versionchanged:: 0.16 *request_class* default changed from ``None`` to ``ClientRequest`` @@ -116,13 +137,15 @@ The client session supports context manager protocol for self closing. forbidden, but you may modify the object in-place if needed. - .. coroutinemethod:: request(method, url, *, params=None, data=None,\ - headers=None, skip_auto_headers=None, \ - auth=None, allow_redirects=True,\ - max_redirects=10, encoding='utf-8',\ - version=HttpVersion(major=1, minor=1),\ - compress=None, chunked=None, expect100=False,\ - read_until_eof=True) + .. comethod:: request(method, url, *, params=None, data=None,\ + headers=None, skip_auto_headers=None, \ + auth=None, allow_redirects=True,\ + max_redirects=10, encoding='utf-8',\ + version=HttpVersion(major=1, minor=1),\ + compress=None, chunked=None, expect100=False,\ + read_until_eof=True) + :async-with: + :coroutine: Performs an asynchronous HTTP request. Returns a response object. @@ -133,7 +156,8 @@ The client session supports context manager protocol for self closing. :param params: Mapping, iterable of tuple of *key*/*value* pairs or string to be sent as parameters in the query - string of the new request (optional) + string of the new request. Ignored for subsequent + redirected requests (optional) Allowed values are: @@ -188,7 +212,9 @@ The client session supports context manager protocol for self closing. :return ClientResponse: a :class:`client response <ClientResponse>` object. - .. coroutinemethod:: get(url, *, allow_redirects=True, **kwargs) + .. comethod:: get(url, *, allow_redirects=True, **kwargs) + :async-with: + :coroutine: Perform a ``GET`` request. @@ -204,7 +230,9 @@ The client session supports context manager protocol for self closing. :return ClientResponse: a :class:`client response <ClientResponse>` object. - .. coroutinemethod:: post(url, *, data=None, **kwargs) + .. comethod:: post(url, *, data=None, **kwargs) + :async-with: + :coroutine: Perform a ``POST`` request. @@ -221,7 +249,9 @@ The client session supports context manager protocol for self closing. :return ClientResponse: a :class:`client response <ClientResponse>` object. - .. coroutinemethod:: put(url, *, data=None, **kwargs) + .. comethod:: put(url, *, data=None, **kwargs) + :async-with: + :coroutine: Perform a ``PUT`` request. @@ -238,7 +268,9 @@ The client session supports context manager protocol for self closing. :return ClientResponse: a :class:`client response <ClientResponse>` object. - .. coroutinemethod:: delete(url, **kwargs) + .. comethod:: delete(url, **kwargs) + :async-with: + :coroutine: Perform a ``DELETE`` request. @@ -251,7 +283,9 @@ The client session supports context manager protocol for self closing. :return ClientResponse: a :class:`client response <ClientResponse>` object. - .. coroutinemethod:: head(url, *, allow_redirects=False, **kwargs) + .. comethod:: head(url, *, allow_redirects=False, **kwargs) + :async-with: + :coroutine: Perform a ``HEAD`` request. @@ -267,7 +301,9 @@ The client session supports context manager protocol for self closing. :return ClientResponse: a :class:`client response <ClientResponse>` object. - .. coroutinemethod:: options(url, *, allow_redirects=True, **kwargs) + .. comethod:: options(url, *, allow_redirects=True, **kwargs) + :async-with: + :coroutine: Perform an ``OPTIONS`` request. @@ -284,7 +320,9 @@ The client session supports context manager protocol for self closing. :return ClientResponse: a :class:`client response <ClientResponse>` object. - .. coroutinemethod:: patch(url, *, data=None, **kwargs) + .. comethod:: patch(url, *, data=None, **kwargs) + :async-with: + :coroutine: Perform a ``PATCH`` request. @@ -301,11 +339,13 @@ The client session supports context manager protocol for self closing. :return ClientResponse: a :class:`client response <ClientResponse>` object. - .. coroutinemethod:: ws_connect(url, *, protocols=(), timeout=10.0,\ - auth=None,\ - autoclose=True,\ - autoping=True,\ - origin=None) + .. comethod:: ws_connect(url, *, protocols=(), timeout=10.0,\ + auth=None,\ + autoclose=True,\ + autoping=True,\ + origin=None) + :async-with: + :coroutine: Create a websocket connection. Returns a :class:`ClientWebSocketResponse` object. @@ -340,12 +380,18 @@ The client session supports context manager protocol for self closing. Add *origin* parameter. - .. method:: close() + .. comethod:: close() Close underlying connector. Release all acquired resources. + .. versionchanged:: 0.21 + + The method is converted into coroutine (but technically + returns a future for keeping backward compatibility during + transition period). + .. method:: detach() Detach connector from session without closing the former. @@ -444,6 +490,10 @@ Usage:: assert resp.status == 200 print(await resp.text()) + .. deprecated:: 0.21 + + Use :meth:`ClientSession.request`. + .. coroutinefunction:: get(url, **kwargs) @@ -455,6 +505,10 @@ Usage:: :return: :class:`ClientResponse` or derived from + .. deprecated:: 0.21 + + Use :meth:`ClientSession.get`. + .. coroutinefunction:: options(url, **kwargs) @@ -466,6 +520,10 @@ Usage:: :return: :class:`ClientResponse` or derived from + .. deprecated:: 0.21 + + Use :meth:`ClientSession.options`. + .. coroutinefunction:: head(url, **kwargs) @@ -477,6 +535,10 @@ Usage:: :return: :class:`ClientResponse` or derived from + .. deprecated:: 0.21 + + Use :meth:`ClientSession.head`. + .. coroutinefunction:: delete(url, **kwargs) @@ -488,6 +550,10 @@ Usage:: :return: :class:`ClientResponse` or derived from + .. deprecated:: 0.21 + + Use :meth:`ClientSession.delete`. + .. coroutinefunction:: post(url, *, data=None, **kwargs) @@ -499,6 +565,10 @@ Usage:: :return: :class:`ClientResponse` or derived from + .. deprecated:: 0.21 + + Use :meth:`ClientSession.post`. + .. coroutinefunction:: put(url, *, data=None, **kwargs) @@ -510,6 +580,10 @@ Usage:: :return: :class:`ClientResponse` or derived from + .. deprecated:: 0.21 + + Use :meth:`ClientSession.put`. + .. coroutinefunction:: patch(url, *, data=None, **kwargs) @@ -521,6 +595,10 @@ Usage:: :return: :class:`ClientResponse` or derived from + .. deprecated:: 0.21 + + Use :meth:`ClientSession.patch`. + .. coroutinefunction:: ws_connect(url, *, protocols=(), \ timeout=10.0, connector=None, auth=None,\ @@ -580,8 +658,13 @@ Usage:: Add *headers* parameter. + .. deprecated:: 0.21 + + Use :meth:`ClientSession.ws_connect`. +.. _aiohttp-client-reference-connectors: + Connectors ---------- @@ -608,7 +691,7 @@ BaseConnector .. class:: BaseConnector(*, conn_timeout=None, keepalive_timeout=30, \ limit=None, \ - share_cookies=False, force_close=False, loop=None) + force_close=False, loop=None) Base class for all connectors. @@ -618,16 +701,15 @@ BaseConnector :param float keepalive_timeout: timeout for connection reusing after releasing (optional). Values - ``0`` or ``None`` mean no timeout. + ``0``. For disabling *keep-alive* + feature use ``force_close=True`` + flag. :param int limit: limit for simultaneous connections to the same endpoint. Endpoints are the same if they are have equal ``(host, port, is_ssl)`` triple. If *limit* is ``None`` the connector has no limit. - :param bool share_cookies: update :attr:`cookies` on connection - processing (optional, deprecated). - :param bool force_close: do close underlying sockets after connection releasing (optional). @@ -638,12 +720,6 @@ BaseConnector recommend to use explicit loops everywhere. (optional) - .. deprecated:: 0.15.2 - - *share_cookies* parameter is deprecated, use - :class:`~aiohttp.client.ClientSession` for handling cookies for - client connections. - .. attribute:: closed Read-only property, ``True`` if connector is closed. @@ -669,11 +745,17 @@ BaseConnector .. versionadded:: 0.16 - .. method:: close() + .. comethod:: close() Close all opened connections. - .. coroutinemethod:: connect(request) + .. versionchanged:: 0.21 + + The method is converted into coroutine (but technically + returns a future for keeping backward compatibility during + transition period). + + .. comethod:: connect(request) Get a free connection from pool or create new one if connection is absent in the pool. @@ -687,7 +769,7 @@ BaseConnector :return: :class:`Connection` object. - .. coroutinemethod:: _create_connection(req) + .. comethod:: _create_connection(req) Abstract method for actual connection establishing, should be overridden in subclasses. @@ -702,8 +784,8 @@ TCPConnector use_dns_cache=False, \ family=0, \ ssl_context=None, conn_timeout=None, \ - keepalive_timeout=30, limit=None, share_cookies=False, \ - force_close=False, loop=None) + keepalive_timeout=30, limit=None, \ + force_close=False, loop=None, local_addr=None) Connector for working with *HTTP* and *HTTPS* via *TCP* sockets. @@ -736,6 +818,15 @@ TCPConnector .. versionadded:: 0.17 + :param aiohttp.abc.AbstractResolver resolver: Custom resolver instance to use. + ``aiohttp.resolver.DefaultResolver`` by default. + + Custom resolvers allow to resolve hostnames differently than the way the + host is configured. Alternate resolvers include aiodns, which does not rely + on a thread executor. + + .. versionadded:: 0.22 + :param bool resolve: alias for *use_dns_cache* parameter. .. deprecated:: 0.17 @@ -757,6 +848,11 @@ TCPConnector *ssl_context* may be used for configuring certification authority channel, supported SSL options etc. + :param tuple local_addr: tuple of ``(local_host, local_port)`` used to bind + socket locally if specified. + + .. versionadded:: 0.21 + .. attribute:: verify_ssl Check *ssl certifications* if ``True``. @@ -836,7 +932,6 @@ ProxyConnector .. class:: ProxyConnector(proxy, *, proxy_auth=None, \ conn_timeout=None, \ keepalive_timeout=30, limit=None, \ - share_cookies=False, \ force_close=True, loop=None) HTTP Proxy connector. @@ -891,7 +986,6 @@ UnixConnector .. class:: UnixConnector(path, *, \ conn_timeout=None, \ keepalive_timeout=30, limit=None, \ - share_cookies=False, \ force_close=False, loop=None) Unix socket connector. @@ -996,6 +1090,18 @@ Response object HTTP status reason of response (:class:`str`), e.g. ``"OK"``. + .. attribute:: host + + Host part of requested url (:class:`str`). + + .. attribute:: method + + Request's method (:class:`str`). + + .. attribute:: url + + URL of request (:class:`str`). + .. attribute:: connection :class:`Connection` used for handling response. @@ -1013,7 +1119,13 @@ Response object .. attribute:: headers - HTTP headers of response, :class:`CIMultiDictProxy`. + A case-insensitive multidict proxy with HTTP headers of + response, :class:`CIMultiDictProxy`. + + .. attribute:: raw_headers + + HTTP headers of response as unconverted bytes, a sequence of + ``(key, value)`` pairs. .. attribute:: history @@ -1027,7 +1139,7 @@ Response object For :term:`keep-alive` support see :meth:`release`. - .. coroutinemethod:: read() + .. comethod:: read() Read the whole response's body as :class:`bytes`. @@ -1038,13 +1150,18 @@ Response object .. seealso:: :meth:`close`, :meth:`release`. - .. coroutinemethod:: release() + .. comethod:: release() Finish response processing, release underlying connection and return it into free connection pool for re-usage by next upcoming request. - .. coroutinemethod:: text(encoding=None) + .. method:: raise_for_status() + + Raise an HttpProcessingError if the response status is 400 or higher. + Do nothing for success responses (less than 400). + + .. comethod:: text(encoding=None) Read response's body and return decoded :class:`str` using specified *encoding* parameter. @@ -1062,7 +1179,7 @@ Response object :return str: decoded *BODY* - .. coroutinemethod:: json(encoding=None, loads=json.loads) + .. comethod:: json(encoding=None, loads=json.loads) Read response's body as *JSON*, return :class:`dict` using specified *encoding* and *loader*. @@ -1138,7 +1255,7 @@ manually. :raise TypeError: if data is not :class:`bytes`, :class:`bytearray` or :class:`memoryview`. - .. coroutinemethod:: close(*, code=1000, message=b'') + .. comethod:: close(*, code=1000, message=b'') A :ref:`coroutine<coroutine>` that initiates closing handshake by sending :const:`~aiohttp.websocket.MSG_CLOSE` message. It waits for @@ -1151,7 +1268,7 @@ manually. :class:`str` (converted to *UTF-8* encoded bytes) or :class:`bytes`. - .. coroutinemethod:: receive() + .. comethod:: receive() A :ref:`coroutine<coroutine>` that waits upcoming *data* message from peer and returns it. @@ -1188,6 +1305,16 @@ BasicAuth e.g. *auth* parameter for :meth:`ClientSession.request`. + .. classmethod:: decode(auth_header, encoding='latin1') + + Decode HTTP basic authentication credentials. + + :param str auth_header: The ``Authorization`` header to decode. + :param str encoding: (optional) encoding ('latin1' by default) + + :return: decoded authentication data, :class:`BasicAuth`. + + .. method:: encode() Encode credentials into string suitable for ``Authorization`` diff --git a/docs/conf.py b/docs/conf.py index d4c3c46..1ba3ef3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -54,17 +54,26 @@ extensions = [ 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'alabaster', - 'aiohttp_doctools', - 'sphinxcontrib.spelling', + 'sphinxcontrib.asyncio', 'sphinxcontrib.newsfeed', ] + +try: + import sphinxcontrib.spelling # noqa + extensions.append('sphinxcontrib.spelling') +except ImportError: + pass + + intersphinx_mapping = { 'python': ('http://docs.python.org/3', None), + 'multidict': + ('https://multidict.readthedocs.io/en/stable/', None), 'aiohttpjinja2': - ('http://aiohttp-jinja2.readthedocs.org/en/stable/', None), + ('https://aiohttp-jinja2.readthedocs.io/en/stable/', None), 'aiohttpsession': - ('http://aiohttp-session.readthedocs.org/en/stable/', None)} + ('https://aiohttp-session.readthedocs.io/en/stable/', None)} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -316,4 +325,3 @@ texinfo_documents = [ disqus_shortname = 'aiohttp' -disqus_developer = True diff --git a/docs/faq.rst b/docs/faq.rst new file mode 100644 index 0000000..04b14ea --- /dev/null +++ b/docs/faq.rst @@ -0,0 +1,83 @@ +Frequently Asked Questions +========================== +.. contents:: + :local: + +Are there any plans for @app.route decorator like in Flask? +----------------------------------------------------------- +There are couple issues here: + +* This adds huge problem name "configuration as side effect of importing". +* Route matching is order specific, it is very hard to maintain import order. +* In semi large application better to have routes table defined in one place. + +For this reason feature will not be implemented. But if you really want to +use decorators just derive from web.Application and add desired method. + + +How to create route that catches urls with given prefix? +--------------------------------------------------------- +Try something like:: + + app.router.add_route('*', '/path/to/{tail:.+}', sink_handler) + +Where first argument, star, means catch any possible method +(*GET, POST, OPTIONS*, etc), second matching ``url`` with desired prefix, +third - handler. + + +Where to put my database connection so handlers can access it? +-------------------------------------------------------------- + +:class:`aiohttp.web.Application` object supports :class:`dict` +interface, and right place to store your database connections or any +other resource you want to share between handlers. Take a look on +following example:: + + async def go(request): + db = request.app['db'] + cursor = await db.cursor() + await cursor.execute('SELECT 42') + # ... + return web.Response(status=200, text='ok') + + + async def init_app(loop): + app = Application(loop=loop) + db = await create_connection(user='user', password='123') + app['db'] = db + app.router.add_route('GET', '/', go) + return app + + +Why the minimal supported version is Python 3.4.1 +-------------------------------------------------- + +As of aiohttp **v0.18.0** we dropped support for Python 3.3 up to +3.4.1. The main reason for that is the :meth:`object.__del__` method, +which is fully working since Python 3.4.1 and we need it for proper +resource closing. + +The last Python 3.3, 3.4.0 compatible version of aiohttp is +**v0.17.4**. + +This should not be an issue for most aiohttp users (for example Ubuntu +14.04.3 LTS provides python upgraded to 3.4.3), however libraries +depending on aiohttp should consider this and either freeze aiohttp +version or drop Python 3.3 support as well. + + +How a middleware may store a data for using by web-handler later? +----------------------------------------------------------------- + +:class:`aiohttp.web.Request` supports :class:`dict` interface as well +as :class:`aiohttp.web.Application`. + +Just put data inside *request*:: + + async def handler(request): + request['unique_key'] = data + +See https://github.com/aio-libs/aiohttp_session code for inspiration, +``aiohttp_session.get_session(request)`` method uses ``SESSION_KEY`` +for saving request specific session info. diff --git a/docs/glossary.rst b/docs/glossary.rst index 1ad0524..8a4c2de 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -41,15 +41,33 @@ keep-alive A technique for communicating between HTTP client and server - when connection is not closed after sending response but keeped + when connection is not closed after sending response but kept open for sending next request through the same socket. It makes communication faster by getting rid of connection establishment for every request. + resource + + A concept reflects the HTTP **path**, every resource corresponds + to *URI*. + + May have an unique name. + + Contains :term:`route`\'s for different HTTP methods. + + route + + A part of :term:`resource`, resource's *path* coupled with HTTP method. + web-handler An endpoint that returns HTTP response. + websocket + + A protocol providing full-duplex communication channels over a + single TCP connection. The WebSocket protocol was standardized + by the IETF as :rfc:`6455` .. disqus:: diff --git a/docs/gunicorn.rst b/docs/gunicorn.rst index cd808ff..01e5dc4 100644 --- a/docs/gunicorn.rst +++ b/docs/gunicorn.rst @@ -37,9 +37,7 @@ Application ----------- Lets write a simple application, which we will save to file. We'll -name this file *my_app_module.py*: - -.. code-block:: python +name this file *my_app_module.py*:: from aiohttp import web @@ -86,6 +84,12 @@ aiohttp.wsgi applications:: Gunicorn is now running and ready to serve requests to your app's worker processes. +.. note:: + + If you want to use an alternative asyncio event loop + `uvloop <https://github.com/MagicStack/uvloop>`_, you can use the + ``aiohttp.worker.GunicornUVLoopWebWorker`` worker class. + More information ---------------- diff --git a/docs/index.rst b/docs/index.rst index 1df5728..7536e6e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -41,21 +41,20 @@ Client example:: import asyncio import aiohttp - async def fetch_page(client, url): - async with client.get(url) as response: - assert response.status == 200 - return await response.read() + async def fetch_page(session, url): + with aiohttp.Timeout(10): + async with session.get(url) as response: + assert response.status == 200 + return await response.read() loop = asyncio.get_event_loop() - client = aiohttp.ClientSession(loop=loop) - content = loop.run_until_complete( - fetch_page(client, 'http://python.org')) - print(content) - client.close() + with aiohttp.ClientSession(loop=loop) as session: + content = loop.run_until_complete( + fetch_page(session, 'http://python.org')) + print(content) Server example:: - import asyncio from aiohttp import web async def handle(request): @@ -63,21 +62,10 @@ Server example:: text = "Hello, " + name return web.Response(body=text.encode('utf-8')) - async def init(loop): - app = web.Application(loop=loop) - app.router.add_route('GET', '/{name}', handle) - - srv = await loop.create_server(app.make_handler(), - '127.0.0.1', 8080) - print("Server started at http://127.0.0.1:8080") - return srv + app = web.Application() + app.router.add_route('GET', '/{name}', handle) - loop = asyncio.get_event_loop() - loop.run_until_complete(init(loop)) - try: - loop.run_forever() - except KeyboardInterrupt: - pass + web.run_app(app) .. note:: @@ -98,6 +86,12 @@ Server example:: ret = yield from f() +Tutorial +-------- + +:ref:`Polls tutorial <aiohttp-tutorial>` + + Source code ----------- @@ -154,17 +148,20 @@ Contents client client_reference + tutorial web web_reference + abc server - multidict multipart api logging + testing gunicorn + faq + new_router contributing changes - Python 3.3 support <python33> glossary Indices and tables diff --git a/docs/logging.rst b/docs/logging.rst index 25047f2..54ce9f2 100644 --- a/docs/logging.rst +++ b/docs/logging.rst @@ -11,6 +11,7 @@ library activity. We have the following loggers enumerated by names: +- ``'aiohttp.access'`` - ``'aiohttp.client'`` - ``'aiohttp.internal'`` - ``'aiohttp.server'`` @@ -27,16 +28,24 @@ configuring whole loggers in your application. Access logs ----------- -Access log is enabled by specifying *access_log* parameter -(:class:`logging.Logger` instance) on -:meth:`aiohttp.web.Application.make_handler` call. +Access log by default is switched on and uses ``'aiohttp.access'`` +logger name. -Optional *access_log_format* parameter may be used for specifying log -format (see below). +The log may be controlled by :meth:`aiohttp.web.Application.make_handler` call. + +Pass *access_log* parameter with value of :class:`logging.Logger` +instance to override default logger. + +.. note:: -.. note:: Access log is disabled by default. + Use ``app.make_handler(access_log=None)`` for disabling access logs. + + +Other parameter called *access_log_format* may be used for specifying log +format (see below). -Format specification. +Format specification +^^^^^^^^^^^^^^^^^^^^ The library provides custom micro-language to specifying info about request and response: @@ -86,7 +95,7 @@ Error logs *aiohttp.web* uses logger named ``'aiohttp.server'`` to store errors given on web requests handling. -The log is always enabled. +The log is enabled by default. To use different logger name please specify *logger* parameter (:class:`logging.Logger` instance) on performing diff --git a/docs/multidict.rst b/docs/multidict.rst deleted file mode 100644 index c0e3fea..0000000 --- a/docs/multidict.rst +++ /dev/null @@ -1,375 +0,0 @@ -.. _aiohttp-multidict: - -============ - Multidicts -============ - -.. module:: aiohttp - - -*HTTP Headers* and *URL query string* require specific data structure: -*multidict*. It behaves mostly like a :class:`dict` but it can have -several *values* for the same *key*. - -:mod:`aiohttp` has four multidict classes: -:class:`MultiDict`, :class:`MultiDictProxy`, :class:`CIMultiDict` -and :class:`CIMultiDictProxy`. - -Immutable proxies (:class:`MultiDictProxy` and -:class:`CIMultiDictProxy`) provide a dynamic view on the -proxied multidict, the view reflects the multidict changes. They -implement the :class:`~collections.abc.Mapping` interface. - -Regular mutable (:class:`MultiDict` and :class:`CIMultiDict`) classes -implement :class:`~collections.abc.MutableMapping` and allows to change -their own content. - - -*Case insensitive* (:class:`CIMultiDict` and -:class:`CIMultiDictProxy`) ones assumes the *keys* are case -insensitive, e.g.:: - - >>> dct = CIMultiDict(a='val') - >>> 'A' in dct - True - >>> dct['A'] - 'val' - -*Keys* should be a :class:`str`. - - -MultiDict -========= - -.. class:: MultiDict(**kwargs) - MultiDict(mapping, **kwargs) - MultiDict(iterable, **kwargs) - - Creates a mutable multidict instance. - - Accepted parameters are the same as for :class:`dict`. - - If the same key appears several times it will be added, e.g.:: - - >>> d = MultiDict[('a', 1), ('b', 2), ('a', 3)]) - >>> d - <MultiDict {'a': 1, 'b': 2, 'a': 3}> - - .. method:: len(d) - - Return the number of items in multidict *d*. - - .. method:: d[key] - - Return the **first** item of *d* with key *key*. - - Raises a :exc:`KeyError` if key is not in the multidict. - - .. method:: d[key] = value - - Set ``d[key]`` to *value*. - - Replace all items where key is equal to *key* with single item - ``(key, value)``. - - .. method:: del d[key] - - Remove all items where key is equal to *key* from *d*. - Raises a :exc:`KeyError` if *key* is not in the map. - - .. method:: key in d - - Return ``True`` if d has a key *key*, else ``False``. - - .. method:: key not in d - - Equivalent to ``not (key in d)`` - - .. method:: iter(d) - - Return an iterator over the keys of the dictionary. - This is a shortcut for ``iter(d.keys())``. - - .. method:: add(key, value) - - Append ``(key, value)`` pair to the dictionary. - - .. method:: clear() - - Remove all items from the dictionary. - - .. method:: copy() - - Return a shallow copy of the dictionary. - - .. method:: extend([other]) - - Extend the dictionary with the key/value pairs from *other*, - overwriting existing keys. - Return ``None``. - - :meth:`extend` accepts either another dictionary object or an - iterable of key/value pairs (as tuples or other iterables of - length two). If keyword arguments are specified, the dictionary - is then extended with those key/value pairs: - ``d.extend(red=1, blue=2)``. - - .. method:: getone(key[, default]) - - Return the **first** value for *key* if *key* is in the - dictionary, else *default*. - - Raises :exc:`KeyError` if *default* is not given and *key* is not found. - - ``d[key]`` is equivalent to ``d.getone(key)``. - - .. method:: getall(key[, default]) - - Return a list of all values for *key* if *key* is in the - dictionary, else *default*. - - Raises :exc:`KeyError` if *default* is not given and *key* is not found. - - .. method:: get(key[, default]) - - Return the **first** value for *key* if *key* is in the - dictionary, else *default*. - - If *default* is not given, it defaults to ``None``, so that this - method never raises a :exc:`KeyError`. - - ``d.get(key)`` is equivalent to ``d.getone(key, None)``. - - .. method:: keys() - - Return a new view of the dictionary's keys. - - View contains all keys, possibly with duplicates. - - .. method:: items() - - Return a new view of the dictionary's items (``(key, value)`` pairs). - - View contains all items, multiple items can have the same key. - - .. method:: values() - - Return a new view of the dictionary's values. - - View contains all values. - - .. method:: pop(key[, default]) - - If *key* is in the dictionary, remove it and return its the - **first** value, else return *default*. - - If *default* is not given and *key* is not in the dictionary, a - :exc:`KeyError` is raised. - - - .. method:: popitem() - - Remove and return an arbitrary ``(key, value)`` pair from the dictionary. - - :meth:`popitem` is useful to destructively iterate over a - dictionary, as often used in set algorithms. - - If the dictionary is empty, calling :meth:`popitem` raises a - :exc:`KeyError`. - - .. method:: setdefault(key[, default]) - - If *key* is in the dictionary, return its the **first** value. - If not, insert *key* with a value of *default* and return *default*. - *default* defaults to ``None``. - - .. method:: update([other]) - - Update the dictionary with the key/value pairs from *other*, - overwriting existing keys. - - Return ``None``. - - :meth:`update` accepts either another dictionary object or an - iterable of key/value pairs (as tuples or other iterables - of length two). If keyword arguments are specified, the - dictionary is then updated with those key/value pairs: - ``d.update(red=1, blue=2)``. - - .. seealso:: - - :class:`MultiDictProxy` can be used to create a read-only view - of a :class:`MultiDict`. - - -CIMultiDict -=========== - - -.. class:: CIMultiDict(**kwargs) - CIMultiDict(mapping, **kwargs) - CIMultiDict(iterable, **kwargs) - - Create a case insensitive multidict instance. - - The behavior is the same as of :class:`MultiDict` but key - comparisons are case insensitive, e.g.:: - - >>> dct = CIMultiDict(a='val') - >>> 'A' in dct - True - >>> dct['A'] - 'val' - >>> dct['a'] - 'val' - >>> dct['b'] = 'new val' - >>> dct['B'] - 'new val' - - The class is inherited from :class:`MultiDict`. - - .. seealso:: - - :class:`CIMultiDictProxy` can be used to create a read-only view - of a :class:`CIMultiDict`. - - -MultiDictProxy -============== - -.. class:: MultiDictProxy(multidict) - - Create an immutable multidict proxy. - - It provides a dynamic view on - the multidict’s entries, which means that when the multidict changes, - the view reflects these changes. - - Raises :exc:`TypeError` is *multidict* is not :class:`MultiDict` instance. - - .. method:: len(d) - - Return number of items in multidict *d*. - - .. method:: d[key] - - Return the **first** item of *d* with key *key*. - - Raises a :exc:`KeyError` if key is not in the multidict. - - .. method:: key in d - - Return ``True`` if d has a key *key*, else ``False``. - - .. method:: key not in d - - Equivalent to ``not (key in d)`` - - .. method:: iter(d) - - Return an iterator over the keys of the dictionary. - This is a shortcut for ``iter(d.keys())``. - - .. method:: copy() - - Return a shallow copy of the underlying multidict. - - .. method:: getone(key[, default]) - - Return the **first** value for *key* if *key* is in the - dictionary, else *default*. - - Raises :exc:`KeyError` if *default* is not given and *key* is not found. - - ``d[key]`` is equivalent to ``d.getone(key)``. - - .. method:: getall(key[, default]) - - Return a list of all values for *key* if *key* is in the - dictionary, else *default*. - - Raises :exc:`KeyError` if *default* is not given and *key* is not found. - - .. method:: get(key[, default]) - - Return the **first** value for *key* if *key* is in the - dictionary, else *default*. - - If *default* is not given, it defaults to ``None``, so that this - method never raises a :exc:`KeyError`. - - ``d.get(key)`` is equivalent to ``d.getone(key, None)``. - - .. method:: keys() - - Return a new view of the dictionary's keys. - - View contains all keys, possibly with duplicates. - - .. method:: items() - - Return a new view of the dictionary's items (``(key, value)`` pairs). - - View contains all items, multiple items can have the same key. - - .. method:: values() - - Return a new view of the dictionary's values. - - View contains all values. - -CIMultiDictProxy -================ - -.. class:: CIMultiDictProxy(multidict) - - Case insensitive version of :class:`MultiDictProxy`. - - Raises :exc:`TypeError` is *multidict* is not :class:`CIMultiDict` instance. - - The class is inherited from :class:`MultiDict`. - - -upstr -===== - -:class:`CIMultiDict` accepts :class:`str` as *key* argument for dict -lookups but converts it to upper case internally. - -For more effective processing it should know if the *key* is already upper cased. - -To skip the :meth:`~str.upper()` call you may want to create upper cased strings by -hand, e.g:: - - >>> key = upstr('Key') - >>> key - 'KEY' - >>> mdict = CIMultiDict(key='value') - >>> key in mdict - True - >>> mdict[key] - 'value' - -For performance you should create :class:`upstr` strings once and -store them globally, like :mod:`aiohttp.hdrs` does. - -.. class:: upstr(object='') - upstr(bytes_or_buffer[, encoding[, errors]]) - - Create a new **upper cased** string object from the given - *object*. If *encoding* or *errors* are specified, then the - object must expose a data buffer that will be decoded using the - given encoding and error handler. - - Otherwise, returns the result of ``object.__str__()`` (if defined) - or ``repr(object)``. - - *encoding* defaults to ``sys.getdefaultencoding()``. - - *errors* defaults to ``'strict'``. - - The class is inherited from :class:`str` and has all regular - string methods. - - -.. disqus:: diff --git a/docs/multipart.rst b/docs/multipart.rst index b0aba32..8fbc55a 100644 --- a/docs/multipart.rst +++ b/docs/multipart.rst @@ -51,7 +51,7 @@ returned - that's the signal to break the loop:: Both :class:`BodyPartReader` and :class:`MultipartReader` provides access to body part headers: this allows you to filter parts by their attributes:: - if part.headers[aiohttp.hdrs.CONTENT-TYPE] == 'application/json': + if part.headers[aiohttp.hdrs.CONTENT_TYPE] == 'application/json': metadata = await part.json() continue diff --git a/docs/new_router.rst b/docs/new_router.rst new file mode 100644 index 0000000..deea6c2 --- /dev/null +++ b/docs/new_router.rst @@ -0,0 +1,84 @@ +.. _aiohttp-router-refactoring-021: + +Router refactoring in 0.21 +========================== + +Rationale +--------- + +First generation (v1) of router mapped ``(method, path)`` pair to +:term:`web-handler`. Mapping is named **route**. Routes used to have +unique names if any. + +The main mistake with the design is coupling the **route** to +``(method, path)`` pair while really URL construction operates with +**resources** (**location** is a synonym). HTTP method is not part of URI +but applied on sending HTTP request only. + +Having different **route names** for the same path is confusing. Moreover +**named routes** constructed for the same path should have unique +non overlapping names which is cumbersome is certain situations. + +From other side sometimes it's desirable to bind several HTTP methods +to the same web handler. For *v1* router it can be solved by passing '*' +as HTTP method. Class based views require '*' method also usually. + + +Implementation +-------------- + +The change introduces **resource** as first class citizen:: + + resource = router.add_resource('/path/{to}', name='name') + +*Resource* has a **path** (dynamic or constant) and optional **name**. + +The name is **unique** in router context. + +*Resource* has **routes**. + +*Route* corresponds to *HTTP method* and :term:`web-handler` for the method:: + + route = resource.add_route('GET', handler) + +User still may use wildcard for accepting all HTTP methods (maybe we +will add something like ``resource.add_wildcard(handler)`` later). + +Since **names** belongs to **resources** now ``app.router['name']`` +returns a **resource** instance instead of :class:`aiohttp.web.Route`. + +**resource** has ``.url()`` method, so +``app.router['name'].url(parts={'a': 'b'}, query={'arg': 'param'})`` +still works as usual. + + +The change allows to rewrite static file handling and implement nested +applications as well. + +Decoupling of *HTTP location* and *HTTP method* makes life easier. + +Backward compatibility +---------------------- + +The refactoring is 99% compatible with previous implementation. + +99% means all example and the most of current code works without +modifications but we have subtle API backward incompatibles. + +``app.router['name']`` returns a :class:`aiohttp.web.BaseResource` +instance instead of :class:`aiohttp.web.Route` but resource has the +same ``resource.url(...)`` most useful method, so end user should feel no +difference. + +``route.match(...)`` is **not** supported anymore, use +:meth:`aiohttp.web.AbstractResource.resolve` instead. + +``app.router.add_route(method, path, handler, name='name')`` now is just +shortcut for:: + + resource = app.router.add_resource(path, name=name) + route = resource.add_route(method, handler) + return route + +``app.router.register_route(...)`` is still supported, it creates +:class:`aiohttp.web.ResourceAdapter` for every call (but it's deprecated now). diff --git a/docs/python33.rst b/docs/python33.rst deleted file mode 100644 index 295d4da..0000000 --- a/docs/python33.rst +++ /dev/null @@ -1,15 +0,0 @@ -Python 3.3, ..., 3.4.1 support -============================== - -As of aiohttp **v0.18.0** we dropped support for Python 3.3 up to -3.4.1. The main reason for that is the :meth:`object.__del__` method, -which is fully working since Python 3.4.1 and we need it for proper -resource closing. - -The last Python 3.3, 3.4.0 compatible version of aiohttp is -**v0.17.4**. - -This should not be an issue for most aiohttp users (for example Ubuntu -14.04.3 LTS provides python upgraded to 3.4.3), however libraries -depending on aiohttp should consider this and either freeze aiohttp -version or drop Python 3.3 support as well. diff --git a/docs/server.rst b/docs/server.rst index bef3b52..c415a6e 100644 --- a/docs/server.rst +++ b/docs/server.rst @@ -16,9 +16,7 @@ Run a basic server Start implementing the basic server by inheriting the :class:`ServerHttpProtocol` object. Your class should implement the only method :meth:`ServerHttpProtocol.handle_request` -which must be a coroutine to handle requests asynchronously - - .. code-block:: python +which must be a coroutine to handle requests asynchronously:: from urllib.parse import urlparse, parse_qsl @@ -43,9 +41,7 @@ which must be a coroutine to handle requests asynchronously The next step is to create a loop and register your handler within a server. :exc:`KeyboardInterrupt` exception handling is necessary so you can stop -your server with Ctrl+C at any time. - - .. code-block:: python +your server with Ctrl+C at any time:: if __name__ == '__main__': loop = asyncio.get_event_loop() @@ -73,10 +69,7 @@ Handling GET params Currently aiohttp does not provide automatic parsing of incoming GET params. However aiohttp does provide a nice -:class:`MulitiDict` wrapper for already parsed params. - - - .. code-block:: python +:class:`MulitiDict` wrapper for already parsed params:: from urllib.parse import urlparse, parse_qsl @@ -92,14 +85,25 @@ params. However aiohttp does provide a nice print("Passed in GET", get_params) +Sending pre-compressed data +--------------------------- + +To include data in the response that is already compressed, do not call +`enable_compression`. Instead, set the `Content-Encoding` header explicitly:: + + @asyncio.coroutine + def handler(request): + headers = {'Content-Encoding': 'gzip'} + deflated_data = zlib.compress(b'mydata') + return web.Response(body=deflated_data, headers=headers) + + Handling POST data ------------------ POST data is accessed through the ``payload.read()`` generator method. If you have form data in the request body, you can parse it in the same way as -GET params. - - .. code-block:: python +GET params:: from urllib.parse import urlparse, parse_qsl @@ -119,9 +123,7 @@ SSL --- To use asyncio's SSL support, just pass an SSLContext object to the -:meth:`asyncio.BaseEventLoop.create_server` method of the loop. - - .. code-block:: python +:meth:`asyncio.BaseEventLoop.create_server` method of the loop:: import ssl diff --git a/docs/testing.rst b/docs/testing.rst new file mode 100644 index 0000000..2e2cbce --- /dev/null +++ b/docs/testing.rst @@ -0,0 +1,212 @@ +.. _aiohttp-testing: + +Testing +======= + +.. currentmodule:: aiohttp.test_utils + +Testing aiohttp web servers +--------------------------- + +aiohttp provides plugin for pytest_ making writing web +server tests extremely easy, it also provides +:ref:`test framework agnostic utilities <framework-agnostic-utilities>` for +testing with other frameworks such as :ref:`unittest <unittest-example>`. + +Pytest example +~~~~~~~~~~~~~~ + +The :data:`test_client` fixture available from :data:`aiohttp.pytest_plugin` +allows you to create a client to make requests to test your app. + +A simple would be:: + + from aiohttp import web + pytest_plugins = 'aiohttp.pytest_plugin' + + async def hello(request): + return web.Response(body=b'Hello, world') + + def create_app(loop): + app = web.Application(loop=loop) + app.router.add_route('GET', '/', hello) + return app + + async def test_hello(test_client): + client = await test_client(create_app) + resp = await client.get('/') + assert resp.status == 200 + text = await resp.text() + assert 'Hello, world' in text + + +It also provides access to the app instance allowing tests to check the state +of the app. Tests can be made even more succinct with a fixture to create an +app test client:: + + import pytest + from aiohttp import web + pytest_plugins = 'aiohttp.pytest_plugin' + + + async def previous(request): + if request.method == 'POST': + request.app['value'] = (await request.post())['value'] + return web.Response(body=b'thanks for the data') + return web.Response(body='value: {}'.format(request.app['value']).encode()) + + def create_app(loop): + app = web.Application(loop=loop) + app.router.add_route('*', '/', previous) + return app + + @pytest.fixture + def cli(loop, test_client): + return loop.run_until_complete(test_client(create_app)) + + async def test_set_value(cli): + resp = await cli.post('/', data={'value': 'foo'}) + assert resp.status == 200 + assert await resp.text() == 'thanks for the data' + assert cli.app['value'] == 'foo' + + async def test_get_value(cli): + cli.app['value'] = 'bar' + resp = await cli.get('/') + assert resp.status == 200 + assert await resp.text() == 'value: bar' + + +.. _framework-agnostic-utilities: + +Framework agnostic utilities +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +High level test creation:: + + from aiohttp.test_utils import TestClient, loop_context + from aiohttp import request + + # loop_context is provided as a utility. You can use any + # asyncio.BaseEventLoop class in it's place. + with loop_context() as loop: + app = _create_example_app(loop) + with TestClient(app) as client: + + async def test_get_route(): + nonlocal client + resp = await client.get("/") + assert resp.status == 200 + text = await resp.text() + assert "Hello, world" in text + + loop.run_until_complete(test_get_route()) + + +If it's preferred to handle the creation / teardown on a more granular +basis, the TestClient object can be used directly:: + + from aiohttp.test_utils import TestClient + + with loop_context() as loop: + app = _create_example_app(loop) + client = TestClient(app) + root = "http://127.0.0.1:{}".format(port) + + async def test_get_route(): + resp = await client.get("/") + assert resp.status == 200 + text = await resp.text() + assert "Hello, world" in text + + loop.run_until_complete(test_get_route()) + # the server is cleaned up implicitly, through + # the deletion of the TestServer. + del client + + +A full list of the utilities provided can be found at the +:data:`api reference <aiohttp.test_utils>` + +The Test Client +~~~~~~~~~~~~~~~ + +The :data:`aiohttp.test_utils.TestClient` creates an asyncio server +for the web.Application object, as well as a ClientSession to perform +requests. In addition, TestClient provides proxy methods to the client for +common operations such as ws_connect, get, post, etc. + +Please see the full api at the +:class:`TestClass api reference <aiohttp.test_utils.TestClient>` + + +.. _unittest-example: + +Unittest example +~~~~~~~~~~~~~~~~ + +To test applications with the standard library's unittest or unittest-based +functionality, the AioHTTPTestCase is provided:: + + from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop + from aiohttp import web + + class MyAppTestCase(AioHTTPTestCase): + + def get_app(self, loop): + """ + override the get_app method to return + your application. + """ + # it's important to use the loop passed here. + return web.Application(loop=loop) + + # the unittest_run_loop decorator can be used in tandem with + # the AioHTTPTestCase to simplify running + # tests that are asynchronous + @unittest_run_loop + async def test_example(self): + request = await self.client.request("GET", "/") + assert request.status == 200 + text = await request.text() + assert "Hello, world" in text + + # a vanilla example + def test_example(self): + async def test_get_route(): + url = root + "/" + resp = await self.client.request("GET", url, loop=loop) + assert resp.status == 200 + text = await resp.text() + assert "Hello, world" in text + + self.loop.run_until_complete(test_get_route()) + +Faking request object +--------------------- + +aiohttp provides test utility for creating fake `web.Request` objects: +:data:`aiohttp.test_utils.make_mocked_request`, it could be useful in case of +simple unit tests, like handler tests, or simulate error conditions that +hard to reproduce on real server. :: + + from aiohttp import web + + def handler(request): + assert request.headers.get('token') == 'x' + return web.Response(body=b'data') + + def test_handler() + req = make_request('get', 'http://python.org/', headers={'token': 'x') + resp = header(req) + assert resp.body == b'data' + + +aiohttp.test_utils +------------------ + +.. _pytest: http://pytest.org/latest/ +.. automodule:: aiohttp.test_utils + :members: TestClient, AioHTTPTestCase, run_loop, loop_context, setup_test_loop, teardown_test_loop make_mocked_request + :undoc-members: + :show-inheritance: diff --git a/docs/tutorial.rst b/docs/tutorial.rst new file mode 100644 index 0000000..a81df4d --- /dev/null +++ b/docs/tutorial.rst @@ -0,0 +1,237 @@ +.. _aiohttp-tutorial: + +Tutorial +======== + +Are you going to learn *aiohttp* but don't where to start? We have +example for you. Polls application is a great example for getting +started with aiohttp. + +If you want the full source code in advance or for comparison, check out +the `demo source`_. + +.. _demo source: + https://github.com/KeepSafe/aiohttp/tree/master/demos/polls/ + + +.. _aiohttp-tutorial-setup: + +Setup your environment +---------------------- + +First of all check you python version:: + + $ python -V + Python 3.5.0 + +Tutorial requires Python 3.5.0 or newer. + +We’ll assume that you have already installed *aiohttp* library. You can check +aiohttp is installed and which version by running the following +command:: + + $ python -c 'import aiohttp; print(aiohttp.__version__)' + 0.22.0 + +Project structure looks very similar to other python based web projects:: + + . + ├── README.rst + └── polls + ├── Makefile + ├── README.rst + ├── aiohttpdemo_polls + │ ├── __init__.py + │ ├── __main__.py + │ ├── db.py + │ ├── main.py + │ ├── routes.py + │ ├── templates + │ ├── utils.py + │ └── views.py + ├── config + │ └── polls.yaml + ├── images + │ └── example.png + ├── setup.py + ├── sql + │ ├── create_tables.sql + │ ├── install.sh + │ └── sample_data.sql + └── static + └── style.css + + +.. _aiohttp-tutorial-introduction: + +Getting started with aiohttp first app +-------------------------------------- + +This tutorial based on Django polls tutorial. + + +.. _aiohttp-tutorial-database: + +Database +-------- + +Setup +^^^^^ + +In this tutorial we use latest PostgreSQL database. You can install +PostgreSQL using this instruction http://www.postgresql.org/download/ + +Database schema +^^^^^^^^^^^^^^^ + +We use SQLAlchemy for describe database schema. +For this tutorial we can use two simple models ``question`` and ``choice``:: + + import sqlalchemy as sa + + meta = sa.MetaData() + + question = sa.Table( + 'question', meta, + sa.Column('id', sa.Integer, nullable=False), + sa.Column('question_text', sa.String(200), nullable=False), + sa.Column('pub_date', sa.Date, nullable=False), + + # Indexes # + sa.PrimaryKeyConstraint('id', name='question_id_pkey')) + + choice = sa.Table( + 'choice', meta, + sa.Column('id', sa.Integer, nullable=False), + sa.Column('question_id', sa.Integer, nullable=False), + sa.Column('choice_text', sa.String(200), nullable=False), + sa.Column('votes', sa.Integer, server_default="0", nullable=False), + + # Indexes # + sa.PrimaryKeyConstraint('id', name='choice_id_pkey'), + sa.ForeignKeyConstraint(['question_id'], [question.c.id], + name='choice_question_id_fkey', + ondelete='CASCADE'), + ) + + + +You can find below description of tables in database: + +First table is question: + ++---------------+ +| question | ++===============+ +| id | ++---------------+ +| question_text | ++---------------+ +| pub_date | ++---------------+ + +and second table is choice table: + ++---------------+ +| choice | ++===============+ +| id | ++---------------+ +| choice_text | ++---------------+ +| votes | ++---------------+ +| question_id | ++---------------+ + + +.. _aiohttp-tutorial-views: + +Views +----- + +Let's start from first views. Open polls/aiohttpdemo_polls/views.py and put +next Python code inside file (``polls/aiohttpdemo_polls/views.py``):: + + from aiohttp import web + + + class SiteHandler: + async def index(self, request): + return web.Response(text='Hello Aiohttp!') + +This is the simplest view possible in Aiohttp. Now we should add ``index`` view +to ``polls/aiohttpdemo_polls/routes.py``:: + + def setup_routes(app, handler, project_root): + add_route = app.router.add_route + add_route('GET', '/', handler.index) + +Now if we open browser we can see:: + + $ curl -X GET localhost:8080 + Hello Aiohttp! + + +.. _aiohttp-tutorial-templates: + +Templates +--------- + +Let's add more useful views:: + + @aiohttp_jinja2.template('detail.html') + async def poll(self, request): + question_id = request.match_info['question_id'] + try: + question, choices = await db.get_question(self.postgres, + question_id) + except db.RecordNotFound as e: + raise web.HTTPNotFound(text=str(e)) + return { + 'question': question, + 'choices': choices + } + +Templates are very convinient way forweb page writing. We return a +dict with page content, ``aiohttp_jinja2.template`` decorator +processes it by jinja2 template renderer. + +For setting up template engine we need to install ``aiohttp_jinja2`` +library first:: + + $ pip install aiohttp_jinja2 + +After installing we need to setup the library:: + + import aiohttp_jinja2 + import jinja2 + + aiohttp_jinja2.setup( + app, loader=jinja2.PackageLoader('aiohttpdemo_polls', 'templates')) + + +In the tutorial we push template files under +``polls/aiohttpdemo_polls/templates`` folder. + + +.. _aiohttp-tutorial-static: + +Static files +------------ + +Any web site has static files: images, JavaScript sources, CSS files etc. + +The best way to handle static in production is setting up reverse +proxy like NGINX or using CDN services. + +But for development handling static files by aiohttp server is very convinient. + +Fortunatelly it can be done easy by single call:: + + app.router.add_static('/static/', + path=str(project_root / 'static'), + name='static') + + +where ``project_root`` is the path to root folder. diff --git a/docs/web.rst b/docs/web.rst index 022c49f..70078fa 100644 --- a/docs/web.rst +++ b/docs/web.rst @@ -5,9 +5,6 @@ HTTP Server Usage .. currentmodule:: aiohttp.web -.. versionchanged:: 0.12 - :mod:`aiohttp.web` was deeply refactored making it backwards incompatible. - Run a Simple Web Server ----------------------- @@ -19,7 +16,6 @@ A request handler is a :ref:`coroutine <coroutine>` or regular function that accepts a :class:`Request` instance as its only parameter and returns a :class:`Response` instance:: - import asyncio from aiohttp import web async def hello(request): @@ -32,26 +28,37 @@ particular *HTTP method* and *path*:: app = web.Application() app.router.add_route('GET', '/', hello) -After that, create a server and run the *asyncio loop* as usual:: +After that, run the application by :func:`run_app` call:: - loop = asyncio.get_event_loop() - handler = app.make_handler() - f = loop.create_server(handler, '0.0.0.0', 8080) - srv = loop.run_until_complete(f) - print('serving on', srv.sockets[0].getsockname()) - try: - loop.run_forever() - except KeyboardInterrupt: - pass - finally: - srv.close() - loop.run_until_complete(srv.wait_closed()) - loop.run_until_complete(handler.finish_connections(1.0)) - loop.run_until_complete(app.finish()) - loop.close() + web.run_app(app) That's it. Now, head over to ``http://localhost:8080/`` to see the results. +.. seealso:: + + :ref:`aiohttp-web-graceful-shutdown` section explains what :func:`run_app` + does and how to implement complex server initialization/finalization + from scratch. + + +.. _aiohttp-web-cli: + +Command Line Interface (CLI) +---------------------------- +:mod:`aiohttp.web` implements a basic CLI for quickly serving an +:class:`Application` in *development* over TCP/IP:: + + $ python -m aiohttp.web -H localhost -P 8080 package.module:init_func + +``package.module:init_func`` should be an importable :term:`callable` that +accepts a list of any non-parsed command-line arguments and returns an +:class:`Application` instance after setting it up:: + + def init_function(argv): + app = web.Application() + app.router.add_route("GET", "/", index_handler) + return app + .. _aiohttp-web-handler: @@ -88,17 +95,43 @@ allowing a handler to serve incoming requests on a *path* having **any** The *HTTP method* can be queried later in the request handler using the :attr:`Request.method` property. -.. versionadded:: 0.15.2 - Support for wildcard *HTTP method* routes. + +.. _aiohttp-web-resource-and-route: + +Resources and Routes +-------------------- + +Internally *router* is a list of *resources*. + +Resource is an entry in *route table* which corresponds to requested URL. + +Resource in turn has at least one *route*. + +Route corresponds to handling *HTTP method* by calling *web handler*. + +:meth:`UrlDispatcher.add_route` is just a shortcut for pair of +:meth:`UrlDispatcher.add_resource` and :meth:`Resource.add_route`:: + + resource = app.router.add_resource(path, name=name) + route = resource.add_route(method, handler) + return route + +.. seealso:: + + :ref:`aiohttp-router-refactoring-021` for more details + +.. versionadded:: 0.21.0 + + Introduce resources. .. _aiohttp-web-variable-handler: -Variable Routes -^^^^^^^^^^^^^^^ +Variable Resources +^^^^^^^^^^^^^^^^^^ -Handlers can also be attached to routes with *variable paths*. For instance, -a route with the path ``'/a/{name}/c'`` would match all incoming requests with +Resource may have *variable path* also. For instance, a resource with +the path ``'/a/{name}/c'`` would match all incoming requests with paths such as ``'/a/b/c'``, ``'/a/1/c'``, and ``'/a/etc/c'``. A variable *part* is specified in the form ``{identifier}``, where the @@ -111,38 +144,35 @@ that *part*. This is done by looking up the ``identifier`` in the return web.Response( text="Hello, {}".format(request.match_info['name'])) - app.router.add_route('GET', '/{name}', variable_handler) + resource = app.router.add_resource('/{name}') + resource.add_route('GET', variable_handler) By default, each *part* matches the regular expression ``[^{}/]+``. You can also specify a custom regex in the form ``{identifier:regex}``:: - app.router.add_route('GET', r'/{name:\d+}', variable_handler) - -.. versionadded:: 0.13 - Support for custom regexs in variable routes. + resource = app.router.add_resource(r'/{name:\d+}') .. _aiohttp-web-named-routes: -Reverse URL Constructing using Named Routes -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Reverse URL Constructing using Named Resources +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Routes can also be given a *name*:: - app.router.add_route('GET', '/root', handler, name='root') + resource = app.router.add_resource('/root', name='root') -Which can then be used to access and build a *URL* for that route later (e.g. +Which can then be used to access and build a *URL* for that resource later (e.g. in a :ref:`request handler <aiohttp-web-handler>`):: - >>> request.app.router['root'].url(query={"a": "b", "c": "d"}) + >>> request.app.router.named_resources()['root'].url(query={"a": "b", "c": "d"}) '/root?a=b&c=d' A more interesting example is building *URLs* for :ref:`variable -routes <aiohttp-web-variable-handler>`:: +resources <aiohttp-web-variable-handler>`:: - app.router.add_route('GET', r'/{user}/info', - variable_handler, name='user-info') + app.router.add_resource(r'/{user}/info', name='user-info') In this case you can also pass in the *parts* of the route:: @@ -217,20 +247,20 @@ registered in application's router:: Example will process GET and POST requests for */path/to* but raise *405 Method not allowed* exception for unimplemented HTTP methods. -Route Views -^^^^^^^^^^^ +Resource Views +^^^^^^^^^^^^^^ -*All* registered routes in a router can be viewed using the -:meth:`UrlDispatcher.routes` method:: +*All* registered resources in a router can be viewed using the +:meth:`UrlDispatcher.resources` method:: - for route in app.router.routes(): - print(route) + for resource in app.router.resources(): + print(resource) -Similarly, a *subset* of the routes that were registered with a *name* can be -viewed using the :meth:`UrlDispatcher.named_routes` method:: +Similarly, a *subset* of the resources that were registered with a *name* can be +viewed using the :meth:`UrlDispatcher.named_resources` method:: - for name, route in app.router.named_routes().items(): - print(name, route) + for name, resource in app.router.named_resources().items(): + print(name, resource) @@ -240,6 +270,11 @@ viewed using the :meth:`UrlDispatcher.named_routes` method:: .. versionadded:: 0.19 :meth:`UrlDispatcher.named_routes` +.. deprecated:: 0.21 + + Use :meth:`UrlDispatcher.named_resources` / + :meth:`UrlDispatcher.resources` instead of + :meth:`UrlDispatcher.named_routes` / :meth:`UrlDispatcher.routes`. Custom Routing Criteria ----------------------- @@ -251,9 +286,7 @@ Although :class:`UrlDispatcher` does not support any extra criteria, routing based on custom conditions can be accomplished by implementing a second layer of routing in your application. -The following example shows custom routing based on the *HTTP Accept* header: - -.. code-block:: python +The following example shows custom routing based on the *HTTP Accept* header:: class AcceptChooser: @@ -284,6 +317,25 @@ The following example shows custom routing based on the *HTTP Accept* header: chooser.reg_acceptor('application/xml', handle_xml) +Static file handling +-------------------- + +The best way to handle static files (images, JavaScripts, CSS files +etc.) is using `Reverse Proxy`_ like `nginx`_ or `CDN`_ services. + +.. _Reverse Proxy: https://en.wikipedia.org/wiki/Reverse_proxy +.. _nginx: https://nginx.org/ +.. _CDN: https://en.wikipedia.org/wiki/Content_delivery_network + +But for development it's very convenient to handle static files by +aiohttp server itself. + +To do it just register a new static route by +:meth:`UrlDispatcher.add_static` call:: + + app.router.add_static('/prefix', path_to_static_folder) + + Template Rendering ------------------ @@ -356,34 +408,44 @@ third-party library, :mod:`aiohttp_session`, that adds *session* support:: *Expect* Header --------------- -.. versionadded:: 0.15 - -By default, :mod:`aiohttp.web` simply responds with an ``HTTP/1.1 100 Continue`` -status code whenever a requests contains an *Expect* header; however, it is -possible to specify a custom *Expect* handler on a per route basis. +:mod:`aiohttp.web` supports *Expect* header. By default it sends +``HTTP/1.1 100 Continue`` line to client, or raises +:exc:`HTTPExpectationFailed` if header value is not equal to +"100-continue". It is possible to specify custom *Expect* header +handler on per route basis. This handler gets called if *Expect* +header exist in request after receiving all headers and before +processing application's :ref:`aiohttp-web-middlewares` and +route handler. Handler can return *None*, in that case the request +processing continues as usual. If handler returns an instance of class +:class:`StreamResponse`, *request handler* uses it as response. Also +handler can raise a subclass of :exc:`HTTPException`. In this case all +further processing will not happen and client will receive appropriate +http response. -This handler gets called **after** receiving the request headers, but **before** -calling application :ref:`middlewares <aiohttp-web-middlewares>`, or route -:ref:`handlers <aiohttp-web-handler>`. +.. note:: + A server that does not understand or is unable to comply with any of the + expectation values in the Expect field of a request MUST respond with + appropriate error status. The server MUST respond with a 417 + (Expectation Failed) status if any of the expectations cannot be met or, + if there are other problems with the request, some other 4xx status. -The *Expect* handler *may* return *None*, in which case the request processing -continues as usual. If the handler returns an instance of -class :class:`StreamResponse`, the *request handler* uses it as the response. + http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20 If all checks pass, the custom handler *must* write a *HTTP/1.1 100 Continue* status code before returning. The following example shows how to setup a custom handler for the *Expect* -header: - -.. code-block:: python +header:: async def check_auth(request): if request.version != aiohttp.HttpVersion11: return + if request.headers.get('EXPECT') != '100-continue': + raise HTTPExpectationFailed(text="Unknown Expect: %s" % expect) + if request.headers.get('AUTHORIZATION') is None: - return web.HTTPForbidden() + raise HTTPForbidden() request.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n") @@ -419,9 +481,7 @@ accepts a MP3 file: Then, in the :ref:`request handler <aiohttp-web-handler>` you can access the file input field as a :class:`FileField` instance. :class:`FileField` is simply -a container for the file as well as some of its metadata: - -.. code-block:: python +a container for the file as well as some of its metadata:: async def store_mp3_handler(request): @@ -447,15 +507,11 @@ a container for the file as well as some of its metadata: WebSockets ---------- -.. versionadded:: 0.14 - :mod:`aiohttp.web` supports *WebSockets* out-of-the-box. To setup a *WebSocket*, create a :class:`WebSocketResponse` in a :ref:`request handler <aiohttp-web-handler>` and then use it to communicate -with the peer: - -.. code-block:: python +with the peer:: async def websocket_handler(request): @@ -477,8 +533,10 @@ with the peer: return ws Reading from the *WebSocket* (``await ws.receive()``) **must only** be -done inside the request handler coroutine; however, writing -(``ws.send_str(...)``) to the *WebSocket* may be delegated to other coroutines. +done inside the request handler *task*; however, writing +(``ws.send_str(...)``) to the *WebSocket* may be delegated to other tasks. +*aiohttp.web* creates an implicit :class:`asyncio.Task` for handling every +incoming request. .. note:: @@ -565,6 +623,7 @@ HTTP Exception hierarchy chart:: * 428 - HTTPPreconditionRequired * 429 - HTTPTooManyRequests * 431 - HTTPRequestHeaderFieldsTooLarge + * 451 - HTTPUnavailableForLegalReasons HTTPServerError * 500 - HTTPInternalServerError * 501 - HTTPNotImplemented @@ -648,8 +707,6 @@ Otherwise, something based on your company name/url would be satisfactory (i.e Middlewares ----------- -.. versionadded:: 0.13 - :mod:`aiohttp.web` provides a powerful mechanism for customizing :ref:`request handlers<aiohttp-web-handler>` via *middlewares*. @@ -694,10 +751,36 @@ if user has no permissions to access the underlying resource. They may also render errors raised by the handler, perform some pre- or post-processing like handling *CORS* and so on. -.. versionchanged:: 0.14 - Middlewares accept route exceptions (:exc:`HTTPNotFound` and - :exc:`HTTPMethodNotAllowed`). +Example +^^^^^^^ + +A common use of middlewares is to implement custom error pages. The following +example will render 404 errors using a JSON response, as might be appropriate +a JSON REST service:: + + import json + from aiohttp import web + + def json_error(message): + return web.Response( + body=json.dumps({'error': message}).encode('utf-8'), + content_type='application/json') + + async def error_middleware(app, handler): + async def middleware_handler(request): + try: + response = await handler(request) + if response.status == 404: + return json_error(response.message) + return response + except web.HTTPException as ex: + if ex.status == 404: + return json_error(ex.reason) + raise + return middleware_handler + + app = web.Application(middlewares=[error_middleware]) .. _aiohttp-web-signals: @@ -737,6 +820,8 @@ parameters. signals, but simply reusing existing ones, you will not be affected. +.. _aiohttp-web-flow-control: + Flow control ------------ @@ -781,6 +866,87 @@ To manual mode switch :meth:`~StreamResponse.set_tcp_cork` and be helpful for better streaming control for example. +.. _aiohttp-web-graceful-shutdown: + +Graceful shutdown +------------------ + +Stopping *aiohttp web server* by just closing all connections is not +always satisfactory. + +The problem is: if application supports :term:`websocket`\s or *data +streaming* it most likely has open connections at server +shutdown time. + +The *library* has no knowledge how to close them gracefully but +developer can help by registering :attr:`Application.on_shutdown` +signal handler and call the signal on *web server* closing. + +Developer should keep a list of opened connections +(:class:`Application` is a good candidate). + +The following :term:`websocket` snippet shows an example for websocket +handler:: + + app = web.Application() + app['websockets'] = [] + + async def websocket_handler(request): + ws = web.WebSocketResponse() + await ws.prepare(request) + + request.app['websockets'].append(ws) + try: + async for msg in ws: + ... + finally: + request.app['websockets'].remove(ws) + + return ws + +Signal handler may looks like:: + + async def on_shutdown(app): + for ws in app['websockets']: + await ws.close(code=999, message='Server shutdown') + + app.on_shutdown.append(on_shutdown) + +Proper finalization procedure has three steps: + + 1. Stop accepting new client connections by + :meth:`asyncio.Server.close` and + :meth:`asyncio.Server.wait_closed` calls. + + 2. Fire :meth:`Application.shutdown` event. + + 3. Close accepted connections from clients by + :meth:`RequestHandlerFactory.finish_connections` call with + reasonable small delay. + + 4. Call registered application finalizers by :meth:`Application.cleanup`. + +The following code snippet performs proper application start, run and +finalizing. It's pretty close to :func:`run_app` utility function:: + + loop = asyncio.get_event_loop() + handler = app.make_handler() + f = loop.create_server(handler, '0.0.0.0', 8080) + srv = loop.run_until_complete(f) + print('serving on', srv.sockets[0].getsockname()) + try: + loop.run_forever() + except KeyboardInterrupt: + pass + finally: + srv.close() + loop.run_until_complete(srv.wait_closed()) + loop.run_until_complete(app.shutdown()) + loop.run_until_complete(handler.finish_connections(60.0)) + loop.run_until_complete(app.cleanup()) + loop.close() + + CORS support ------------ diff --git a/docs/web_reference.rst b/docs/web_reference.rst index ab45ea7..79368a9 100644 --- a/docs/web_reference.rst +++ b/docs/web_reference.rst @@ -118,6 +118,11 @@ like one using :meth:`Request.copy`. Read-only :class:`~aiohttp.CIMultiDictProxy` property. + .. attribute:: raw_headers + + HTTP headers of response as unconverted bytes, a sequence of + ``(key, value)`` pairs. + .. attribute:: keep_alive ``True`` if keep-alive connection enabled by HTTP client and @@ -166,8 +171,6 @@ like one using :meth:`Request.copy`. Read-only property. - .. versionadded:: 0.15 - .. attribute:: has_body Return ``True`` if request has *HTTP BODY*, ``False`` otherwise. @@ -176,17 +179,6 @@ like one using :meth:`Request.copy`. .. versionadded:: 0.16 - .. attribute:: payload - - A :class:`~aiohttp.streams.FlowControlStreamReader` instance, - input stream for reading request's *BODY*. - - Read-only property. - - .. deprecated:: 0.15 - - Use :attr:`~Request.content` instead. - .. attribute:: content_type Read-only property with *content* part of *Content-Type* header. @@ -246,18 +238,18 @@ like one using :meth:`Request.copy`. The method **does** store read data internally, subsequent :meth:`~Request.text` call will return the same value. - .. coroutinemethod:: json(*, loader=json.loads) + .. coroutinemethod:: json(*, loads=json.loads) Read request body decoded as *json*. The method is just a boilerplate :ref:`coroutine <coroutine>` implemented as:: - async def json(self, *, loader=json.loads): + async def json(self, *, loads=json.loads): body = await self.text() - return loader(body) + return loads(body) - :param callable loader: any :term:`callable` that accepts + :param callable loads: any :term:`callable` that accepts :class:`str` and returns :class:`dict` with parsed JSON (:func:`json.loads` by default). @@ -402,8 +394,6 @@ StreamResponse ``False`` by default. - .. versionadded:: 0.14 - .. seealso:: :meth:`enable_compression` .. method:: enable_compression(force=None) @@ -416,8 +406,6 @@ StreamResponse *Accept-Encoding* is not checked if *force* is set to a :class:`ContentCoding`. - .. versionadded:: 0.14 - .. seealso:: :attr:`compression` .. attribute:: chunked @@ -426,8 +414,6 @@ StreamResponse Can be enabled by :meth:`enable_chunked_encoding` call. - .. versionadded:: 0.14 - .. seealso:: :attr:`enable_chunked_encoding` .. method:: enable_chunked_encoding @@ -436,8 +422,6 @@ StreamResponse disable it back. With enabled :attr:`chunked` encoding each `write()` operation encoded in separate chunk. - .. versionadded:: 0.14 - .. warning:: chunked encoding can be enabled for ``HTTP/1.1`` only. Setting up both :attr:`content_length` and chunked @@ -510,10 +494,6 @@ StreamResponse specification the cookie conforms. (Optional, *version=1* by default) - .. versionchanged:: 0.14.3 - - Default value for *path* changed from ``None`` to ``'/'``. - .. method:: del_cookie(name, *, path='/', domain=None) Deletes cookie. @@ -524,10 +504,6 @@ StreamResponse :param str path: optional cookie path, ``'/'`` by default - .. versionchanged:: 0.14.3 - - Default value for *path* changed from ``None`` to ``'/'``. - .. attribute:: content_length *Content-Length* for outgoing response. @@ -640,8 +616,6 @@ StreamResponse written to the transport, and the coroutine does not yield-from between calls to :meth:`write`. - .. versionadded:: 0.14 - .. coroutinemethod:: write_eof() A :ref:`coroutine<coroutine>` *may* be called as a mark of the @@ -889,7 +863,7 @@ WebSocketResponse .. coroutinemethod:: receive_str() - A :ref:`coroutine<coroutine>` that calls :meth:`receive_mgs` but + A :ref:`coroutine<coroutine>` that calls :meth:`receive` but also asserts the message type is :const:`~aiohttp.websocket.MSG_TEXT`. @@ -899,7 +873,7 @@ WebSocketResponse .. coroutinemethod:: receive_bytes() - A :ref:`coroutine<coroutine>` that calls :meth:`receive_mgs` but + A :ref:`coroutine<coroutine>` that calls :meth:`receive` but also asserts the message type is :const:`~aiohttp.websocket.MSG_BINARY`. @@ -907,8 +881,24 @@ WebSocketResponse :raise TypeError: if message is :const:`~aiohttp.websocket.MSG_TEXT`. + .. coroutinemethod:: receive_json(*, loads=json.loads) + + A :ref:`coroutine<coroutine>` that calls :meth:`receive`, asserts the + message type is :const:`~aiohttp.websocket.MSG_TEXT`, and loads the JSON + string to a Python dict. + + :param callable loads: any :term:`callable` that accepts + :class:`str` and returns :class:`dict` + with parsed JSON (:func:`json.loads` by + default). + + :return dict: loaded JSON content + + :raise TypeError: if message is :const:`~aiohttp.websocket.MSG_BINARY`. + :raise ValueError: if message is not valid JSON. + + .. versionadded:: 0.22 -.. versionadded:: 0.14 .. seealso:: :ref:`WebSockets handling<aiohttp-web-websockets>` @@ -984,8 +974,6 @@ duplicated like one using :meth:`Application.copy`. :param middlewares: :class:`list` of middleware factories, see :ref:`aiohttp-web-middlewares` for details. - .. versionadded:: 0.13 - .. attribute:: router Read-only property that returns *router instance*. @@ -1007,9 +995,44 @@ duplicated like one using :meth:`Application.copy`. Signal handlers should have the following signature:: - async def handler(request, response): + async def on_prepare(request, response): + pass + + .. attribute:: on_shutdown + + A :class:`~aiohttp.signals.Signal` that is fired on application shutdown. + + Subscribers may use the signal for gracefully closing long running + connections, e.g. websockets and data streaming. + + Signal handlers should have the following signature:: + + async def on_shutdown(app): + pass + + It's up to end user to figure out which :term:`web-handler`\s + are still alive and how to finish them properly. + + We suggest keeping a list of long running handlers in + :class:`Application` dictionary. + + .. seealso:: :ref:`aiohttp-web-graceful-shutdown` and :attr:`on_cleanup`. + + .. attribute:: on_cleanup + + A :class:`~aiohttp.signals.Signal` that is fired on application cleanup. + + Subscribers may use the signal for gracefully closing + connections to database server etc. + + Signal handlers should have the following signature:: + + async def on_cleanup(app): pass + .. seealso:: :ref:`aiohttp-web-graceful-shutdown` and :attr:`on_shutdown`. + + .. method:: make_handler(**kwargs) Creates HTTP protocol factory for handling requests. @@ -1030,17 +1053,27 @@ duplicated like one using :meth:`Application.copy`. await loop.create_server(app.make_handler(), '0.0.0.0', 8080) - .. coroutinemethod:: finish() + .. coroutinemethod:: shutdown() + + A :ref:`coroutine<coroutine>` that should be called on + server stopping but before :meth:`finish()`. + + The purpose of the method is calling :attr:`on_shutdown` signal + handlers. + + .. coroutinemethod:: cleanup() - A :ref:`coroutine<coroutine>` that should be called after - server stopping. + A :ref:`coroutine<coroutine>` that should be called on + server stopping but after :meth:`shutdown`. - This method executes functions registered by - :meth:`register_on_finish` in LIFO order. + The purpose of the method is calling :attr:`on_cleanup` signal + handlers. - If callback raises an exception, the error will be stored by - :meth:`~asyncio.BaseEventLoop.call_exception_handler` with keys: - *message*, *exception*, *application*. + .. coroutinemethod:: finish() + + A deprecated alias for :meth:`cleanup`. + + .. deprecated:: 0.21 .. method:: register_on_finish(self, func, *args, **kwargs): @@ -1055,6 +1088,10 @@ duplicated like one using :meth:`Application.copy`. *func* may be either regular function or :ref:`coroutine<coroutine>`, :meth:`finish` will un-yield (`await`) the later. + .. deprecated:: 0.21 + + Use :attr:`on_cleanup` instead: ``app.on_cleanup.append(handler)``. + .. note:: Application object has :attr:`router` attribute but has no @@ -1078,11 +1115,11 @@ RequestHandlerFactory RequestHandlerFactory is responsible for creating HTTP protocol objects that can handle HTTP connections. - .. attribute:: connections + .. attribute:: RequestHandlerFactory.connections List of all currently opened connections. - .. method:: finish_connections(timeout) + .. coroutinemethod:: RequestHandlerFactory.finish_connections(timeout) A :ref:`coroutine<coroutine>` that should be called to close all opened connections. @@ -1120,6 +1157,21 @@ Router is any object that implements :class:`AbstractRouter` interface. .. seealso:: :ref:`Route classes <aiohttp-web-route>` + .. method:: add_resource(path, *, name=None) + + Append a :term:`resource` to the end of route table. + + *path* may be either *constant* string like ``'/a/b/c'`` or + *variable rule* like ``'/a/{var}'`` (see + :ref:`handling variable pathes<aiohttp-web-variable-handler>`) + + :param str path: resource path spec. + + :param str name: optional resource name. + + :return: created resource instance (:class:`PlainResource` or + :class:`DynamicResource`). + .. method:: add_route(method, path, handler, *, \ name=None, expect_handler=None) @@ -1180,8 +1232,8 @@ Router is any object that implements :class:`AbstractRouter` interface. :param str prefix: URL path prefix for handled static files - :param str path: path to the folder in file system that contains - handled static files. + :param path: path to the folder in file system that contains + handled static files, :class:`str` or :class:`pathlib.Path`. :param str name: optional route name. @@ -1213,8 +1265,8 @@ Router is any object that implements :class:`AbstractRouter` interface. The method never raises exception, but returns :class:`AbstractMatchInfo` instance with: - 1. :attr:`~AbstractMatchInfo.route` assigned to - :class:`SystemRoute` instance + 1. :attr:`~AbstractMatchInfo.http_exception` assigned to + :exc:`HTTPException` instance. 2. :attr:`~AbstractMatchInfo.handler` which raises :exc:`HTTPNotFound` or :exc:`HTTPMethodNotAllowed` on handler's execution if there is no registered route for *request*. @@ -1227,114 +1279,290 @@ Router is any object that implements :class:`AbstractRouter` interface. .. note:: The method uses :attr:`Request.raw_path` for pattern matching against registered routes. - .. versionchanged:: 0.14 + .. method:: resources() - The method don't raise :exc:`HTTPNotFound` and - :exc:`HTTPMethodNotAllowed` anymore. - - .. method:: routes() - - The method returns a *view* for *all* registered routes. + The method returns a *view* for *all* registered resources. The view is an object that allows to: 1. Get size of the router table:: - len(app.router.routes()) + len(app.router.resources()) + + 2. Iterate over registered resources:: - 2. Iterate over registered routes:: + for resource in app.router.resources(): + print(resource) - for route in app.router.routes(): - print(route) + 3. Make a check if the resources is registered in the router table:: - 3. Make a check if the route is registered in the router table:: + route in app.router.resources() - route in app.router.routes() + .. versionadded:: 0.21.1 + + .. method:: routes() + + The method returns a *view* for *all* registered routes. .. versionadded:: 0.18 - .. method:: named_routes() + .. method:: named_resources() Returns a :obj:`dict`-like :class:`types.MappingProxyType` *view* over - *all* named routes. + *all* named **resources**. + + The view maps every named resources's **name** to the + :class:`BaseResource` instance. It supports the usual + :obj:`dict`-like operations, except for any mutable operations + (i.e. it's **read-only**):: - The view maps every named route's :attr:`Route.name` attribute to the - :class:`Route`. It supports the usual :obj:`dict`-like operations, except - for any mutable operations (i.e. it's **read-only**):: + len(app.router.named_resources()) - len(app.router.named_routes()) + for name, resource in app.router.named_resources().items(): + print(name, resource) - for name, route in app.router.named_routes().items(): - print(name, route) + "name" in app.router.named_resources() - "route_name" in app.router.named_routes() + app.router.named_resources()["name"] - app.router.named_routes()["route_name"] + .. versionadded:: 0.21 + + .. method:: named_routes() + + An alias for :meth:`named_resources` starting from aiohttp 0.21. .. versionadded:: 0.19 + .. versionchanged:: 0.21 + + The method is an alias for :meth:`named_resources`, so it + iterates over resources instead of routes. + + .. deprecated:: 0.21 + + Please use named **resources** instead of named **routes**. + + Several routes which belongs to the same resource shares the + resource name. + + +.. _aiohttp-web-resource: + +Resource +^^^^^^^^ + +Default router :class:`UrlDispatcher` operates with :term:`resource`\s. + +Resource is an item in *routing table* which has a *path*, an optional +unique *name* and at least one :term:`route`. + +:term:`web-handler` lookup is performed in the following way: + +1. Router iterates over *resources* one-by-one. +2. If *resource* matches to requested URL the resource iterates over + own *routes*. +3. If route matches to requested HTTP method (or ``'*'`` wildcard) the + route's handler is used as found :term:`web-handler`. The lookup is + finished. +4. Otherwise router tries next resource from the *routing table*. +5. If the end of *routing table* is reached and no *resource* / + *route* pair found the *router* returns special :class:`AbstractMatchInfo` + instance with :attr:`AbstractMatchInfo.http_exception` is not ``None`` + but :exc:`HTTPException` with either *HTTP 404 Not Found* or + *HTTP 405 Method Not Allowed* status code. + Registered :attr:`AbstractMatchInfo.handler` raises this exception on call. + +User should never instantiate resource classes but give it by +:meth:`UrlDispatcher.add_resource` call. + +After that he may add a :term:`route` by calling :meth:`Resource.add_route`. + +:meth:`UrlDispatcher.add_route` is just shortcut for:: + + router.add_resource(path).add_route(method, handler) + +Resource with a *name* is called *named resource*. +The main purpose of *named resource* is constructing URL by route name for +passing it into *template engine* for example:: + + url = app.router['resource_name'].url(query={'a': 1, 'b': 2}) + +Resource classes hierarchy:: + + AbstractResource + Resource + PlainResource + DynamicResource + ResourceAdapter + + +.. class:: AbstractResource + + A base class for all resources. + + Inherited from :class:`collections.abc.Sized` and + :class:`collections.abc.Iterable`. + + ``len(resource)`` returns amount of :term:`route`\s belongs to the resource, + ``for route in resource`` allows to iterate over these routes. + + .. attribute:: name + + Read-only *name* of resource or ``None``. + + .. coroutinemethod:: resolve(method, path) + + Resolve resource by finding appropriate :term:`web-handler` for + ``(method, path)`` combination. + + :param str method: requested HTTP method. + :param str path: *path* part of request. + + :return: (*match_info*, *allowed_methods*) pair. + + *allowed_methods* is a :class:`set` or HTTP methods accepted by + resource. + + *match_info* is either :class:`UrlMappingMatchInfo` if + request is resolved or ``None`` if no :term:`route` is + found. + + .. method:: url(**kwargs) + + Construct an URL for route with additional params. + + **kwargs** depends on a list accepted by inherited resource + class parameters. + + :return: :class:`str` -- resulting URL. + + +.. class:: Resource + + A base class for new-style resources, inherits :class:`AbstractResource`. + + + .. method:: add_route(method, handler, *, expect_handler=None) + + Add a :term:`web-handler` to resource. + + :param str method: HTTP method for route. Should be one of + ``'GET'``, ``'POST'``, ``'PUT'``, + ``'DELETE'``, ``'PATCH'``, ``'HEAD'``, + ``'OPTIONS'`` or ``'*'`` for any method. + + The parameter is case-insensitive, e.g. you + can push ``'get'`` as well as ``'GET'``. + + The method should be unique for resource. + + :param callable handler: route handler. + + :param coroutine expect_handler: optional *expect* header handler. + + :returns: new :class:`ResourceRoute` instance. + + +.. class:: PlainResource + + A new-style resource, inherited from :class:`Resource`. + + The class corresponds to resources with plain-text matching, + ``'/path/to'`` for example. + + +.. class:: DynamicResource + + A new-style resource, inherited from :class:`Resource`. + + The class corresponds to resources with + :ref:`variable <aiohttp-web-variable-handler>` matching, + e.g. ``'/path/{to}/{param}'`` etc. + + +.. class:: ResourceAdapter + + An adapter for old-style routes. + + The adapter is used by ``router.register_route()`` call, the method + is deprecated and will be removed eventually. + .. _aiohttp-web-route: Route ^^^^^ -Default router :class:`UrlDispatcher` operates with *routes*. +Route has *HTTP method* (wildcard ``'*'`` is an option), +:term:`web-handler` and optional *expect handler*. -User should not instantiate route classes by hand but can give *named -route instance* by ``router[name]`` if he have added route by -:meth:`UrlDispatcher.add_route` or :meth:`UrlDispatcher.add_static` -calls with non-empty *name* parameter. +Every route belong to some resource. -The main usage of *named routes* is constructing URL by route name for -passing it into *template engine* for example:: +Route classes hierarchy:: - url = app.router['route_name'].url(query={'a': 1, 'b': 2}) + AbstractRoute + ResourceRoute + Route + PlainRoute + DynamicRoute + StaticRoute -There are three concrete route classes: +:class:`ResourceRoute` is the route used for new-style resources, +:class:`PlainRoute` and :class:`DynamicRoute` serves old-style +routes kept for backward compatibility only. -* :class:`PlainRoute` for urls without :ref:`variable - pathes<aiohttp-web-variable-handler>` spec. +:class:`StaticRoute` is used for static file serving +(:meth:`UrlDispatcher.add_static`). Don't rely on the route +implementation too hard, static file handling most likely will be +rewritten eventually. -* :class:`DynamicRoute` for urls with :ref:`variable - pathes<aiohttp-web-variable-handler>` spec. +So the only non-deprecated and not internal route is +:class:`ResourceRoute` only. -* :class:`StaticRoute` for static file handlers. - -.. class:: Route +.. class:: AbstractRoute Base class for routes served by :class:`UrlDispatcher`. .. attribute:: method - HTTP method handled by the route, e.g. *GET*, *POST* etc. + HTTP method handled by the route, e.g. *GET*, *POST* etc. .. attribute:: handler - :ref:`handler<aiohttp-web-handler>` that processes the route. + :ref:`handler<aiohttp-web-handler>` that processes the route. .. attribute:: name - Name of the route. - - .. method:: match(path) + Name of the route, always equals to name of resource which owns the route. - Abstract method, accepts *URL path* and returns :class:`dict` with - parsed *path parts* for :class:`UrlMappingMatchInfo` or ``None`` if - the route cannot handle given *path*. + .. attribute:: resource - The method exists for internal usage, end user unlikely need to call it. + Resource instance which holds the route. .. method:: url(*, query=None, **kwargs) - Abstract method for constructing url handled by the route. + Abstract method for constructing url handled by the route. + + *query* is a mapping or list of *(name, value)* pairs for + specifying *query* part of url (parameter is processed by + :func:`~urllib.parse.urlencode`). - *query* is a mapping or list of *(name, value)* pairs for - specifying *query* part of url (parameter is processed by - :func:`~urllib.parse.urlencode`). + Other available parameters depends on concrete route class and + described in descendant classes. + + + .. note:: - Other available parameters depends on concrete route class and - described in descendant classes. + The method is kept for sake of backward compatibility, usually + you should use :meth:`Resource.url` instead. + + .. coroutinemethod:: handle_expect_header(request) + + ``100-continue`` handler. + +.. class:: ResourceRoute + + The route class for handling different HTTP methods for :class:`Resource`. .. class:: PlainRoute @@ -1342,10 +1570,10 @@ There are three concrete route classes: .. method:: url(*, parts, query=None) - Construct url, doesn't accepts extra parameters:: + Construct url, doesn't accepts extra parameters:: - >>> route.url(query={'d': 1, 'e': 2}) - '/a/b/c/?d=1&e=2' + >>> route.url(query={'d': 1, 'e': 2}) + '/a/b/c/?d=1&e=2' .. class:: DynamicRoute @@ -1354,11 +1582,11 @@ There are three concrete route classes: .. method:: url(*, parts, query=None) - Construct url with given *dynamic parts*:: + Construct url with given *dynamic parts*:: - >>> route.url(parts={'name1': 'b', 'name2': 'c'}, - query={'d': 1, 'e': 2}) - '/a/b/c/?d=1&e=2' + >>> route.url(parts={'name1': 'b', 'name2': 'c'}, + query={'d': 1, 'e': 2}) + '/a/b/c/?d=1&e=2' .. class:: StaticRoute @@ -1368,22 +1596,10 @@ There are three concrete route classes: .. method:: url(*, filename, query=None) - Construct url for given *filename*:: - - >>> route.url(filename='img/logo.png', query={'param': 1}) - '/path/to/static/img/logo.png?param=1' + Construct url for given *filename*:: - -.. class:: SystemRoute - - The route class for internal purposes. - - Now it has used for handling *404: Not Found* and *405: Method Not Allowed*. - - .. method:: url() - - Always raises :exc:`RuntimeError`, :class:`SystemRoute` should not - be used in url construction expressions. + >>> route.url(filename='img/logo.png', query={'param': 1}) + '/path/to/static/img/logo.png?param=1' MatchInfo @@ -1401,11 +1617,19 @@ In general the result may be any object derived from .. class:: UrlMappingMatchInfo Inherited from :class:`dict` and :class:`AbstractMatchInfo`. Dict - items are given from :meth:`Route.match` call return value. + items are filled by matching info and is :term:`resource`\-specific. + + .. attribute:: expect_handler + + A coroutine for handling ``100-continue``. + + .. attribute:: handler + + A coroutine for handling request. .. attribute:: route - :class:`Route` instance for url matching. + :class:`Route` instance for url matching. View @@ -1432,7 +1656,7 @@ View app.router.add_route('*', '/view', MyView) The view raises *405 Method Not allowed* - (:class:`HTTPMEthodNowAllowed`) if requested web verb is not + (:class:`HTTPMethodNowAllowed`) if requested web verb is not supported. :param request: instance of :class:`Request` that has initiated a view @@ -1478,6 +1702,49 @@ Utilities .. seealso:: :ref:`aiohttp-web-file-upload` +.. function:: run_app(app, *, host='0.0.0.0', port=None, loop=None, \ + shutdown_timeout=60.0, ssl_context=None, \ + print=print, backlog=128) + + An utility function for running an application, serving it until + keyboard interrupt and performing a + :ref:`aiohttp-web-graceful-shutdown`. + + Suitable as handy tool for scaffolding aiohttp based projects. + Perhaps production config will use more sophisticated runner but it + good enough at least at very beginning stage. + + The function uses *app.loop* as event loop to run. + + :param app: :class:`Application` instance to run + + :param str host: host for HTTP server, ``'0.0.0.0'`` by default + + :param int port: port for HTTP server. By default is ``8080`` for + plain text HTTP and ``8443`` for HTTP via SSL + (when *ssl_context* parameter is specified). + + :param int shutdown_timeout: a delay to wait for graceful server + shutdown before disconnecting all + open client sockets hard way. + + A system with properly + :ref:`aiohttp-web-graceful-shutdown` + implemented never waits for this + timeout but closes a server in a few + milliseconds. + + :param ssl_context: :class:`ssl.SSLContext` for HTTPS server, + ``None`` for HTTP connection. + + :param print: a callable compatible with :func:`print`. May be used + to override STDOUT output or suppress it. + + :param int backlog: the number of unaccepted connections that the + system will allow before refusing new + connections (``128`` by default). + + Constants --------- diff --git a/examples/basic_srv.py b/examples/basic_srv.py index bfd00e1..bb6a99d 100755 --- a/examples/basic_srv.py +++ b/examples/basic_srv.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Basic http server with minimal setup""" +"""Basic HTTP server with minimal setup""" import aiohttp import aiohttp.server @@ -37,7 +37,7 @@ if __name__ == '__main__': loop = asyncio.get_event_loop() f = loop.create_server( lambda: HttpRequestHandler(debug=True, keep_alive=75), - '0.0.0.0', '8080') + '0.0.0.0', 8080) srv = loop.run_until_complete(f) print('serving on', srv.sockets[0].getsockname()) try: diff --git a/examples/cli_app.py b/examples/cli_app.py new file mode 100644 index 0000000..a853e9c --- /dev/null +++ b/examples/cli_app.py @@ -0,0 +1,54 @@ +""" +Example of serving an Application using the `aiohttp.web` CLI. + +Serve this app using:: + + $ python -m aiohttp.web -H localhost -P 8080 --repeat 10 cli_app:init \ + > "Hello World" + +Here ``--repeat`` & ``"Hello World"`` are application specific command-line +arguments. `aiohttp.web` only parses & consumes the command-line arguments it +needs (i.e. ``-H``, ``-P`` & ``entry-func``) and passes on any additional +arguments to the `cli_app:init` function for processing. +""" + +from aiohttp.web import Application, Response +from argparse import ArgumentParser + + +def display_message(req): + args = req.app["args"] + text = "\n".join([args.message] * args.repeat) + return Response(text=text) + + +def init(argv): + arg_parser = ArgumentParser( + prog="aiohttp.web ...", description="Application CLI", add_help=False + ) + + # Positional argument + arg_parser.add_argument( + "message", + help="message to print" + ) + + # Optional argument + arg_parser.add_argument( + "--repeat", + help="number of times to repeat message", type=int, default="1" + ) + + # Avoid conflict with -h from `aiohttp.web` CLI parser + arg_parser.add_argument( + "--app-help", + help="show this message and exit", action="help" + ) + + args = arg_parser.parse_args(argv) + + app = Application() + app["args"] = args + app.router.add_route('GET', '/', display_message) + + return app diff --git a/examples/crawl.py b/examples/crawl.py index fef6428..5e5688f 100755 --- a/examples/crawl.py +++ b/examples/crawl.py @@ -19,19 +19,21 @@ class Crawler: self.busy = set() self.done = {} self.tasks = set() - self.sem = asyncio.Semaphore(maxtasks) + self.sem = asyncio.Semaphore(maxtasks, loop=loop) # connector stores cookies between requests and uses connection pool - self.connector = aiohttp.TCPConnector(share_cookies=True, loop=loop) + self.session = aiohttp.ClientSession(loop=loop) @asyncio.coroutine def run(self): - asyncio.Task(self.addurls([(self.rooturl, '')])) # Set initial work. - yield from asyncio.sleep(1) + t = asyncio.ensure_future(self.addurls([(self.rooturl, '')]), + loop=self.loop) + yield from asyncio.sleep(1, loop=self.loop) while self.busy: - yield from asyncio.sleep(1) + yield from asyncio.sleep(1, loop=self.loop) - self.connector.close() + yield from t + yield from self.session.close() self.loop.stop() @asyncio.coroutine @@ -45,7 +47,7 @@ class Crawler: url not in self.todo): self.todo.add(url) yield from self.sem.acquire() - task = asyncio.Task(self.process(url)) + task = asyncio.ensure_future(self.process(url), loop=self.loop) task.add_done_callback(lambda t: self.sem.release()) task.add_done_callback(self.tasks.remove) self.tasks.add(task) @@ -57,8 +59,7 @@ class Crawler: self.todo.remove(url) self.busy.add(url) try: - resp = yield from aiohttp.request( - 'get', url, connector=self.connector) + resp = yield from self.session.get(url) except Exception as exc: print('...', url, 'has error', repr(str(exc))) self.done[url] = False @@ -81,7 +82,7 @@ def main(): loop = asyncio.get_event_loop() c = Crawler(sys.argv[1], loop) - asyncio.Task(c.run()) + asyncio.ensure_future(c.run(), loop=loop) try: loop.add_signal_handler(signal.SIGINT, loop.stop) diff --git a/examples/curl.py b/examples/curl.py index b432001..486e41b 100755 --- a/examples/curl.py +++ b/examples/curl.py @@ -6,13 +6,15 @@ import asyncio def curl(url): - response = yield from aiohttp.request('GET', url) + session = aiohttp.ClientSession() + response = yield from session.request('GET', url) print(repr(response)) chunk = yield from response.content.read() print('Downloaded: %s' % len(chunk)) response.close() + session.close() if __name__ == '__main__': diff --git a/examples/mpsrv.py b/examples/mpsrv.py index 9e25620..737071b 100755 --- a/examples/mpsrv.py +++ b/examples/mpsrv.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Simple multiprocess http server written using an event loop.""" +"""Simple multiprocess HTTP server written using an event loop.""" import argparse import os @@ -12,7 +12,7 @@ import aiohttp import aiohttp.server from aiohttp import websocket -ARGS = argparse.ArgumentParser(description="Run simple http server.") +ARGS = argparse.ArgumentParser(description="Run simple HTTP server.") ARGS.add_argument( '--host', action="store", dest='host', default='127.0.0.1', help='Host name') diff --git a/examples/srv.py b/examples/srv.py index 768bf9e..1a38bc3 100755 --- a/examples/srv.py +++ b/examples/srv.py @@ -98,7 +98,7 @@ class HttpRequestHandler(aiohttp.server.ServerHttpProtocol): self.keep_alive(True) -ARGS = argparse.ArgumentParser(description="Run simple http server.") +ARGS = argparse.ArgumentParser(description="Run simple HTTP server.") ARGS.add_argument( '--host', action="store", dest='host', default='127.0.0.1', help='Host name') diff --git a/examples/tcp_protocol_parser.py b/examples/tcp_protocol_parser.py index c86c164..294cbf9 100755 --- a/examples/tcp_protocol_parser.py +++ b/examples/tcp_protocol_parser.py @@ -25,7 +25,7 @@ def my_protocol_parser(out, buf): more details in asyncio/parsers.py existing parsers: - * http protocol parsers asyncio/http/protocol.py + * HTTP protocol parsers asyncio/http/protocol.py * websocket parser asyncio/http/websocket.py """ while True: diff --git a/examples/wssrv.py b/examples/wssrv.py index ce2da42..6b4f850 100755 --- a/examples/wssrv.py +++ b/examples/wssrv.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Multiprocess WebSocket http chat example.""" +"""Multiprocess WebSocket HTTP chat example.""" import argparse import os @@ -12,7 +12,7 @@ import aiohttp import aiohttp.server from aiohttp import websocket -ARGS = argparse.ArgumentParser(description="Run simple http server.") +ARGS = argparse.ArgumentParser(description="Run simple HTTP server.") ARGS.add_argument( '--host', action="store", dest='host', default='127.0.0.1', help='Host name') @@ -5,7 +5,7 @@ zip_ok = false ignore = N801,N802,N803,E226 [egg_info] +tag_build = tag_date = 0 tag_svn_revision = 0 -tag_build = @@ -17,8 +17,7 @@ except ImportError: ext = '.pyx' if USE_CYTHON else '.c' -extensions = [Extension('aiohttp._multidict', ['aiohttp/_multidict' + ext]), - Extension('aiohttp._websocket', ['aiohttp/_websocket' + ext])] +extensions = [Extension('aiohttp._websocket', ['aiohttp/_websocket' + ext])] if USE_CYTHON: @@ -55,7 +54,7 @@ with codecs.open(os.path.join(os.path.abspath(os.path.dirname( raise RuntimeError('Unable to determine version.') -install_requires = ['chardet'] +install_requires = ['chardet', 'multidict>=1.1.0,<2'] if sys.version_info < (3, 4, 1): raise RuntimeError("aiohttp requires Python 3.4.1+") diff --git a/tests/conftest.py b/tests/conftest.py index 9d57383..e972162 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,15 +1,15 @@ import asyncio import aiohttp import collections -import gc import logging import pytest import re -import socket import sys import warnings - from aiohttp import web +from aiohttp.test_utils import ( + loop_context, unused_port +) class _AssertWarnsContext: @@ -147,32 +147,18 @@ def log(): yield _AssertLogsContext -@pytest.fixture -def unused_port(): - def f(): - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - return f +# add the unused_port and loop fixtures +pytest.fixture(unused_port) @pytest.yield_fixture -def loop(request): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(None) - - yield loop - - if not loop._closed: - loop.stop() - loop.run_forever() - loop.close() - gc.collect() - asyncio.set_event_loop(None) +def loop(): + with loop_context() as loop: + yield loop @pytest.yield_fixture -def create_server(loop, unused_port): +def create_server(loop): app = handler = srv = None @asyncio.coroutine @@ -222,6 +208,12 @@ class Client: url = self._url + path return self._session.post(url, **kwargs) + def delete(self, path, **kwargs): + while path.startswith('/'): + path = path[1:] + url = self._url + path + return self._session.delete(url) + def ws_connect(self, path, **kwargs): while path.startswith('/'): path = path[1:] diff --git a/tests/test_classbasedview.py b/tests/test_classbasedview.py index a0613e1..2dbce5a 100644 --- a/tests/test_classbasedview.py +++ b/tests/test_classbasedview.py @@ -34,11 +34,13 @@ def test_render_unknown_method(): @asyncio.coroutine def get(self): return web.Response(text='OK') + options = get request = mock.Mock() request.method = 'UNKNOWN' with pytest.raises(web.HTTPMethodNotAllowed) as ctx: yield from MyView(request) + assert ctx.value.headers['allow'] == 'GET,OPTIONS' assert ctx.value.status == 405 @@ -49,9 +51,11 @@ def test_render_unsupported_method(): @asyncio.coroutine def get(self): return web.Response(text='OK') + options = delete = get request = mock.Mock() request.method = 'POST' with pytest.raises(web.HTTPMethodNotAllowed) as ctx: yield from MyView(request) + assert ctx.value.headers['allow'] == 'DELETE,GET,OPTIONS' assert ctx.value.status == 405 diff --git a/tests/test_client_functional.py b/tests/test_client_functional.py index 51f4e4b..7638aa7 100644 --- a/tests/test_client_functional.py +++ b/tests/test_client_functional.py @@ -1,4 +1,4 @@ -"""Http client functional tests against aiohttp.web server""" +"""HTTP client functional tests against aiohttp.web server""" import aiohttp import asyncio @@ -7,6 +7,7 @@ import os import os.path import pytest import ssl +from unittest import mock from aiohttp import hdrs, web from aiohttp.errors import FingerprintMismatch @@ -315,7 +316,9 @@ def test_format_task_get(create_server, loop): client = aiohttp.ClientSession(loop=loop) task = loop.create_task(client.get(url)) assert "{}".format(task)[:18] == "<Task pending coro" - yield from task + resp = yield from task + resp.close() + client.close() @pytest.mark.run_loop @@ -336,6 +339,28 @@ def test_str_params(create_app_and_client): @pytest.mark.run_loop +def test_drop_params_on_redirect(create_app_and_client): + @asyncio.coroutine + def handler_redirect(request): + return web.Response(status=301, headers={'Location': '/ok?a=redirect'}) + + @asyncio.coroutine + def handler_ok(request): + assert request.query_string == 'a=redirect' + return web.Response(status=200) + + app, client = yield from create_app_and_client() + app.router.add_route('GET', '/ok', handler_ok) + app.router.add_route('GET', '/redirect', handler_redirect) + + resp = yield from client.get('/redirect', params={'a': 'initial'}) + try: + assert resp.status == 200 + finally: + yield from resp.release() + + +@pytest.mark.run_loop def test_history(create_app_and_client): @asyncio.coroutine def handler_redirect(request): @@ -354,7 +379,7 @@ def test_history(create_app_and_client): assert len(resp.history) == 0 assert resp.status == 200 finally: - resp.release() + yield from resp.release() resp_redirect = yield from client.get('/redirect') try: @@ -362,7 +387,7 @@ def test_history(create_app_and_client): assert resp_redirect.history[0].status == 301 assert resp_redirect.status == 200 finally: - resp_redirect.release() + yield from resp_redirect.release() @pytest.mark.run_loop @@ -399,3 +424,52 @@ def test_wait_for(create_app_and_client, loop): assert resp.status == 200 txt = yield from resp.text() assert txt == 'OK' + + +@pytest.mark.run_loop +def test_raw_headers(create_app_and_client, loop): + @asyncio.coroutine + def handler(request): + return web.Response() + + app, client = yield from create_app_and_client() + app.router.add_route('GET', '/', handler) + resp = yield from client.get('/') + assert resp.status == 200 + assert resp.raw_headers == ((b'CONTENT-LENGTH', b'0'), + (b'DATE', mock.ANY), + (b'SERVER', mock.ANY)) + resp.close() + + +@pytest.mark.run_loop +def test_http_request_with_version(create_app_and_client, loop, warning): + @asyncio.coroutine + def handler(request): + return web.Response() + + app, client = yield from create_app_and_client() + app.router.add_route('GET', '/', handler) + with warning(DeprecationWarning): + resp = yield from client.get('/', version=aiohttp.HttpVersion11) + assert resp.status == 200 + resp.close() + + +@pytest.mark.run_loop +def test_204_with_gzipped_content_encoding(create_app_and_client): + @asyncio.coroutine + def handler(request): + resp = web.StreamResponse(status=204) + resp.content_length = 0 + resp.content_type = 'application/json' + # resp.enable_compression(web.ContentCoding.gzip) + resp.headers['Content-Encoding'] = 'gzip' + yield from resp.prepare(request) + return resp + + app, client = yield from create_app_and_client() + app.router.add_route('DELETE', '/', handler) + resp = yield from client.delete('/') + assert resp.status == 204 + yield from resp.release() diff --git a/tests/test_client_functional_oldstyle.py b/tests/test_client_functional_oldstyle.py index 88f29c8..5806db2 100644 --- a/tests/test_client_functional_oldstyle.py +++ b/tests/test_client_functional_oldstyle.py @@ -1,4 +1,4 @@ -"""Http client functional tests.""" +"""HTTP client functional tests.""" import binascii import gc @@ -7,16 +7,26 @@ import os.path import json import http.cookies import asyncio +import socket import unittest from unittest import mock +from multidict import MultiDict + import aiohttp from aiohttp import client, helpers from aiohttp import test_utils -from aiohttp.multidict import MultiDict from aiohttp.multipart import MultipartWriter +def find_unused_port(): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(('127.0.0.1', 0)) + port = s.getsockname()[1] + s.close() + return port + + class TestHttpClientFunctional(unittest.TestCase): def setUp(self): @@ -625,7 +635,7 @@ class TestHttpClientFunctional(unittest.TestCase): with open(fname, 'rb') as f: data = f.read() - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) @asyncio.coroutine def stream(): @@ -809,29 +819,6 @@ class TestHttpClientFunctional(unittest.TestCase): m_log.warning.assert_called_with('Can not load response cookies: %s', mock.ANY) - @mock.patch('aiohttp.client_reqrep.client_logger') - def test_share_cookies(self, m_log): - with test_utils.run_server(self.loop, router=Functional) as httpd: - with self.assertWarns(DeprecationWarning): - conn = aiohttp.TCPConnector(share_cookies=True, loop=self.loop) - resp = self.loop.run_until_complete( - client.request('get', httpd.url('cookies'), - connector=conn, loop=self.loop)) - self.assertIn('SET-COOKIE', resp.headers) - self.assertEqual(resp.cookies['c1'].value, 'cookie1') - self.assertEqual(resp.cookies['c2'].value, 'cookie2') - self.assertEqual(conn.cookies, resp.cookies) - resp.close() - - resp2 = self.loop.run_until_complete( - client.request('get', httpd.url('method', 'get'), - connector=conn, loop=self.loop)) - self.assertNotIn('SET-COOKIE', resp2.headers) - data = self.loop.run_until_complete(resp2.json()) - self.assertEqual(data['headers']['Cookie'], - 'c1=cookie1; c2=cookie2') - resp2.close() - def test_chunked(self): with test_utils.run_server(self.loop, router=Functional) as httpd: r = self.loop.run_until_complete( @@ -853,43 +840,17 @@ class TestHttpClientFunctional(unittest.TestCase): r.close() def test_request_conn_error(self): - self.assertRaises( - aiohttp.ClientConnectionError, - self.loop.run_until_complete, - client.request('get', 'http://0.0.0.0:1', loop=self.loop)) + with self.assertRaises(aiohttp.ClientConnectionError): + self.loop.run_until_complete( + client.request('get', 'http://0.0.0.0:1', loop=self.loop)) def test_request_conn_closed(self): with test_utils.run_server(self.loop, router=Functional) as httpd: httpd['close'] = True - self.assertRaises( - aiohttp.ClientHttpProcessingError, - self.loop.run_until_complete, - client.request( - 'get', httpd.url('method', 'get'), loop=self.loop)) - - def test_keepalive(self): - from aiohttp import connector - with self.assertWarns(DeprecationWarning): - c = connector.TCPConnector(share_cookies=True, loop=self.loop) - - with test_utils.run_server(self.loop, router=Functional) as httpd: - r = self.loop.run_until_complete( - client.request('get', httpd.url('keepalive',), - connector=c, loop=self.loop)) - self.assertEqual(r.status, 200) - content = self.loop.run_until_complete(r.json()) - self.assertEqual(content['content'], 'requests=1') - r.close() - - r = self.loop.run_until_complete( - client.request('get', httpd.url('keepalive'), - connector=c, loop=self.loop)) - self.assertEqual(r.status, 200) - content = self.loop.run_until_complete(r.json()) - self.assertEqual(content['content'], 'requests=2') - r.close() - - c.close() + with self.assertRaises(aiohttp.ClientHttpProcessingError): + self.loop.run_until_complete( + client.request('get', httpd.url('method', 'get'), + loop=self.loop)) def test_session_close(self): conn = aiohttp.TCPConnector(loop=self.loop) @@ -914,31 +875,6 @@ class TestHttpClientFunctional(unittest.TestCase): conn.close() - @mock.patch('aiohttp.client_reqrep.client_logger') - def test_connector_cookies(self, m_log): - from aiohttp import connector - with self.assertWarns(DeprecationWarning): - conn = connector.TCPConnector(share_cookies=True, loop=self.loop) - - with test_utils.run_server(self.loop, router=Functional) as httpd: - conn.update_cookies({'test': '1'}) - r = self.loop.run_until_complete( - client.request('get', httpd.url('cookies'), - connector=conn, loop=self.loop)) - self.assertEqual(r.status, 200) - content = self.loop.run_until_complete(r.json()) - - self.assertEqual(content['headers']['Cookie'], 'test=1') - r.close() - - cookies = sorted([(k, v.value) for k, v in conn.cookies.items()]) - self.assertEqual( - cookies, [('c1', 'cookie1'), ('c2', 'cookie2'), ('test', '1')]) - - m_log.warning.assert_called_with( - 'Can not load response cookies: %s', mock.ANY) - conn.close() - def test_multidict_headers(self): with test_utils.run_server(self.loop, router=Functional) as httpd: url = httpd.url('method', 'post') @@ -1016,7 +952,7 @@ class TestHttpClientFunctional(unittest.TestCase): @asyncio.coroutine def go(): server = yield from self.loop.create_server( - Proto, '127.0.0.1') + Proto, '127.0.0.1', find_unused_port()) addr = server.sockets[0].getsockname() @@ -1059,7 +995,7 @@ class TestHttpClientFunctional(unittest.TestCase): @asyncio.coroutine def go(): server = yield from self.loop.create_server( - Proto, '127.0.0.1') + Proto, '127.0.0.1', find_unused_port()) addr = server.sockets[0].getsockname() @@ -1086,58 +1022,6 @@ class TestHttpClientFunctional(unittest.TestCase): self.loop.run_until_complete(go()) @mock.patch('aiohttp.client_reqrep.client_logger') - def test_share_cookie_partial_update(self, m_log): - with test_utils.run_server(self.loop, router=Functional) as httpd: - with self.assertWarns(DeprecationWarning): - conn = aiohttp.TCPConnector(share_cookies=True, loop=self.loop) - # Set c1 and c2 cookie - resp = self.loop.run_until_complete( - client.request('get', httpd.url('cookies'), - connector=conn, loop=self.loop)) - self.assertEqual(resp.cookies['c1'].value, 'cookie1') - self.assertEqual(resp.cookies['c2'].value, 'cookie2') - self.assertEqual(conn.cookies, resp.cookies) - resp.close() - - # Update c1 at server side - resp = self.loop.run_until_complete( - client.request('get', httpd.url('cookies_partial'), - connector=conn, loop=self.loop)) - self.assertEqual(resp.cookies['c1'].value, 'other_cookie1') - resp.close() - - # Assert, that we send updated cookies in next requests - r = self.loop.run_until_complete( - client.request('get', httpd.url('method', 'get'), - connector=conn, loop=self.loop)) - self.assertEqual(r.status, 200) - content = self.loop.run_until_complete(r.json()) - self.assertEqual( - content['headers']['Cookie'], - 'c1=other_cookie1; c2=cookie2') - r.close() - - def test_connector_cookie_merge(self): - with test_utils.run_server(self.loop, router=Functional) as httpd: - with self.assertWarns(DeprecationWarning): - conn = aiohttp.TCPConnector(share_cookies=True, loop=self.loop) - conn.update_cookies({ - "c1": "connector_cookie1", - "c2": "connector_cookie2", - }) - # Update c1 using direct cookies attribute of request - r = self.loop.run_until_complete( - client.request('get', httpd.url('method', 'get'), - cookies={"c1": "direct_cookie1"}, - connector=conn, loop=self.loop)) - self.assertEqual(r.status, 200) - content = self.loop.run_until_complete(r.json()) - self.assertEqual( - content['headers']['Cookie'], - 'c1=direct_cookie1; c2=connector_cookie2') - r.close() - - @mock.patch('aiohttp.client_reqrep.client_logger') def test_session_cookies(self, m_log): with test_utils.run_server(self.loop, router=Functional) as httpd: session = client.ClientSession(loop=self.loop) @@ -1146,9 +1030,12 @@ class TestHttpClientFunctional(unittest.TestCase): session.request('get', httpd.url('cookies'))) self.assertEqual(resp.cookies['c1'].value, 'cookie1') self.assertEqual(resp.cookies['c2'].value, 'cookie2') - self.assertEqual(session.cookies, resp.cookies) resp.close() + # Add the received cookies as shared for sending them to the test + # server, which is only accessible via IP + session.cookies.update(resp.cookies) + # Assert, that we send those cookies in next requests r = self.loop.run_until_complete( session.request('get', httpd.url('method', 'get'))) diff --git a/tests/test_client_request.py b/tests/test_client_request.py index abebef9..c354525 100644 --- a/tests/test_client_request.py +++ b/tests/test_client_request.py @@ -11,11 +11,13 @@ import urllib.parse import zlib from http.cookies import SimpleCookie +from multidict import CIMultiDict, CIMultiDictProxy, upstr + import pytest import aiohttp from aiohttp import BaseConnector +from aiohttp import helpers from aiohttp.client_reqrep import ClientRequest, ClientResponse -from aiohttp.multidict import CIMultiDict, CIMultiDictProxy, upstr import os.path @@ -265,13 +267,10 @@ def test_basic_auth_utf8(make_request): assert 'Basic bmtpbTrRgdC10LrRgNC10YI=' == req.headers['AUTHORIZATION'] -def test_basic_auth_tuple_deprecated(make_request, warning): - with warning(DeprecationWarning): - req = make_request('get', 'http://python.org', - auth=('nkim', '1234')) - - assert 'AUTHORIZATION' in req.headers - assert 'Basic bmtpbToxMjM0' == req.headers['AUTHORIZATION'] +def test_basic_auth_tuple_forbidden(make_request, warning): + with pytest.raises(TypeError): + make_request('get', 'http://python.org', + auth=('nkim', '1234')) def test_basic_auth_from_url(make_request): @@ -527,7 +526,7 @@ class TestClientRequest(unittest.TestCase): @unittest.mock.patch('aiohttp.client_reqrep.aiohttp') def test_content_encoding(self, m_http): - req = ClientRequest('get', 'http://python.org/', + req = ClientRequest('get', 'http://python.org/', data='foo', compress='deflate', loop=self.loop) resp = req.send(self.transport, self.protocol) self.assertEqual(req.headers['TRANSFER-ENCODING'], 'chunked') @@ -538,9 +537,19 @@ class TestClientRequest(unittest.TestCase): resp.close() @unittest.mock.patch('aiohttp.client_reqrep.aiohttp') + def test_content_encoding_dont_set_headers_if_no_body(self, m_http): + req = ClientRequest('get', 'http://python.org/', + compress='deflate', loop=self.loop) + resp = req.send(self.transport, self.protocol) + self.assertNotIn('TRANSFER-ENCODING', req.headers) + self.assertNotIn('CONTENT-ENCODING', req.headers) + self.loop.run_until_complete(req.close()) + resp.close() + + @unittest.mock.patch('aiohttp.client_reqrep.aiohttp') def test_content_encoding_header(self, m_http): req = ClientRequest( - 'get', 'http://python.org/', + 'get', 'http://python.org/', data='foo', headers={'Content-Encoding': 'deflate'}, loop=self.loop) resp = req.send(self.transport, self.protocol) self.assertEqual(req.headers['TRANSFER-ENCODING'], 'chunked') @@ -715,7 +724,7 @@ class TestClientRequest(unittest.TestCase): self.loop.run_until_complete(req.close()) def test_data_stream_exc(self): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) def gen(): yield b'binary data' @@ -755,7 +764,7 @@ class TestClientRequest(unittest.TestCase): resp.close() def test_data_stream_exc_chain(self): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) def gen(): yield from fut diff --git a/tests/test_client_response.py b/tests/test_client_response.py index 1a9d341..99458e8 100644 --- a/tests/test_client_response.py +++ b/tests/test_client_response.py @@ -7,6 +7,7 @@ import unittest import unittest.mock import aiohttp +from aiohttp import helpers from aiohttp.client_reqrep import ClientResponse @@ -69,9 +70,24 @@ class TestClientResponse(unittest.TestCase): '<ClientResponse(http://def-cl-resp.org) [200 Ok]>', repr(self.response)) + def test_repr_non_ascii_url(self): + response = ClientResponse('get', 'http://fake-host.org/\u03bb') + self.assertIn( + "<ClientResponse(http://fake-host.org/\\u03bb) [None None]>", + repr(response)) + response.close() + + def test_repr_non_ascii_reason(self): + response = ClientResponse('get', 'http://fake-host.org/path') + response.reason = '\u03bb' + self.assertIn( + "<ClientResponse(http://fake-host.org/path) [None \\u03bb]>", + repr(response)) + response.close() + def test_read_and_release_connection(self): def side_effect(*args, **kwargs): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result(b'payload') return fut content = self.response.content = unittest.mock.Mock() @@ -83,7 +99,7 @@ class TestClientResponse(unittest.TestCase): def test_read_and_release_connection_with_error(self): content = self.response.content = unittest.mock.Mock() - content.read.return_value = asyncio.Future(loop=self.loop) + content.read.return_value = helpers.create_future(self.loop) content.read.return_value.set_exception(ValueError) self.assertRaises( @@ -92,7 +108,7 @@ class TestClientResponse(unittest.TestCase): self.assertTrue(self.response._closed) def test_release(self): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result(b'') content = self.response.content = unittest.mock.Mock() content.readany.return_value = fut @@ -103,7 +119,7 @@ class TestClientResponse(unittest.TestCase): def test_read_decode_deprecated(self): self.response._content = b'data' self.response.json = unittest.mock.Mock() - self.response.json.return_value = asyncio.Future(loop=self.loop) + self.response.json.return_value = helpers.create_future(self.loop) self.response.json.return_value.set_result('json') with self.assertWarns(DeprecationWarning): @@ -113,7 +129,7 @@ class TestClientResponse(unittest.TestCase): def test_text(self): def side_effect(*args, **kwargs): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut self.response.headers = { @@ -127,7 +143,7 @@ class TestClientResponse(unittest.TestCase): def test_text_custom_encoding(self): def side_effect(*args, **kwargs): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut self.response.headers = { @@ -144,7 +160,7 @@ class TestClientResponse(unittest.TestCase): def test_text_detect_encoding(self): def side_effect(*args, **kwargs): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut self.response.headers = {'CONTENT-TYPE': 'application/json'} @@ -158,7 +174,7 @@ class TestClientResponse(unittest.TestCase): def test_text_after_read(self): def side_effect(*args, **kwargs): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut self.response.headers = { @@ -172,7 +188,7 @@ class TestClientResponse(unittest.TestCase): def test_json(self): def side_effect(*args, **kwargs): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut self.response.headers = { @@ -209,7 +225,7 @@ class TestClientResponse(unittest.TestCase): def test_json_override_encoding(self): def side_effect(*args, **kwargs): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut self.response.headers = { @@ -226,7 +242,7 @@ class TestClientResponse(unittest.TestCase): def test_json_detect_encoding(self): def side_effect(*args, **kwargs): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut self.response.headers = {'CONTENT-TYPE': 'application/json'} @@ -258,3 +274,16 @@ class TestClientResponse(unittest.TestCase): with self.assertWarns(DeprecationWarning): self.response.close(force=False) self.assertIsNone(self.response._connection) + + def test_raise_for_status_2xx(self): + self.response.status = 200 + self.response.reason = 'OK' + self.response.raise_for_status() # should not raise + + def test_raise_for_status_4xx(self): + self.response.status = 409 + self.response.reason = 'CONFLICT' + with self.assertRaises(aiohttp.HttpProcessingError) as cm: + self.response.raise_for_status() + self.assertEqual(str(cm.exception.code), '409') + self.assertEqual(str(cm.exception.message), "CONFLICT") diff --git a/tests/test_client_session.py b/tests/test_client_session.py index e6188f9..1a197de 100644 --- a/tests/test_client_session.py +++ b/tests/test_client_session.py @@ -3,13 +3,16 @@ import contextlib import gc import re import types +import http.cookies from unittest import mock +from multidict import CIMultiDict, MultiDict + import aiohttp import pytest +from aiohttp import web from aiohttp.client import ClientSession from aiohttp.connector import BaseConnector, TCPConnector -from aiohttp.multidict import CIMultiDict, MultiDict @pytest.fixture @@ -368,3 +371,43 @@ def test_request_ctx_manager_props(loop): assert isinstance(ctx_mgr.gi_frame, types.FrameType) assert not ctx_mgr.gi_running assert isinstance(ctx_mgr.gi_code, types.CodeType) + + +@pytest.mark.run_loop +def test_cookie_jar_usage(create_app_and_client): + req_url = None + + jar = mock.Mock() + jar.filter_cookies.return_value = None + + @asyncio.coroutine + def handler(request): + nonlocal req_url + req_url = "http://%s/" % request.host + + resp = web.Response() + resp.set_cookie("response", "resp_value") + return resp + + app, client = yield from create_app_and_client( + client_params={"cookies": {"request": "req_value"}, + "cookie_jar": jar} + ) + app.router.add_route('GET', '/', handler) + + # Updating the cookie jar with initial user defined cookies + jar.update_cookies.assert_called_with({"request": "req_value"}) + + jar.update_cookies.reset_mock() + yield from client.get("/") + + # Filtering the cookie jar before sending the request, + # getting the request URL as only parameter + jar.filter_cookies.assert_called_with(req_url) + + # Updating the cookie jar with the response cookies + assert jar.update_cookies.called + resp_cookies = jar.update_cookies.call_args[0][0] + assert isinstance(resp_cookies, http.cookies.SimpleCookie) + assert "response" in resp_cookies + assert resp_cookies["response"].value == "resp_value" diff --git a/tests/test_connector.py b/tests/test_connector.py index ba0ba8d..fddd387 100644 --- a/tests/test_connector.py +++ b/tests/test_connector.py @@ -1,7 +1,6 @@ """Tests of http client with custom Connector""" import asyncio -import http.cookies import gc import socket import unittest @@ -14,8 +13,10 @@ from unittest import mock import aiohttp from aiohttp import web from aiohttp import client -from aiohttp.client import ClientResponse +from aiohttp import helpers +from aiohttp.client import ClientResponse, ClientRequest from aiohttp.connector import Connection +from aiohttp.test_utils import unused_port class TestBaseConnector(unittest.TestCase): @@ -171,17 +172,12 @@ class TestBaseConnector(unittest.TestCase): conn.close() def test_release_close(self): - with self.assertWarns(DeprecationWarning): - conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop) + conn = aiohttp.BaseConnector(loop=self.loop) req = unittest.mock.Mock() resp = unittest.mock.Mock() resp.message.should_close = True req.response = resp - cookies = resp.cookies = http.cookies.SimpleCookie() - cookies['c1'] = 'cookie1' - cookies['c2'] = 'cookie2' - tr, proto = unittest.mock.Mock(), unittest.mock.Mock() key = 1 conn._acquired[key].add(tr) @@ -217,8 +213,7 @@ class TestBaseConnector(unittest.TestCase): key = ('127.0.0.1', 80, False) tr1, proto1 = unittest.mock.Mock(), unittest.mock.Mock() - with self.assertWarns(DeprecationWarning): - conn = aiohttp.BaseConnector(share_cookies=True, loop=self.loop) + conn = aiohttp.BaseConnector(loop=self.loop) conn._conns[key] = [(tr1, proto1, 1)] req = unittest.mock.Mock() resp = unittest.mock.Mock() @@ -263,20 +258,18 @@ class TestBaseConnector(unittest.TestCase): tr, proto = unittest.mock.Mock(), unittest.mock.Mock() proto.is_connected.return_value = True - class Req: - host = 'host' - port = 80 - ssl = False - response = unittest.mock.Mock() + req = ClientRequest('GET', 'http://host:80', + loop=self.loop, + response_class=unittest.mock.Mock()) conn = aiohttp.BaseConnector(loop=self.loop) key = ('host', 80, False) conn._conns[key] = [(tr, proto, self.loop.time())] conn._create_connection = unittest.mock.Mock() - conn._create_connection.return_value = asyncio.Future(loop=self.loop) + conn._create_connection.return_value = helpers.create_future(self.loop) conn._create_connection.return_value.set_result((tr, proto)) - connection = self.loop.run_until_complete(conn.connect(Req())) + connection = self.loop.run_until_complete(conn.connect(req)) self.assertFalse(conn._create_connection.called) self.assertEqual(connection._transport, tr) self.assertEqual(connection._protocol, proto) @@ -286,7 +279,7 @@ class TestBaseConnector(unittest.TestCase): def test_connect_timeout(self): conn = aiohttp.BaseConnector(loop=self.loop) conn._create_connection = unittest.mock.Mock() - conn._create_connection.return_value = asyncio.Future(loop=self.loop) + conn._create_connection.return_value = helpers.create_future(self.loop) conn._create_connection.return_value.set_exception( asyncio.TimeoutError()) @@ -297,7 +290,7 @@ class TestBaseConnector(unittest.TestCase): def test_connect_oserr(self): conn = aiohttp.BaseConnector(loop=self.loop) conn._create_connection = unittest.mock.Mock() - conn._create_connection.return_value = asyncio.Future(loop=self.loop) + conn._create_connection.return_value = helpers.create_future(self.loop) err = OSError(1, 'permission error') conn._create_connection.return_value.set_exception(err) @@ -489,21 +482,19 @@ class TestBaseConnector(unittest.TestCase): tr, proto = unittest.mock.Mock(), unittest.mock.Mock() proto.is_connected.return_value = True - class Req: - host = 'host' - port = 80 - ssl = False - response = unittest.mock.Mock() + req = ClientRequest('GET', 'http://host:80', + loop=self.loop, + response_class=unittest.mock.Mock()) conn = aiohttp.BaseConnector(loop=self.loop, limit=1) key = ('host', 80, False) conn._conns[key] = [(tr, proto, self.loop.time())] conn._create_connection = unittest.mock.Mock() - conn._create_connection.return_value = asyncio.Future( - loop=self.loop) + conn._create_connection.return_value = helpers.create_future( + self.loop) conn._create_connection.return_value.set_result((tr, proto)) - connection1 = yield from conn.connect(Req()) + connection1 = yield from conn.connect(req) self.assertEqual(connection1._transport, tr) self.assertEqual(1, len(conn._acquired[key])) @@ -513,7 +504,7 @@ class TestBaseConnector(unittest.TestCase): @asyncio.coroutine def f(): nonlocal acquired - connection2 = yield from conn.connect(Req()) + connection2 = yield from conn.connect(req) acquired = True self.assertEqual(1, len(conn._acquired[key])) connection2.release() @@ -537,34 +528,49 @@ class TestBaseConnector(unittest.TestCase): tr, proto = unittest.mock.Mock(), unittest.mock.Mock() proto.is_connected.return_value = True - class Req: - host = 'host' - port = 80 - ssl = False - response = unittest.mock.Mock() + req = ClientRequest('GET', 'http://host:80', + loop=self.loop, + response_class=unittest.mock.Mock()) conn = aiohttp.BaseConnector(loop=self.loop, limit=1) key = ('host', 80, False) conn._conns[key] = [(tr, proto, self.loop.time())] conn._create_connection = unittest.mock.Mock() - conn._create_connection.return_value = asyncio.Future( - loop=self.loop) + conn._create_connection.return_value = helpers.create_future( + self.loop) conn._create_connection.return_value.set_result((tr, proto)) - connection = yield from conn.connect(Req()) + connection = yield from conn.connect(req) self.assertEqual(connection._transport, tr) self.assertEqual(1, len(conn._acquired[key])) with self.assertRaises(asyncio.TimeoutError): # limit exhausted - yield from asyncio.wait_for(conn.connect(Req), 0.01, + yield from asyncio.wait_for(conn.connect(req), 0.01, loop=self.loop) - connection.close() - self.loop.run_until_complete(go()) + def test_connect_with_limit_release_waiters(self): + + def check_with_exc(err): + conn = aiohttp.BaseConnector(limit=1, loop=self.loop) + conn._create_connection = unittest.mock.Mock() + conn._create_connection.return_value = \ + helpers.create_future(self.loop) + conn._create_connection.return_value.set_exception(err) + + with self.assertRaises(Exception): + req = unittest.mock.Mock() + self.loop.run_until_complete(conn.connect(req)) + key = (req.host, req.port, req.ssl) + self.assertFalse(conn._waiters[key]) + + check_with_exc(OSError(1, 'permission error')) + check_with_exc(RuntimeError()) + check_with_exc(asyncio.TimeoutError()) + def test_connect_with_limit_concurrent(self): @asyncio.coroutine @@ -572,11 +578,10 @@ class TestBaseConnector(unittest.TestCase): proto = unittest.mock.Mock() proto.is_connected.return_value = True - class Req: - host = 'host' - port = 80 - ssl = False - response = unittest.mock.Mock(_should_close=False) + req = ClientRequest('GET', 'http://host:80', + loop=self.loop, + response_class=unittest.mock.Mock( + _should_close=False)) max_connections = 2 num_connections = 0 @@ -618,7 +623,7 @@ class TestBaseConnector(unittest.TestCase): return num_requests += 1 if not start: - connection = yield from conn.connect(Req()) + connection = yield from conn.connect(req) yield from asyncio.sleep(0, loop=self.loop) connection.release() tasks = [ @@ -641,21 +646,19 @@ class TestBaseConnector(unittest.TestCase): tr, proto = unittest.mock.Mock(), unittest.mock.Mock() proto.is_connected.return_value = True - class Req: - host = 'host' - port = 80 - ssl = False - response = unittest.mock.Mock() + req = ClientRequest('GET', 'http://host:80', + loop=self.loop, + response_class=unittest.mock.Mock()) conn = aiohttp.BaseConnector(loop=self.loop, limit=1) key = ('host', 80, False) conn._conns[key] = [(tr, proto, self.loop.time())] conn._create_connection = unittest.mock.Mock() - conn._create_connection.return_value = asyncio.Future( - loop=self.loop) + conn._create_connection.return_value = helpers.create_future( + self.loop) conn._create_connection.return_value.set_result((tr, proto)) - connection = yield from conn.connect(Req()) + connection = yield from conn.connect(req) self.assertEqual(1, len(conn._acquired)) conn.close() @@ -683,6 +686,19 @@ class TestBaseConnector(unittest.TestCase): self.assertIsNone(conn.limit) conn.close() + def test_force_close_and_explicit_keep_alive(self): + with self.assertRaises(ValueError): + aiohttp.BaseConnector(loop=self.loop, keepalive_timeout=30, + force_close=True) + + conn = aiohttp.BaseConnector(loop=self.loop, force_close=True, + keepalive_timeout=None) + assert conn + + conn = aiohttp.BaseConnector(loop=self.loop, force_close=True) + + assert conn + class TestHttpClientConnector(unittest.TestCase): @@ -699,19 +715,12 @@ class TestHttpClientConnector(unittest.TestCase): self.loop.close() gc.collect() - def find_unused_port(self): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.bind(('127.0.0.1', 0)) - port = s.getsockname()[1] - s.close() - return port - @asyncio.coroutine def create_server(self, method, path, handler): app = web.Application(loop=self.loop) app.router.add_route(method, path, handler) - port = self.find_unused_port() + port = unused_port() self.handler = app.make_handler(keep_alive_on=False) srv = yield from self.loop.create_server( self.handler, '127.0.0.1', port) @@ -726,7 +735,7 @@ class TestHttpClientConnector(unittest.TestCase): app = web.Application(loop=self.loop) app.router.add_route(method, path, handler) - self.handler = app.make_handler(keep_alive_on=False) + self.handler = app.make_handler(keep_alive_on=False, access_log=None) sock_path = os.path.join(tmpdir, 'socket.sock') srv = yield from self.loop.create_unix_server( self.handler, sock_path) @@ -752,6 +761,32 @@ class TestHttpClientConnector(unittest.TestCase): r.close() conn.close() + def test_tcp_connector_uses_provided_local_addr(self): + @asyncio.coroutine + def handler(request): + return web.HTTPOk() + + app, srv, url = self.loop.run_until_complete( + self.create_server('get', '/', handler) + ) + + port = unused_port() + conn = aiohttp.TCPConnector(loop=self.loop, + local_addr=('127.0.0.1', port)) + + r = self.loop.run_until_complete( + aiohttp.request( + 'get', url, + connector=conn + )) + + self.loop.run_until_complete(r.release()) + first_conn = next(iter(conn._conns.values()))[0][0] + self.assertEqual(first_conn._sock.getsockname(), ('127.0.0.1', port)) + r.close() + + conn.close() + @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'requires unix') def test_unix_connector(self): @asyncio.coroutine @@ -772,12 +807,6 @@ class TestHttpClientConnector(unittest.TestCase): self.assertEqual(r.status, 200) r.close() - def test_connector_cookie_deprecation(self): - with self.assertWarnsRegex(DeprecationWarning, - "^Using `share_cookies` is deprecated"): - conn = aiohttp.TCPConnector(share_cookies=True, loop=self.loop) - conn.close() - def test_ambiguous_ctor_params(self): with self.assertRaises(ValueError): aiohttp.TCPConnector(resolve=True, use_dns_cache=False, @@ -796,3 +825,43 @@ class TestHttpClientConnector(unittest.TestCase): self.assertTrue(conn.use_dns_cache) with self.assertWarns(DeprecationWarning): self.assertTrue(conn.resolve) + + def test_resolver_not_called_with_address_is_ip(self): + resolver = unittest.mock.MagicMock() + connector = aiohttp.TCPConnector(resolver=resolver, loop=self.loop) + + req = ClientRequest('GET', 'http://127.0.0.1:{}'.format(unused_port()), + loop=self.loop, + response_class=unittest.mock.Mock()) + + with self.assertRaises(OSError): + self.loop.run_until_complete(connector.connect(req)) + + resolver.resolve.assert_not_called() + + def test_ip_addresses(self): + ip_addresses = [ + '0.0.0.0', + '127.0.0.1', + '255.255.255.255', + '0:0:0:0:0:0:0:0', + 'FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF', + '00AB:0002:3008:8CFD:00AB:0002:3008:8CFD', + '00ab:0002:3008:8cfd:00ab:0002:3008:8cfd', + 'AB:02:3008:8CFD:AB:02:3008:8CFD', + 'AB:02:3008:8CFD::02:3008:8CFD', + '::', + '1::1', + ] + for address in ip_addresses: + assert helpers.is_ip_address(address) is True + + def test_host_addresses(self): + hosts = [ + 'www.four.part.host' + 'www.python.org', + 'foo.bar', + 'localhost', + ] + for host in hosts: + assert helpers.is_ip_address(host) is False diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 34949f6..4368b42 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -1,7 +1,10 @@ +import asyncio import pytest -from unittest import mock -from aiohttp import helpers +import unittest import datetime +import http.cookies +from unittest import mock +from aiohttp import helpers, test_utils def test_parse_mimetype_1(): @@ -71,6 +74,27 @@ def test_basic_auth4(): assert auth.encode() == 'Basic bmtpbTpwd2Q=' +def test_basic_auth_decode(): + auth = helpers.BasicAuth.decode('Basic bmtpbTpwd2Q=') + assert auth.login == 'nkim' + assert auth.password == 'pwd' + + +def test_basic_auth_invalid(): + with pytest.raises(ValueError): + helpers.BasicAuth.decode('bmtpbTpwd2Q=') + + +def test_basic_auth_decode_not_basic(): + with pytest.raises(ValueError): + helpers.BasicAuth.decode('Complex bmtpbTpwd2Q=') + + +def test_basic_auth_decode_bad_base64(): + with pytest.raises(ValueError): + helpers.BasicAuth.decode('Basic bmtpbTpwd2Q') + + def test_invalid_formdata_params(): with pytest.raises(TypeError): helpers.FormData('asdasf') @@ -131,7 +155,7 @@ def test_access_logger_atoms(mock_getpid, mock_datetime): transport = mock.Mock() transport.get_extra_info.return_value = ("127.0.0.2", 1234) access_logger.log(message, environ, response, transport, 3.1415926) - assert False == mock_logger.exception.called + assert not mock_logger.exception.called expected = ('127.0.0.2 [01/Jan/1843:00:00:00 +0000] <42> - - ' 'GET /path HTTP/1.1 200 42 123 3 3.141593 3141593') mock_logger.info.assert_called_with(expected) @@ -147,7 +171,7 @@ def test_access_logger_dicts(): transport = mock.Mock() transport.get_extra_info.return_value = ("127.0.0.2", 1234) access_logger.log(message, environ, response, transport, 0.0) - assert False == mock_logger.error.called + assert not mock_logger.error.called expected = 'Mock/1.0 123 EGGS -' mock_logger.info.assert_called_with(expected) @@ -156,9 +180,10 @@ def test_logger_no_message_and_environ(): mock_logger = mock.Mock() mock_transport = mock.Mock() mock_transport.get_extra_info.return_value = ("127.0.0.3", 0) - access_logger = helpers.AccessLogger(mock_logger, "%r %{FOOBAR}e") + access_logger = helpers.AccessLogger(mock_logger, + "%r %{FOOBAR}e %{content-type}i") access_logger.log(None, None, None, mock_transport, 0.0) - mock_logger.info.assert_called_with("- -") + mock_logger.info.assert_called_with("- - (no headers)") def test_reify(): @@ -205,3 +230,491 @@ def test_requote_uri_properly_requotes(): # Ensure requoting doesn't break expectations. quoted = 'http://example.com/fiz?buz=%25ppicture' assert quoted == helpers.requote_uri(quoted) + + +def test_create_future_with_new_loop(): + # We should use the new create_future() if it's available. + mock_loop = mock.Mock() + expected = 'hello' + mock_loop.create_future.return_value = expected + assert expected == helpers.create_future(mock_loop) + + +@mock.patch('asyncio.Future') +def test_create_future_with_old_loop(MockFuture): + # The old loop (without create_future()) should just have a Future object + # wrapped around it. + mock_loop = mock.Mock() + del mock_loop.create_future + + expected = 'hello' + MockFuture.return_value = expected + + future = helpers.create_future(mock_loop) + MockFuture.assert_called_with(loop=mock_loop) + assert expected == future + + +def test_is_ip_address(): + assert helpers.is_ip_address("127.0.0.1") + assert helpers.is_ip_address("::1") + assert helpers.is_ip_address("FE80:0000:0000:0000:0202:B3FF:FE1E:8329") + + # Hostnames + assert not helpers.is_ip_address("localhost") + assert not helpers.is_ip_address("www.example.com") + + # Out of range + assert not helpers.is_ip_address("999.999.999.999") + # Contain a port + assert not helpers.is_ip_address("127.0.0.1:80") + assert not helpers.is_ip_address("[2001:db8:0:1]:80") + # Too many "::" + assert not helpers.is_ip_address("1200::AB00:1234::2552:7777:1313") + + +class TestCookieJarBase(unittest.TestCase): + + def setUp(self): + self.loop = asyncio.new_event_loop() + asyncio.set_event_loop(None) + + # N.B. those need to be overriden in child test cases + self.jar = helpers.CookieJar(loop=self.loop) + # Cookies to send from client to server as "Cookie" header + self.cookies_to_send = http.cookies.SimpleCookie() + # Cookies received from the server as "Set-Cookie" header + self.cookies_to_receive = http.cookies.SimpleCookie() + + def tearDown(self): + self.loop.close() + + def request_reply_with_same_url(self, url): + self.jar.update_cookies(self.cookies_to_send) + cookies_sent = self.jar.filter_cookies(url) + + self.jar.cookies.clear() + + self.jar.update_cookies(self.cookies_to_receive, url) + cookies_received = self.jar.cookies.copy() + + self.jar.cookies.clear() + + return cookies_sent, cookies_received + + +class TestCookieJarSafe(TestCookieJarBase): + + def setUp(self): + super().setUp() + + self.cookies_to_send = http.cookies.SimpleCookie( + "shared-cookie=first; " + "domain-cookie=second; Domain=example.com; " + "subdomain1-cookie=third; Domain=test1.example.com; " + "subdomain2-cookie=fourth; Domain=test2.example.com; " + "dotted-domain-cookie=fifth; Domain=.example.com; " + "different-domain-cookie=sixth; Domain=different.org; " + "secure-cookie=seventh; Domain=secure.com; Secure; " + "no-path-cookie=eighth; Domain=pathtest.com; " + "path1-cookie=nineth; Domain=pathtest.com; Path=/; " + "path2-cookie=tenth; Domain=pathtest.com; Path=/one; " + "path3-cookie=eleventh; Domain=pathtest.com; Path=/one/two; " + "path4-cookie=twelfth; Domain=pathtest.com; Path=/one/two/; " + "expires-cookie=thirteenth; Domain=expirestest.com; Path=/;" + " Expires=Tue, 1 Jan 1980 12:00:00 GMT; " + "max-age-cookie=fourteenth; Domain=maxagetest.com; Path=/;" + " Max-Age=60; " + "invalid-max-age-cookie=fifteenth; Domain=invalid-values.com; " + " Max-Age=string; " + "invalid-expires-cookie=sixteenth; Domain=invalid-values.com; " + " Expires=string;" + ) + + self.cookies_to_receive = http.cookies.SimpleCookie( + "unconstrained-cookie=first; Path=/; " + "domain-cookie=second; Domain=example.com; Path=/; " + "subdomain1-cookie=third; Domain=test1.example.com; Path=/; " + "subdomain2-cookie=fourth; Domain=test2.example.com; Path=/; " + "dotted-domain-cookie=fifth; Domain=.example.com; Path=/; " + "different-domain-cookie=sixth; Domain=different.org; Path=/; " + "no-path-cookie=seventh; Domain=pathtest.com; " + "path-cookie=eighth; Domain=pathtest.com; Path=/somepath; " + "wrong-path-cookie=nineth; Domain=pathtest.com; Path=somepath;" + ) + + self.jar = helpers.CookieJar(loop=self.loop) + + def timed_request( + self, url, update_time, send_time): + time_func = "time.monotonic" + + with mock.patch(time_func, return_value=update_time): + self.jar.update_cookies(self.cookies_to_send) + + with mock.patch(time_func, return_value=send_time): + test_utils.run_briefly(self.loop) + + cookies_sent = self.jar.filter_cookies(url) + + self.jar.cookies.clear() + + return cookies_sent + + def test_constructor(self): + jar = helpers.CookieJar(loop=self.loop) + jar.update_cookies(self.cookies_to_send) + self.assertEqual(jar.cookies, self.cookies_to_send) + self.assertIs(jar._loop, self.loop) + + def test_domain_filter_ip(self): + cookies_sent, cookies_received = ( + self.request_reply_with_same_url("http://1.2.3.4/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie" + }) + + self.assertEqual(set(cookies_received.keys()), set()) + + def test_domain_filter_same_host(self): + cookies_sent, cookies_received = ( + self.request_reply_with_same_url("http://example.com/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "domain-cookie", + "dotted-domain-cookie" + }) + + self.assertEqual(set(cookies_received.keys()), { + "unconstrained-cookie", + "domain-cookie", + "dotted-domain-cookie" + }) + + def test_domain_filter_same_host_and_subdomain(self): + cookies_sent, cookies_received = ( + self.request_reply_with_same_url("http://test1.example.com/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "domain-cookie", + "subdomain1-cookie", + "dotted-domain-cookie" + }) + + self.assertEqual(set(cookies_received.keys()), { + "unconstrained-cookie", + "domain-cookie", + "subdomain1-cookie", + "dotted-domain-cookie" + }) + + def test_domain_filter_same_host_diff_subdomain(self): + cookies_sent, cookies_received = ( + self.request_reply_with_same_url("http://different.example.com/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "domain-cookie", + "dotted-domain-cookie" + }) + + self.assertEqual(set(cookies_received.keys()), { + "unconstrained-cookie", + "domain-cookie", + "dotted-domain-cookie" + }) + + def test_domain_filter_diff_host(self): + cookies_sent, cookies_received = ( + self.request_reply_with_same_url("http://different.org/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "different-domain-cookie" + }) + + self.assertEqual(set(cookies_received.keys()), { + "unconstrained-cookie", + "different-domain-cookie" + }) + + def test_domain_filter_host_only(self): + self.jar.update_cookies(self.cookies_to_receive, "http://example.com/") + + cookies_sent = self.jar.filter_cookies("http://example.com/") + self.assertIn("unconstrained-cookie", set(cookies_sent.keys())) + + cookies_sent = self.jar.filter_cookies("http://different.org/") + self.assertNotIn("unconstrained-cookie", set(cookies_sent.keys())) + + def test_secure_filter(self): + cookies_sent, _ = ( + self.request_reply_with_same_url("http://secure.com/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie" + }) + + cookies_sent, _ = ( + self.request_reply_with_same_url("https://secure.com/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "secure-cookie" + }) + + def test_path_filter_root(self): + cookies_sent, _ = ( + self.request_reply_with_same_url("http://pathtest.com/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "no-path-cookie", + "path1-cookie" + }) + + def test_path_filter_folder(self): + + cookies_sent, _ = ( + self.request_reply_with_same_url("http://pathtest.com/one/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "no-path-cookie", + "path1-cookie", + "path2-cookie" + }) + + def test_path_filter_file(self): + + cookies_sent, _ = self.request_reply_with_same_url( + "http://pathtest.com/one/two") + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "no-path-cookie", + "path1-cookie", + "path2-cookie", + "path3-cookie" + }) + + def test_path_filter_subfolder(self): + + cookies_sent, _ = self.request_reply_with_same_url( + "http://pathtest.com/one/two/") + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "no-path-cookie", + "path1-cookie", + "path2-cookie", + "path3-cookie", + "path4-cookie" + }) + + def test_path_filter_subsubfolder(self): + + cookies_sent, _ = self.request_reply_with_same_url( + "http://pathtest.com/one/two/three/") + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "no-path-cookie", + "path1-cookie", + "path2-cookie", + "path3-cookie", + "path4-cookie" + }) + + def test_path_filter_different_folder(self): + + cookies_sent, _ = ( + self.request_reply_with_same_url("http://pathtest.com/hundred/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "no-path-cookie", + "path1-cookie" + }) + + def test_path_value(self): + _, cookies_received = ( + self.request_reply_with_same_url("http://pathtest.com/")) + + self.assertEqual(set(cookies_received.keys()), { + "unconstrained-cookie", + "no-path-cookie", + "path-cookie", + "wrong-path-cookie" + }) + + self.assertEqual(cookies_received["no-path-cookie"]["path"], "/") + self.assertEqual(cookies_received["path-cookie"]["path"], "/somepath") + self.assertEqual(cookies_received["wrong-path-cookie"]["path"], "/") + + def test_expires(self): + ts_before = datetime.datetime( + 1975, 1, 1, tzinfo=datetime.timezone.utc).timestamp() + + ts_after = datetime.datetime( + 1985, 1, 1, tzinfo=datetime.timezone.utc).timestamp() + + cookies_sent = self.timed_request( + "http://expirestest.com/", ts_before, ts_before) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "expires-cookie" + }) + + cookies_sent = self.timed_request( + "http://expirestest.com/", ts_before, ts_after) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie" + }) + + def test_max_age(self): + cookies_sent = self.timed_request( + "http://maxagetest.com/", 1000, 1000) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "max-age-cookie" + }) + + cookies_sent = self.timed_request( + "http://maxagetest.com/", 1000, 2000) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie" + }) + + def test_invalid_values(self): + cookies_sent, cookies_received = ( + self.request_reply_with_same_url("http://invalid-values.com/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "invalid-max-age-cookie", + "invalid-expires-cookie" + }) + + cookie = cookies_sent["invalid-max-age-cookie"] + self.assertEqual(cookie["max-age"], "") + + cookie = cookies_sent["invalid-expires-cookie"] + self.assertEqual(cookie["expires"], "") + + def test_domain_matching(self): + test_func = helpers.CookieJar._is_domain_match + + self.assertTrue(test_func("test.com", "test.com")) + self.assertTrue(test_func("test.com", "sub.test.com")) + + self.assertFalse(test_func("test.com", "")) + self.assertFalse(test_func("test.com", "test.org")) + self.assertFalse(test_func("diff-test.com", "test.com")) + self.assertFalse(test_func("test.com", "diff-test.com")) + self.assertFalse(test_func("test.com", "127.0.0.1")) + + def test_path_matching(self): + test_func = helpers.CookieJar._is_path_match + + self.assertTrue(test_func("/", "")) + self.assertTrue(test_func("/file", "")) + self.assertTrue(test_func("/folder/file", "")) + self.assertTrue(test_func("/", "/")) + self.assertTrue(test_func("/file", "/")) + self.assertTrue(test_func("/file", "/file")) + self.assertTrue(test_func("/folder/", "/folder/")) + self.assertTrue(test_func("/folder/", "/")) + self.assertTrue(test_func("/folder/file", "/")) + + self.assertFalse(test_func("/", "/file")) + self.assertFalse(test_func("/", "/folder/")) + self.assertFalse(test_func("/file", "/folder/file")) + self.assertFalse(test_func("/folder/", "/folder/file")) + self.assertFalse(test_func("/different-file", "/file")) + self.assertFalse(test_func("/different-folder/", "/folder/")) + + def test_date_parsing(self): + parse_func = helpers.CookieJar._parse_date + utc = datetime.timezone.utc + + self.assertEqual(parse_func(""), None) + + # 70 -> 1970 + self.assertEqual( + parse_func("Tue, 1 Jan 70 00:00:00 GMT"), + datetime.datetime(1970, 1, 1, tzinfo=utc)) + + # 10 -> 2010 + self.assertEqual( + parse_func("Tue, 1 Jan 10 00:00:00 GMT"), + datetime.datetime(2010, 1, 1, tzinfo=utc)) + + # No day of week string + self.assertEqual( + parse_func("1 Jan 1970 00:00:00 GMT"), + datetime.datetime(1970, 1, 1, tzinfo=utc)) + + # No timezone string + self.assertEqual( + parse_func("Tue, 1 Jan 1970 00:00:00"), + datetime.datetime(1970, 1, 1, tzinfo=utc)) + + # No year + self.assertEqual(parse_func("Tue, 1 Jan 00:00:00 GMT"), None) + + # No month + self.assertEqual(parse_func("Tue, 1 1970 00:00:00 GMT"), None) + + # No day of month + self.assertEqual(parse_func("Tue, Jan 1970 00:00:00 GMT"), None) + + # No time + self.assertEqual(parse_func("Tue, 1 Jan 1970 GMT"), None) + + # Invalid day of month + self.assertEqual(parse_func("Tue, 0 Jan 1970 00:00:00 GMT"), None) + + # Invalid year + self.assertEqual(parse_func("Tue, 1 Jan 1500 00:00:00 GMT"), None) + + # Invalid time + self.assertEqual(parse_func("Tue, 1 Jan 1970 77:88:99 GMT"), None) + + +class TestCookieJarUnsafe(TestCookieJarBase): + + def setUp(self): + super().setUp() + self.cookies_to_send = http.cookies.SimpleCookie( + "shared-cookie=first; " + "ip-cookie=second; Domain=127.0.0.1;" + ) + + self.cookies_to_receive = http.cookies.SimpleCookie( + "shared-cookie=first; " + "ip-cookie=second; Domain=127.0.0.1;" + ) + + self.jar = helpers.CookieJar(loop=self.loop, unsafe=True) + + def test_preserving_ip_domain_cookies(self): + cookies_sent, cookies_received = ( + self.request_reply_with_same_url("http://127.0.0.1/")) + + self.assertEqual(set(cookies_sent.keys()), { + "shared-cookie", + "ip-cookie", + }) + + self.assertEqual(set(cookies_received.keys()), { + "shared-cookie", + "ip-cookie", + }) diff --git a/tests/test_http_parser.py b/tests/test_http_parser.py index bd5c9e9..a4ec09f 100644 --- a/tests/test_http_parser.py +++ b/tests/test_http_parser.py @@ -19,83 +19,92 @@ class TestParseHeaders(unittest.TestCase): self.parser = protocol.HttpParser(8190, 32768, 8190) def test_parse_headers(self): - hdrs = ('', 'test: line', ' continue', - 'test2: data', '', '') + hdrs = (b'', b'test: line', b' continue', + b'test2: data', b'', b'') - headers, close, compression = self.parser.parse_headers(hdrs) + headers, raw_headers, close, compression = self.parser.parse_headers( + hdrs) self.assertEqual(list(headers.items()), [('TEST', 'line\r\n continue'), ('TEST2', 'data')]) + self.assertEqual(raw_headers, + [(b'TEST', b'line\r\n continue'), + (b'TEST2', b'data')]) self.assertIsNone(close) self.assertIsNone(compression) def test_parse_headers_multi(self): - hdrs = ('', - 'Set-Cookie: c1=cookie1', - 'Set-Cookie: c2=cookie2', '') + hdrs = (b'', + b'Set-Cookie: c1=cookie1', + b'Set-Cookie: c2=cookie2', '') - headers, close, compression = self.parser.parse_headers(hdrs) + headers, raw_headers, close, compression = self.parser.parse_headers( + hdrs) self.assertEqual(list(headers.items()), [('SET-COOKIE', 'c1=cookie1'), ('SET-COOKIE', 'c2=cookie2')]) + self.assertEqual(raw_headers, + [(b'SET-COOKIE', b'c1=cookie1'), + (b'SET-COOKIE', b'c2=cookie2')]) self.assertIsNone(close) self.assertIsNone(compression) def test_conn_close(self): - headers, close, compression = self.parser.parse_headers( - ['', 'connection: close', '']) + headers, raw_headers, close, compression = self.parser.parse_headers( + [b'', b'connection: close', b'']) self.assertTrue(close) def test_conn_keep_alive(self): - headers, close, compression = self.parser.parse_headers( - ['', 'connection: keep-alive', '']) + headers, raw_headers, close, compression = self.parser.parse_headers( + [b'', b'connection: keep-alive', b'']) self.assertFalse(close) def test_conn_other(self): - headers, close, compression = self.parser.parse_headers( - ['', 'connection: test', '', '']) + headers, raw_headers, close, compression = self.parser.parse_headers( + [b'', b'connection: test', b'', b'']) self.assertIsNone(close) def test_compression_gzip(self): - headers, close, compression = self.parser.parse_headers( - ['', 'content-encoding: gzip', '', '']) + headers, raw_headers, close, compression = self.parser.parse_headers( + [b'', b'content-encoding: gzip', b'', b'']) self.assertEqual('gzip', compression) def test_compression_deflate(self): - headers, close, compression = self.parser.parse_headers( - ['', 'content-encoding: deflate', '', '']) + headers, raw_headers, close, compression = self.parser.parse_headers( + [b'', b'content-encoding: deflate', b'', b'']) self.assertEqual('deflate', compression) def test_compression_unknown(self): - headers, close, compression = self.parser.parse_headers( - ['', 'content-encoding: compress', '', '']) + headers, raw_headers, close, compression = self.parser.parse_headers( + [b'', b'content-encoding: compress', b'', b'']) self.assertIsNone(compression) def test_max_field_size(self): with self.assertRaises(errors.LineTooLong) as cm: parser = protocol.HttpParser(8190, 32768, 5) parser.parse_headers( - ['', 'test: line data data\r\n', 'data\r\n', '\r\n']) + [b'', b'test: line data data\r\n', b'data\r\n', b'\r\n']) self.assertIn("limit request headers fields size", str(cm.exception)) def test_max_continuation_headers_size(self): with self.assertRaises(errors.LineTooLong) as cm: parser = protocol.HttpParser(8190, 32768, 5) - parser.parse_headers(['', 'test: line\r\n', ' test\r\n', '\r\n']) + parser.parse_headers([b'', b'test: line\r\n', + b' test\r\n', b'\r\n']) self.assertIn("limit request headers fields size", str(cm.exception)) def test_invalid_header(self): with self.assertRaisesRegex( errors.InvalidHeader, "(400, message='Invalid HTTP Header: test line)"): - self.parser.parse_headers(['', 'test line\r\n', '\r\n']) + self.parser.parse_headers([b'', b'test line\r\n', b'\r\n']) def test_invalid_name(self): with self.assertRaisesRegex( errors.InvalidHeader, "(400, message='Invalid HTTP Header: TEST..)"): - self.parser.parse_headers(['', 'test[]: line\r\n', '\r\n']) + self.parser.parse_headers([b'', b'test[]: line\r\n', b'\r\n']) class TestDeflateBuffer(unittest.TestCase): @@ -245,6 +254,7 @@ class TestParsePayload(unittest.TestCase): msg = protocol.RawRequestMessage( 'GET', '/', (1, 1), CIMultiDict([('CONTENT-LENGTH', 'qwe')]), + [(b'CONTENT-LENGTH', b'qwe')], None, None) out = aiohttp.FlowControlDataQueue(self.stream) buf = aiohttp.ParserBuffer() @@ -254,7 +264,9 @@ class TestParsePayload(unittest.TestCase): def test_http_payload_parser_length_wrong(self): msg = protocol.RawRequestMessage( 'GET', '/', (1, 1), - CIMultiDict([('CONTENT-LENGTH', '-1')]), None, None) + CIMultiDict([('CONTENT-LENGTH', '-1')]), + [(b'CONTENT-LENGTH', b'-1')], + None, None) out = aiohttp.FlowControlDataQueue(self.stream) buf = aiohttp.ParserBuffer() p = protocol.HttpPayloadParser(msg)(out, buf) @@ -263,7 +275,9 @@ class TestParsePayload(unittest.TestCase): def test_http_payload_parser_length(self): msg = protocol.RawRequestMessage( 'GET', '/', (1, 1), - CIMultiDict([('CONTENT-LENGTH', '2')]), None, None) + CIMultiDict([('CONTENT-LENGTH', '2')]), + [(b'CONTENT-LENGTH', b'2')], + None, None) out = aiohttp.FlowControlDataQueue(self.stream) buf = aiohttp.ParserBuffer() p = protocol.HttpPayloadParser(msg)(out, buf) @@ -278,7 +292,7 @@ class TestParsePayload(unittest.TestCase): def test_http_payload_parser_no_length(self): msg = protocol.RawRequestMessage( - 'GET', '/', (1, 1), CIMultiDict(), None, None) + 'GET', '/', (1, 1), CIMultiDict(), [], None, None) out = aiohttp.FlowControlDataQueue(self.stream) buf = aiohttp.ParserBuffer() p = protocol.HttpPayloadParser(msg, readall=False)(out, buf) @@ -292,7 +306,8 @@ class TestParsePayload(unittest.TestCase): def test_http_payload_parser_deflate(self): msg = protocol.RawRequestMessage( 'GET', '/', (1, 1), - CIMultiDict([('CONTENT-LENGTH', len(self._COMPRESSED))]), + CIMultiDict([('CONTENT-LENGTH', str(len(self._COMPRESSED)))]), + [(b'CONTENT-LENGTH', str(len(self._COMPRESSED)).encode('ascii'))], None, 'deflate') out = aiohttp.FlowControlDataQueue(self.stream) @@ -306,6 +321,7 @@ class TestParsePayload(unittest.TestCase): msg = protocol.RawRequestMessage( 'GET', '/', (1, 1), CIMultiDict([('CONTENT-LENGTH', len(self._COMPRESSED))]), + [(b'CONTENT-LENGTH', str(len(self._COMPRESSED)).encode('ascii'))], None, 'deflate') out = aiohttp.FlowControlDataQueue(self.stream) @@ -318,7 +334,9 @@ class TestParsePayload(unittest.TestCase): def test_http_payload_parser_websocket(self): msg = protocol.RawRequestMessage( 'GET', '/', (1, 1), - CIMultiDict([('SEC-WEBSOCKET-KEY1', '13')]), None, None) + CIMultiDict([('SEC-WEBSOCKET-KEY1', '13')]), + [(b'SEC-WEBSOCKET-KEY1', b'13')], + None, None) out = aiohttp.FlowControlDataQueue(self.stream) buf = aiohttp.ParserBuffer() p = protocol.HttpPayloadParser(msg)(out, buf) @@ -330,6 +348,7 @@ class TestParsePayload(unittest.TestCase): msg = protocol.RawRequestMessage( 'GET', '/', (1, 1), CIMultiDict([('TRANSFER-ENCODING', 'chunked')]), + [(b'TRANSFER-ENCODING', b'chunked')], None, None) out = aiohttp.FlowControlDataQueue(self.stream) buf = aiohttp.ParserBuffer() @@ -341,7 +360,7 @@ class TestParsePayload(unittest.TestCase): def test_http_payload_parser_eof(self): msg = protocol.RawRequestMessage( - 'GET', '/', (1, 1), CIMultiDict(), None, None) + 'GET', '/', (1, 1), CIMultiDict(), [], None, None) out = aiohttp.FlowControlDataQueue(self.stream) buf = aiohttp.ParserBuffer() p = protocol.HttpPayloadParser(msg, readall=True)(out, buf) @@ -354,7 +373,9 @@ class TestParsePayload(unittest.TestCase): def test_http_payload_parser_length_zero(self): msg = protocol.RawRequestMessage( 'GET', '/', (1, 1), - CIMultiDict([('CONTENT-LENGTH', '0')]), None, None) + CIMultiDict([('CONTENT-LENGTH', '0')]), + [(b'CONTENT-LENGTH', b'0')], + None, None) out = aiohttp.FlowControlDataQueue(self.stream) buf = aiohttp.ParserBuffer() p = protocol.HttpPayloadParser(msg)(out, buf) @@ -390,7 +411,7 @@ class TestParseRequest(unittest.TestCase): pass result = out._buffer[0][0] self.assertEqual( - ('GET', '/path', (1, 1), CIMultiDict(), False, None), + ('GET', '/path', (1, 1), CIMultiDict(), [], False, None), result) def test_http_request_parser_utf8(self): @@ -407,7 +428,29 @@ class TestParseRequest(unittest.TestCase): self.assertEqual(len(msg), length) self.assertEqual( ('GET', '/path', (1, 1), - CIMultiDict([('X-TEST', 'тест')]), False, None), + CIMultiDict([('X-TEST', 'тест')]), + [(b'X-TEST', 'тест'.encode('utf-8'))], + False, None), + result) + + def test_http_request_parser_non_utf8(self): + out = aiohttp.FlowControlDataQueue(self.stream) + buf = aiohttp.ParserBuffer() + p = protocol.HttpRequestParser()(out, buf) + next(p) + msg = 'get /path HTTP/1.1\r\nx-test:тест\r\n\r\n'.encode('cp1251') + try: + p.send(msg) + except StopIteration: + pass + result, length = out._buffer[0] + self.assertEqual(len(msg), length) + self.assertEqual( + ('GET', '/path', (1, 1), + CIMultiDict([('X-TEST', 'тест'.encode('cp1251').decode( + 'utf-8', 'surrogateescape'))]), + [(b'X-TEST', 'тест'.encode('cp1251'))], + False, None), result) def test_http_request_parser_eof(self): @@ -433,7 +476,7 @@ class TestParseRequest(unittest.TestCase): except StopIteration: pass self.assertEqual( - ('GET', '//path', (1, 1), CIMultiDict(), False, None), + ('GET', '//path', (1, 1), CIMultiDict(), [], False, None), out._buffer[0][0]) def test_http_request_parser_bad_status_line(self): diff --git a/tests/test_multidict.py b/tests/test_multidict.py deleted file mode 100644 index c31e1f4..0000000 --- a/tests/test_multidict.py +++ /dev/null @@ -1,857 +0,0 @@ -import sys -import unittest - -from aiohttp.multidict import (MultiDictProxy, - MultiDict, - CIMultiDictProxy, - CIMultiDict, - upstr, - _MultiDictProxy, - _MultiDict, - _CIMultiDictProxy, - _CIMultiDict, - _upstr) - - -import aiohttp - - -class _Root: - - cls = None - - proxy_cls = None - - upstr_cls = None - - def test_exposed_names(self): - name = self.cls.__name__ - while name.startswith('_'): - name = name[1:] - self.assertIn(name, aiohttp.__all__) - - -class _BaseTest(_Root): - - def test_instantiate__empty(self): - d = self.make_dict() - self.assertEqual(d, {}) - self.assertEqual(len(d), 0) - self.assertEqual(list(d.keys()), []) - self.assertEqual(list(d.values()), []) - self.assertEqual(list(d.values()), []) - self.assertEqual(list(d.items()), []) - self.assertEqual(list(d.items()), []) - - self.assertNotEqual(self.make_dict(), list()) - with self.assertRaisesRegex(TypeError, "\(2 given\)"): - self.make_dict(('key1', 'value1'), ('key2', 'value2')) - - def test_instantiate__from_arg0(self): - d = self.make_dict([('key', 'value1')]) - - self.assertEqual(d, {'key': 'value1'}) - self.assertEqual(len(d), 1) - self.assertEqual(list(d.keys()), ['key']) - self.assertEqual(list(d.values()), ['value1']) - self.assertEqual(list(d.items()), [('key', 'value1')]) - - def test_instantiate__from_arg0_dict(self): - d = self.make_dict({'key': 'value1'}) - - self.assertEqual(d, {'key': 'value1'}) - self.assertEqual(len(d), 1) - self.assertEqual(list(d.keys()), ['key']) - self.assertEqual(list(d.values()), ['value1']) - self.assertEqual(list(d.items()), [('key', 'value1')]) - - def test_instantiate__with_kwargs(self): - d = self.make_dict([('key', 'value1')], key2='value2') - - self.assertEqual(d, {'key': 'value1', 'key2': 'value2'}) - self.assertEqual(len(d), 2) - self.assertEqual(sorted(d.keys()), ['key', 'key2']) - self.assertEqual(sorted(d.values()), ['value1', 'value2']) - self.assertEqual(sorted(d.items()), [('key', 'value1'), - ('key2', 'value2')]) - - def test_getone(self): - d = self.make_dict([('key', 'value1')], key='value2') - self.assertEqual(d.getone('key'), 'value1') - self.assertEqual(d.get('key'), 'value1') - self.assertEqual(d['key'], 'value1') - - with self.assertRaises(KeyError): - d['key2'] - with self.assertRaises(KeyError): - d.getone('key2') - - self.assertEqual('default', d.getone('key2', 'default')) - - def test__iter__(self): - d = self.make_dict([('key', 'one'), ('key2', 'two'), ('key', 3)]) - self.assertEqual(['key', 'key2', 'key'], list(d)) - - def test_keys__contains(self): - d = self.make_dict([('key', 'one'), ('key2', 'two'), ('key', 3)]) - self.assertEqual(list(d.keys()), ['key', 'key2', 'key']) - - self.assertIn('key', d.keys()) - self.assertIn('key2', d.keys()) - - self.assertNotIn('foo', d.keys()) - - def test_values__contains(self): - d = self.make_dict([('key', 'one'), ('key', 'two'), ('key', 3)]) - self.assertEqual(list(d.values()), ['one', 'two', 3]) - - self.assertIn('one', d.values()) - self.assertIn('two', d.values()) - self.assertIn(3, d.values()) - - self.assertNotIn('foo', d.values()) - - def test_items__contains(self): - d = self.make_dict([('key', 'one'), ('key', 'two'), ('key', 3)]) - self.assertEqual(list(d.items()), - [('key', 'one'), ('key', 'two'), ('key', 3)]) - self.assertEqual(list(d.items()), - [('key', 'one'), ('key', 'two'), ('key', 3)]) - - self.assertIn(('key', 'one'), d.items()) - self.assertIn(('key', 'two'), d.items()) - self.assertIn(('key', 3), d.items()) - - self.assertNotIn(('foo', 'bar'), d.items()) - - def test_cannot_create_from_unaccepted(self): - with self.assertRaises(TypeError): - self.make_dict([(1, 2, 3)]) - - def test_keys_is_set_less(self): - d = self.make_dict([('key', 'value1')]) - - self.assertLess(d.keys(), {'key', 'key2'}) - - def test_keys_is_set_less_equal(self): - d = self.make_dict([('key', 'value1')]) - - self.assertLessEqual(d.keys(), {'key'}) - - def test_keys_is_set_equal(self): - d = self.make_dict([('key', 'value1')]) - - self.assertEqual(d.keys(), {'key'}) - - def test_keys_is_set_greater(self): - d = self.make_dict([('key', 'value1')]) - - self.assertGreater({'key', 'key2'}, d.keys()) - - def test_keys_is_set_greater_equal(self): - d = self.make_dict([('key', 'value1')]) - - self.assertGreaterEqual({'key'}, d.keys()) - - def test_keys_is_set_not_equal(self): - d = self.make_dict([('key', 'value1')]) - - self.assertNotEqual(d.keys(), {'key2'}) - - def test_eq(self): - d = self.make_dict([('key', 'value1')]) - self.assertEqual({'key': 'value1'}, d) - - def test_ne(self): - d = self.make_dict([('key', 'value1')]) - self.assertNotEqual(d, {'key': 'another_value'}) - - def test_and(self): - d = self.make_dict([('key', 'value1')]) - self.assertEqual({'key'}, d.keys() & {'key', 'key2'}) - - def test_or(self): - d = self.make_dict([('key', 'value1')]) - self.assertEqual({'key', 'key2'}, d.keys() | {'key2'}) - - def test_sub(self): - d = self.make_dict([('key', 'value1'), ('key2', 'value2')]) - self.assertEqual({'key'}, d.keys() - {'key2'}) - - def test_xor(self): - d = self.make_dict([('key', 'value1'), ('key2', 'value2')]) - self.assertEqual({'key', 'key3'}, d.keys() ^ {'key2', 'key3'}) - - def test_isdisjoint(self): - d = self.make_dict([('key', 'value1')]) - self.assertTrue(d.keys().isdisjoint({'key2'})) - - def test_isdisjoint2(self): - d = self.make_dict([('key', 'value1')]) - self.assertFalse(d.keys().isdisjoint({'key'})) - - def test_repr_issue_410(self): - d = self.make_dict() - try: - raise Exception - self.fail("Sould never happen") # pragma: no cover - except Exception as e: - repr(d) - self.assertIs(sys.exc_info()[1], e) - - def test_or_issue_410(self): - d = self.make_dict([('key', 'value')]) - try: - raise Exception - self.fail("Sould never happen") # pragma: no cover - except Exception as e: - d.keys() | {'other'} - self.assertIs(sys.exc_info()[1], e) - - def test_and_issue_410(self): - d = self.make_dict([('key', 'value')]) - try: - raise Exception - self.fail("Sould never happen") # pragma: no cover - except Exception as e: - d.keys() & {'other'} - self.assertIs(sys.exc_info()[1], e) - - def test_sub_issue_410(self): - d = self.make_dict([('key', 'value')]) - try: - raise Exception - self.fail("Sould never happen") # pragma: no cover - except Exception as e: - d.keys() - {'other'} - self.assertIs(sys.exc_info()[1], e) - - def test_xor_issue_410(self): - d = self.make_dict([('key', 'value')]) - try: - raise Exception - self.fail("Sould never happen") # pragma: no cover - except Exception as e: - d.keys() ^ {'other'} - self.assertIs(sys.exc_info()[1], e) - - -class _MultiDictTests(_BaseTest): - - def test__repr__(self): - d = self.make_dict() - cls = self.proxy_cls if self.proxy_cls is not None else self.cls - - self.assertEqual(str(d), "<%s()>" % cls.__name__) - d = self.make_dict([('key', 'one'), ('key', 'two')]) - self.assertEqual( - str(d), - "<%s('key': 'one', 'key': 'two')>" % cls.__name__) - - def test_getall(self): - d = self.make_dict([('key', 'value1')], key='value2') - - self.assertNotEqual(d, {'key': 'value1'}) - self.assertEqual(len(d), 2) - - self.assertEqual(d.getall('key'), ['value1', 'value2']) - - with self.assertRaisesRegex(KeyError, "some_key"): - d.getall('some_key') - - default = object() - self.assertIs(d.getall('some_key', default), default) - - def test_preserve_stable_ordering(self): - d = self.make_dict([('a', 1), ('b', '2'), ('a', 3)]) - s = '&'.join('{}={}'.format(k, v) for k, v in d.items()) - - self.assertEqual('a=1&b=2&a=3', s) - - def test_get(self): - d = self.make_dict([('a', 1), ('a', 2)]) - self.assertEqual(1, d['a']) - - def test_items__repr__(self): - d = self.make_dict([('key', 'value1')], key='value2') - self.assertEqual(repr(d.items()), - "_ItemsView('key': 'value1', 'key': 'value2')") - - def test_keys__repr__(self): - d = self.make_dict([('key', 'value1')], key='value2') - self.assertEqual(repr(d.keys()), - "_KeysView('key', 'key')") - - def test_values__repr__(self): - d = self.make_dict([('key', 'value1')], key='value2') - self.assertEqual(repr(d.values()), - "_ValuesView('value1', 'value2')") - - -class _CIMultiDictTests(_Root): - - def test_basics(self): - d = self.make_dict([('KEY', 'value1')], KEY='value2') - self.assertEqual(d.getone('key'), 'value1') - self.assertEqual(d.get('key'), 'value1') - self.assertEqual(d.get('key2', 'val'), 'val') - self.assertEqual(d['key'], 'value1') - self.assertIn('key', d) - - with self.assertRaises(KeyError): - d['key2'] - with self.assertRaises(KeyError): - d.getone('key2') - - def test_getall(self): - d = self.make_dict([('KEY', 'value1')], KEY='value2') - - self.assertNotEqual(d, {'KEY': 'value1'}) - self.assertEqual(len(d), 2) - - self.assertEqual(d.getall('key'), ['value1', 'value2']) - - with self.assertRaisesRegex(KeyError, "SOME_KEY"): - d.getall('some_key') - - def test_get(self): - d = self.make_dict([('A', 1), ('a', 2)]) - self.assertEqual(1, d['a']) - - def test_items__repr__(self): - d = self.make_dict([('KEY', 'value1')], key='value2') - self.assertEqual(repr(d.items()), - "_ItemsView('KEY': 'value1', 'KEY': 'value2')") - - def test_keys__repr__(self): - d = self.make_dict([('KEY', 'value1')], key='value2') - self.assertEqual(repr(d.keys()), - "_KeysView('KEY', 'KEY')") - - def test_values__repr__(self): - d = self.make_dict([('KEY', 'value1')], key='value2') - self.assertEqual(repr(d.values()), - "_ValuesView('value1', 'value2')") - - -class _NonProxyCIMultiDict(_CIMultiDictTests): - - def test_extend_with_upstr(self): - us = self.upstr_cls('a') - d = self.make_dict() - - d.extend([(us, 'val')]) - self.assertEqual([('A', 'val')], list(d.items())) - - -class _TestProxy(_MultiDictTests): - - def make_dict(self, *args, **kwargs): - dct = self.cls(*args, **kwargs) - return self.proxy_cls(dct) - - def test_copy(self): - d1 = self.cls(key='value', a='b') - p1 = self.proxy_cls(d1) - - d2 = p1.copy() - self.assertEqual(d1, d2) - self.assertIsNot(d1, d2) - - -class _TestCIProxy(_CIMultiDictTests): - - def make_dict(self, *args, **kwargs): - dct = self.cls(*args, **kwargs) - return self.proxy_cls(dct) - - def test_copy(self): - d1 = self.cls(key='value', a='b') - p1 = self.proxy_cls(d1) - - d2 = p1.copy() - self.assertEqual(d1, d2) - self.assertIsNot(d1, d2) - - -class _BaseMutableMultiDictTests(_BaseTest): - - def test_copy(self): - d1 = self.make_dict(key='value', a='b') - - d2 = d1.copy() - self.assertEqual(d1, d2) - self.assertIsNot(d1, d2) - - def make_dict(self, *args, **kwargs): - return self.cls(*args, **kwargs) - - def test__repr__(self): - d = self.make_dict() - self.assertEqual(str(d), "<%s()>" % self.cls.__name__) - - d = self.make_dict([('key', 'one'), ('key', 'two')]) - - self.assertEqual( - str(d), - "<%s('key': 'one', 'key': 'two')>" % self.cls.__name__) - - def test_getall(self): - d = self.make_dict([('key', 'value1')], key='value2') - self.assertEqual(len(d), 2) - - self.assertEqual(d.getall('key'), ['value1', 'value2']) - - with self.assertRaisesRegex(KeyError, "some_key"): - d.getall('some_key') - - default = object() - self.assertIs(d.getall('some_key', default), default) - - def test_add(self): - d = self.make_dict() - - self.assertEqual(d, {}) - d['key'] = 'one' - self.assertEqual(d, {'key': 'one'}) - self.assertEqual(d.getall('key'), ['one']) - - d['key'] = 'two' - self.assertEqual(d, {'key': 'two'}) - self.assertEqual(d.getall('key'), ['two']) - - d.add('key', 'one') - self.assertEqual(2, len(d)) - self.assertEqual(d.getall('key'), ['two', 'one']) - - d.add('foo', 'bar') - self.assertEqual(3, len(d)) - self.assertEqual(d.getall('foo'), ['bar']) - - def test_extend(self): - d = self.make_dict() - self.assertEqual(d, {}) - - d.extend([('key', 'one'), ('key', 'two')], key=3, foo='bar') - self.assertNotEqual(d, {'key': 'one', 'foo': 'bar'}) - self.assertEqual(4, len(d)) - itms = d.items() - # we can't guarantee order of kwargs - self.assertTrue(('key', 'one') in itms) - self.assertTrue(('key', 'two') in itms) - self.assertTrue(('key', 3) in itms) - self.assertTrue(('foo', 'bar') in itms) - - other = self.make_dict(bar='baz') - self.assertEqual(other, {'bar': 'baz'}) - - d.extend(other) - self.assertIn(('bar', 'baz'), d.items()) - - d.extend({'foo': 'moo'}) - self.assertIn(('foo', 'moo'), d.items()) - - d.extend() - self.assertEqual(6, len(d)) - - with self.assertRaises(TypeError): - d.extend('foo', 'bar') - - def test_extend_from_proxy(self): - d = self.make_dict([('a', 'a'), ('b', 'b')]) - proxy = self.proxy_cls(d) - - d2 = self.make_dict() - d2.extend(proxy) - - self.assertEqual([('a', 'a'), ('b', 'b')], list(d2.items())) - - def test_clear(self): - d = self.make_dict([('key', 'one')], key='two', foo='bar') - - d.clear() - self.assertEqual(d, {}) - self.assertEqual(list(d.items()), []) - - def test_del(self): - d = self.make_dict([('key', 'one'), ('key', 'two')], foo='bar') - - del d['key'] - self.assertEqual(d, {'foo': 'bar'}) - self.assertEqual(list(d.items()), [('foo', 'bar')]) - - with self.assertRaises(KeyError): - del d['key'] - - def test_set_default(self): - d = self.make_dict([('key', 'one'), ('key', 'two')], foo='bar') - self.assertEqual('one', d.setdefault('key', 'three')) - self.assertEqual('three', d.setdefault('otherkey', 'three')) - self.assertIn('otherkey', d) - self.assertEqual('three', d['otherkey']) - - def test_popitem(self): - d = self.make_dict() - d.add('key', 'val1') - d.add('key', 'val2') - - self.assertEqual(('key', 'val1'), d.popitem()) - self.assertEqual([('key', 'val2')], list(d.items())) - - def test_popitem_empty_multidict(self): - d = self.make_dict() - - with self.assertRaises(KeyError): - d.popitem() - - def test_pop(self): - d = self.make_dict() - d.add('key', 'val1') - d.add('key', 'val2') - - self.assertEqual('val1', d.pop('key')) - self.assertFalse(d) - - def test_pop_default(self): - d = self.make_dict(other='val') - - self.assertEqual('default', d.pop('key', 'default')) - self.assertIn('other', d) - - def test_pop_raises(self): - d = self.make_dict(other='val') - - with self.assertRaises(KeyError): - d.pop('key') - - self.assertIn('other', d) - - def test_update(self): - d = self.make_dict() - d.add('key', 'val1') - d.add('key', 'val2') - d.add('key2', 'val3') - - d.update(key='val') - - self.assertEqual([('key2', 'val3'), ('key', 'val')], list(d.items())) - - -class _CIMutableMultiDictTests(_Root): - - def make_dict(self, *args, **kwargs): - return self.cls(*args, **kwargs) - - def test_getall(self): - d = self.make_dict([('KEY', 'value1')], KEY='value2') - - self.assertNotEqual(d, {'KEY': 'value1'}) - self.assertEqual(len(d), 2) - - self.assertEqual(d.getall('key'), ['value1', 'value2']) - - with self.assertRaisesRegex(KeyError, "SOME_KEY"): - d.getall('some_key') - - def test_ctor(self): - d = self.make_dict(k1='v1') - self.assertEqual('v1', d['K1']) - - def test_setitem(self): - d = self.make_dict() - d['k1'] = 'v1' - self.assertEqual('v1', d['K1']) - - def test_delitem(self): - d = self.make_dict() - d['k1'] = 'v1' - self.assertIn('K1', d) - del d['k1'] - self.assertNotIn('K1', d) - - def test_copy(self): - d1 = self.make_dict(key='KEY', a='b') - - d2 = d1.copy() - self.assertEqual(d1, d2) - self.assertIsNot(d1, d2) - - def test__repr__(self): - d = self.make_dict() - self.assertEqual(str(d), "<%s()>" % self.cls.__name__) - - d = self.make_dict([('KEY', 'one'), ('KEY', 'two')]) - - self.assertEqual( - str(d), - "<%s('KEY': 'one', 'KEY': 'two')>" % self.cls.__name__) - - def test_add(self): - d = self.make_dict() - - self.assertEqual(d, {}) - d['KEY'] = 'one' - self.assertEqual(d, {'KEY': 'one'}) - self.assertEqual(d.getall('key'), ['one']) - - d['KEY'] = 'two' - self.assertEqual(d, {'KEY': 'two'}) - self.assertEqual(d.getall('key'), ['two']) - - d.add('KEY', 'one') - self.assertEqual(2, len(d)) - self.assertEqual(d.getall('key'), ['two', 'one']) - - d.add('FOO', 'bar') - self.assertEqual(3, len(d)) - self.assertEqual(d.getall('foo'), ['bar']) - - def test_extend(self): - d = self.make_dict() - self.assertEqual(d, {}) - - d.extend([('KEY', 'one'), ('key', 'two')], key=3, foo='bar') - self.assertNotEqual(d, {'KEY': 'one', 'FOO': 'bar'}) - self.assertEqual(4, len(d)) - itms = d.items() - # we can't guarantee order of kwargs - self.assertTrue(('KEY', 'one') in itms) - self.assertTrue(('KEY', 'two') in itms) - self.assertTrue(('KEY', 3) in itms) - self.assertTrue(('FOO', 'bar') in itms) - - other = self.make_dict(bar='baz') - self.assertEqual(other, {'BAR': 'baz'}) - - d.extend(other) - self.assertIn(('BAR', 'baz'), d.items()) - - d.extend({'FOO': 'moo'}) - self.assertIn(('FOO', 'moo'), d.items()) - - d.extend() - self.assertEqual(6, len(d)) - - with self.assertRaises(TypeError): - d.extend('foo', 'bar') - - def test_extend_from_proxy(self): - d = self.make_dict([('a', 'a'), ('b', 'b')]) - proxy = self.proxy_cls(d) - - d2 = self.make_dict() - d2.extend(proxy) - - self.assertEqual([('A', 'a'), ('B', 'b')], list(d2.items())) - - def test_clear(self): - d = self.make_dict([('KEY', 'one')], key='two', foo='bar') - - d.clear() - self.assertEqual(d, {}) - self.assertEqual(list(d.items()), []) - - def test_del(self): - d = self.make_dict([('KEY', 'one'), ('key', 'two')], foo='bar') - - del d['key'] - self.assertEqual(d, {'FOO': 'bar'}) - self.assertEqual(list(d.items()), [('FOO', 'bar')]) - - with self.assertRaises(KeyError): - del d['key'] - - def test_set_default(self): - d = self.make_dict([('KEY', 'one'), ('key', 'two')], foo='bar') - self.assertEqual('one', d.setdefault('key', 'three')) - self.assertEqual('three', d.setdefault('otherkey', 'three')) - self.assertIn('otherkey', d) - self.assertEqual('three', d['OTHERKEY']) - - def test_popitem(self): - d = self.make_dict() - d.add('KEY', 'val1') - d.add('key', 'val2') - - self.assertEqual(('KEY', 'val1'), d.popitem()) - self.assertEqual([('KEY', 'val2')], list(d.items())) - - def test_popitem_empty_multidict(self): - d = self.make_dict() - - with self.assertRaises(KeyError): - d.popitem() - - def test_pop(self): - d = self.make_dict() - d.add('KEY', 'val1') - d.add('key', 'val2') - - self.assertEqual('val1', d.pop('KEY')) - self.assertFalse(d) - - def test_pop_default(self): - d = self.make_dict(OTHER='val') - - self.assertEqual('default', d.pop('key', 'default')) - self.assertIn('other', d) - - def test_pop_raises(self): - d = self.make_dict(OTHER='val') - - with self.assertRaises(KeyError): - d.pop('KEY') - - self.assertIn('other', d) - - def test_update(self): - d = self.make_dict() - d.add('KEY', 'val1') - d.add('key', 'val2') - d.add('key2', 'val3') - - d.update(key='val') - - self.assertEqual([('KEY2', 'val3'), ('KEY', 'val')], list(d.items())) - - -class TestPyMultiDictProxy(_TestProxy, unittest.TestCase): - - cls = _MultiDict - proxy_cls = _MultiDictProxy - - -class TestPyCIMultiDictProxy(_TestCIProxy, unittest.TestCase): - - cls = _CIMultiDict - proxy_cls = _CIMultiDictProxy - - -class PyMutableMultiDictTests(_BaseMutableMultiDictTests, unittest.TestCase): - - cls = _MultiDict - proxy_cls = _MultiDictProxy - - -class PyCIMutableMultiDictTests(_CIMutableMultiDictTests, _NonProxyCIMultiDict, - unittest.TestCase): - - cls = _CIMultiDict - upstr_cls = _upstr - proxy_cls = _CIMultiDictProxy - - -class TestMultiDictProxy(_TestProxy, unittest.TestCase): - - cls = MultiDict - proxy_cls = MultiDictProxy - - -class TestCIMultiDictProxy(_TestCIProxy, unittest.TestCase): - - cls = CIMultiDict - proxy_cls = CIMultiDictProxy - - -class MutableMultiDictTests(_BaseMutableMultiDictTests, unittest.TestCase): - - cls = MultiDict - proxy_cls = MultiDictProxy - - -class CIMutableMultiDictTests(_CIMutableMultiDictTests, _NonProxyCIMultiDict, - unittest.TestCase): - - cls = CIMultiDict - upstr_cls = upstr - proxy_cls = CIMultiDictProxy - - -class _UpStrMixin: - - cls = None - - def test_ctor(self): - s = self.cls() - self.assertEqual('', s) - - def test_ctor_str(self): - s = self.cls('a') - self.assertEqual('A', s) - - def test_ctor_str_uppercase(self): - s = self.cls('A') - self.assertEqual('A', s) - - def test_ctor_buffer(self): - s = self.cls(b'a') - self.assertEqual('A', s) - - def test_ctor_repr(self): - s = self.cls(None) - self.assertEqual('NONE', s) - - def test_upper(self): - s = self.cls('a') - self.assertIs(s, s.upper()) - - -class TestPyUpStr(_UpStrMixin, unittest.TestCase): - - cls = _upstr - - -class TestUpStr(_UpStrMixin, unittest.TestCase): - - cls = upstr - - -class TypesMixin: - - proxy = ciproxy = mdict = cimdict = None - - def test_proxies(self): - self.assertTrue(issubclass(self.ciproxy, self.proxy)) - - def test_dicts(self): - self.assertTrue(issubclass(self.cimdict, self.mdict)) - - def test_proxy_not_inherited_from_dict(self): - self.assertFalse(issubclass(self.proxy, self.mdict)) - - def test_dict_not_inherited_from_proxy(self): - self.assertFalse(issubclass(self.mdict, self.proxy)) - - def test_create_multidict_proxy_from_nonmultidict(self): - with self.assertRaises(TypeError): - self.proxy({}) - - def test_create_multidict_proxy_from_cimultidict(self): - d = self.cimdict(key='val') - p = self.proxy(d) - self.assertEqual(p, d) - - def test_create_cimultidict_proxy_from_nonmultidict(self): - with self.assertRaises(TypeError): - self.ciproxy({}) - - def test_create_ci_multidict_proxy_from_multidict(self): - d = self.mdict(key='val') - with self.assertRaises(TypeError): - self.ciproxy(d) - - -class TestPyTypes(TypesMixin, unittest.TestCase): - - proxy = _MultiDictProxy - ciproxy = _CIMultiDictProxy - mdict = _MultiDict - cimdict = _CIMultiDict - - -class TestTypes(TypesMixin, unittest.TestCase): - - proxy = MultiDictProxy - ciproxy = CIMultiDictProxy - mdict = MultiDict - cimdict = CIMultiDict diff --git a/tests/test_multipart.py b/tests/test_multipart.py index f63fbb2..b5310f0 100644 --- a/tests/test_multipart.py +++ b/tests/test_multipart.py @@ -7,6 +7,7 @@ import unittest.mock as mock import zlib import aiohttp.multipart +from aiohttp import helpers from aiohttp.helpers import parse_mimetype from aiohttp.hdrs import ( CONTENT_DISPOSITION, @@ -48,7 +49,7 @@ class TestCase(unittest.TestCase, metaclass=MetaAioTestCase): self.loop.close() def future(self, obj): - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result(obj) return fut @@ -69,10 +70,16 @@ class Stream(object): def read(self, size=None): return self.content.read(size) + def at_eof(self): + return self.content.tell() == len(self.content.getbuffer()) + @asyncio.coroutine def readline(self): return self.content.readline() + def unread_data(self, data): + self.content = io.BytesIO(data + self.content.read()) + class StreamWithShortenRead(Stream): @@ -156,11 +163,87 @@ class PartReaderTestCase(TestCase): result = yield from obj.read_chunk() self.assertEqual(b'', result) - def test_read_chunk_requires_content_length(self): + def test_read_chunk_without_content_length(self): obj = aiohttp.multipart.BodyPartReader( self.boundary, {}, Stream(b'Hello, world!\r\n--:')) + c1 = yield from obj.read_chunk(8) + c2 = yield from obj.read_chunk(8) + c3 = yield from obj.read_chunk(8) + self.assertEqual(c1 + c2, b'Hello, world!') + self.assertEqual(c3, b'') + + def test_read_incomplete_chunk(self): + stream = Stream(b'') + + def prepare(data): + f = helpers.create_future(self.loop) + f.set_result(data) + return f + + with mock.patch.object(stream, 'read', side_effect=[ + prepare(b'Hello, '), + prepare(b'World'), + prepare(b'!\r\n--:'), + prepare(b'') + ]): + obj = aiohttp.multipart.BodyPartReader( + self.boundary, {}, stream) + c1 = yield from obj.read_chunk(8) + self.assertEqual(c1, b'Hello, ') + c2 = yield from obj.read_chunk(8) + self.assertEqual(c2, b'World') + c3 = yield from obj.read_chunk(8) + self.assertEqual(c3, b'!') + + def test_read_all_at_once(self): + stream = Stream(b'Hello, World!\r\n--:--\r\n') + obj = aiohttp.multipart.BodyPartReader(self.boundary, {}, stream) + result = yield from obj.read_chunk() + self.assertEqual(b'Hello, World!', result) + result = yield from obj.read_chunk() + self.assertEqual(b'', result) + self.assertTrue(obj.at_eof()) + + def test_read_incomplete_body_chunked(self): + stream = Stream(b'Hello, World!\r\n-') + obj = aiohttp.multipart.BodyPartReader(self.boundary, {}, stream) + result = b'' with self.assertRaises(AssertionError): - yield from obj.read_chunk() + for _ in range(4): + result += yield from obj.read_chunk(7) + self.assertEqual(b'Hello, World!\r\n-', result) + + def test_read_boundary_with_incomplete_chunk(self): + stream = Stream(b'') + + def prepare(data): + f = helpers.create_future(self.loop) + f.set_result(data) + return f + + with mock.patch.object(stream, 'read', side_effect=[ + prepare(b'Hello, World'), + prepare(b'!\r\n'), + prepare(b'--:'), + prepare(b'') + ]): + obj = aiohttp.multipart.BodyPartReader( + self.boundary, {}, stream) + c1 = yield from obj.read_chunk(12) + self.assertEqual(c1, b'Hello, World') + c2 = yield from obj.read_chunk(8) + self.assertEqual(c2, b'!') + c3 = yield from obj.read_chunk(8) + self.assertEqual(c3, b'') + + def test_multi_read_chunk(self): + stream = Stream(b'Hello,\r\n--:\r\n\r\nworld!\r\n--:--') + obj = aiohttp.multipart.BodyPartReader(self.boundary, {}, stream) + result = yield from obj.read_chunk(8) + self.assertEqual(b'Hello,', result) + result = yield from obj.read_chunk(8) + self.assertEqual(b'', result) + self.assertTrue(obj.at_eof()) def test_read_chunk_properly_counts_read_bytes(self): expected = b'.' * 10 @@ -557,7 +640,7 @@ class MultipartReaderTestCase(TestCase): self.assertTrue(second.at_eof()) self.assertIsNone(third) - def test_read_chunk_doesnt_breaks_reader(self): + def test_read_chunk_by_length_doesnt_breaks_reader(self): reader = aiohttp.multipart.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n' @@ -567,12 +650,57 @@ class MultipartReaderTestCase(TestCase): b'Content-Length: 6\r\n\r\n' b'passed' b'\r\n--:--')) + body_parts = [] + while True: + read_part = b'' + part = yield from reader.next() + if part is None: + break + while not part.at_eof(): + read_part += yield from part.read_chunk(3) + body_parts.append(read_part) + self.assertListEqual(body_parts, [b'test', b'passed']) + + def test_read_chunk_from_stream_doesnt_breaks_reader(self): + reader = aiohttp.multipart.MultipartReader( + {CONTENT_TYPE: 'multipart/related;boundary=":"'}, + Stream(b'--:\r\n' + b'\r\n' + b'chunk' + b'\r\n--:\r\n' + b'\r\n' + b'two_chunks' + b'\r\n--:--')) + body_parts = [] while True: + read_part = b'' part = yield from reader.next() if part is None: break while not part.at_eof(): - yield from part.read_chunk(3) + chunk = yield from part.read_chunk(5) + self.assertTrue(chunk) + read_part += chunk + body_parts.append(read_part) + self.assertListEqual(body_parts, [b'chunk', b'two_chunks']) + + def test_reading_skips_prelude(self): + reader = aiohttp.multipart.MultipartReader( + {CONTENT_TYPE: 'multipart/related;boundary=":"'}, + Stream(b'Multi-part data is not supported.\r\n' + b'\r\n' + b'--:\r\n' + b'\r\n' + b'test\r\n' + b'--:\r\n' + b'\r\n' + b'passed\r\n' + b'--:--')) + first = yield from reader.next() + self.assertIsInstance(first, aiohttp.multipart.BodyPartReader) + second = yield from reader.next() + self.assertTrue(first.at_eof()) + self.assertFalse(second.at_eof()) class BodyPartWriterTestCase(unittest.TestCase): diff --git a/tests/test_protocol.py b/tests/test_protocol.py index 42937ef..c66b668 100644 --- a/tests/test_protocol.py +++ b/tests/test_protocol.py @@ -173,13 +173,21 @@ def test_add_headers_hop_headers(transport): assert [] == list(msg.headers) -def test_default_headers(transport): +def test_default_headers_http_10(transport): + msg = protocol.Response(transport, 200, + http_version=protocol.HttpVersion10) + msg._add_default_headers() + + assert 'DATE' in msg.headers + assert 'keep-alive' == msg.headers['CONNECTION'] + + +def test_default_headers_http_11(transport): msg = protocol.Response(transport, 200) msg._add_default_headers() - headers = [r for r, _ in msg.headers.items()] - assert 'DATE' in headers - assert 'CONNECTION' in headers + assert 'DATE' in msg.headers + assert 'CONNECTION' not in msg.headers def test_default_headers_server(transport): @@ -222,8 +230,9 @@ def test_default_headers_connection_close(transport): assert [('CONNECTION', 'close')] == headers -def test_default_headers_connection_keep_alive(transport): - msg = protocol.Response(transport, 200) +def test_default_headers_connection_keep_alive_http_10(transport): + msg = protocol.Response(transport, 200, + http_version=protocol.HttpVersion10) msg.keepalive = True msg._add_default_headers() @@ -231,6 +240,16 @@ def test_default_headers_connection_keep_alive(transport): assert [('CONNECTION', 'keep-alive')] == headers +def test_default_headers_connection_keep_alive_11(transport): + msg = protocol.Response(transport, 200, + http_version=protocol.HttpVersion11) + msg.keepalive = True + msg._add_default_headers() + + headers = [r for r in msg.headers.items() if r[0] == 'CONNECTION'] + assert 'CONNECTION' not in headers + + def test_send_headers(transport): write = transport.write = mock.Mock() diff --git a/tests/test_py35/test_resp.py b/tests/test_py35/test_resp.py index ff6b7d0..cca6426 100644 --- a/tests/test_py35/test_resp.py +++ b/tests/test_py35/test_resp.py @@ -1,3 +1,4 @@ +import asyncio import pytest import aiohttp @@ -53,3 +54,45 @@ async def test_client_api_context_manager(create_server, loop): def test_ctx_manager_is_coroutine(): assert issubclass(_RequestContextManager, Coroutine) + + +@pytest.mark.run_loop +async def test_context_manager_timeout_on_release(create_server, loop): + + async def handler(request): + resp = web.StreamResponse() + await resp.prepare(request) + await asyncio.sleep(10, loop=loop) + return resp + + app, url = await create_server() + app.router.add_route('GET', '/', handler) + + with aiohttp.ClientSession(loop=loop) as session: + resp = await session.get(url+'/') + with pytest.raises(asyncio.TimeoutError): + with aiohttp.Timeout(0.01, loop=loop): + async with resp: + assert resp.status == 200 + assert resp.connection is not None + assert resp.connection is None + + +@pytest.mark.run_loop +async def test_iter_any(create_server, loop): + + data = b'0123456789' * 1024 + + async def handler(request): + buf = [] + async for raw in request.content.iter_any(): + buf.append(raw) + assert b''.join(buf) == data + return web.Response() + + app, url = await create_server() + app.router.add_route('POST', '/', handler) + + with aiohttp.ClientSession(loop=loop) as session: + async with await session.post(url+'/', data=data) as resp: + assert resp.status == 200 diff --git a/tests/test_py35/test_streams_35.py b/tests/test_py35/test_streams_35.py index 83d298a..c6b939e 100644 --- a/tests/test_py35/test_streams_35.py +++ b/tests/test_py35/test_streams_35.py @@ -70,3 +70,10 @@ async def test_data_queue_items(loop): async for item in buffer: assert item is next(item_iter, None) pytest.raises(StopIteration, next, item_iter) + + +@pytest.mark.run_loop +async def test_stream_reader_iter_any(loop): + it = iter([b'line1\nline2\nline3\n']) + async for raw in create_stream(loop).iter_any(): + assert raw == next(it) diff --git a/tests/test_py35/test_web_websocket_35.py b/tests/test_py35/test_web_websocket_35.py index 8dbb198..8ded6c1 100644 --- a/tests/test_py35/test_web_websocket_35.py +++ b/tests/test_py35/test_web_websocket_35.py @@ -1,14 +1,13 @@ import pytest -import asyncio - import aiohttp from aiohttp import web +from aiohttp import helpers @pytest.mark.run_loop async def test_server_ws_async_for(loop, create_server): - closed = asyncio.Future(loop=loop) + closed = helpers.create_future(loop) async def handler(request): ws = web.WebSocketResponse() diff --git a/tests/test_pytest_plugin.py b/tests/test_pytest_plugin.py new file mode 100644 index 0000000..71b6f05 --- /dev/null +++ b/tests/test_pytest_plugin.py @@ -0,0 +1,99 @@ +pytest_plugins = 'pytester' + + +def test_myplugin(testdir): + testdir.makepyfile("""\ +import asyncio +import pytest +from aiohttp import web + +pytest_plugins = 'aiohttp.pytest_plugin' + + +@asyncio.coroutine +def hello(request): + return web.Response(body=b'Hello, world') + + +def create_app(loop): + app = web.Application(loop=loop) + app.router.add_route('GET', '/', hello) + return app + + +@asyncio.coroutine +def test_hello(test_client): + client = yield from test_client(create_app) + resp = yield from client.get('/') + assert resp.status == 200 + text = yield from resp.text() + assert 'Hello, world' in text + + +@asyncio.coroutine +def test_hello_with_loop(test_client, loop): + client = yield from test_client(create_app) + resp = yield from client.get('/') + assert resp.status == 200 + text = yield from resp.text() + assert 'Hello, world' in text + + +@asyncio.coroutine +def test_hello_fails(test_client): + client = yield from test_client(create_app) + resp = yield from client.get('/') + assert resp.status == 200 + text = yield from resp.text() + assert 'Hello, wield' in text + + +@asyncio.coroutine +def test_noop(): + pass + + +@asyncio.coroutine +def previous(request): + if request.method == 'POST': + request.app['value'] = (yield from request.post())['value'] + return web.Response(body=b'thanks for the data') + else: + v = request.app.get('value', 'unknown') + return web.Response(body='value: {}'.format(v).encode()) + + +def create_stateful_app(loop): + app = web.Application(loop=loop) + app.router.add_route('*', '/', previous) + return app + + +@pytest.fixture +def cli(loop, test_client): + return loop.run_until_complete(test_client(create_stateful_app)) + + +@asyncio.coroutine +def test_set_value(cli): + resp = yield from cli.post('/', data={'value': 'foo'}) + assert resp.status == 200 + text = yield from resp.text() + assert text == 'thanks for the data' + assert cli.app['value'] == 'foo' + + +@asyncio.coroutine +def test_get_value(cli): + resp = yield from cli.get('/') + assert resp.status == 200 + text = yield from resp.text() + assert text == 'value: unknown' + cli.app['value'] = 'bar' + resp = yield from cli.get('/') + assert resp.status == 200 + text = yield from resp.text() + assert text == 'value: bar' +""") + result = testdir.runpytest('-p', 'no:sugar') + result.assert_outcomes(passed=5, failed=1) diff --git a/tests/test_resolver.py b/tests/test_resolver.py new file mode 100644 index 0000000..3239e6e --- /dev/null +++ b/tests/test_resolver.py @@ -0,0 +1,114 @@ +import pytest +import asyncio +import socket +import ipaddress +from aiohttp.resolver import AsyncResolver, DefaultResolver +from unittest.mock import patch + +try: + import aiodns +except ImportError: + aiodns = None + + +class FakeResult: + def __init__(self, host): + self.host = host + + +@asyncio.coroutine +def fake_result(result): + return [FakeResult(host=h) + for h in result] + + +def fake_addrinfo(hosts): + @asyncio.coroutine + def fake(*args, **kwargs): + if not hosts: + raise socket.gaierror + + return list([(None, None, None, None, [h, 0]) + for h in hosts]) + + return fake + + +@pytest.mark.skipif(aiodns is None, reason="aiodns required") +def test_async_resolver_positive_lookup(loop): + @asyncio.coroutine + def go(): + with patch('aiodns.DNSResolver.query') as mock_query: + mock_query.return_value = fake_result(['127.0.0.1']) + resolver = AsyncResolver(loop=loop) + real = yield from resolver.resolve('www.python.org') + ipaddress.ip_address(real[0]['host']) + loop.run_until_complete(go()) + + +@pytest.mark.skipif(aiodns is None, reason="aiodns required") +def test_async_resolver_multiple_replies(loop): + @asyncio.coroutine + def go(): + with patch('aiodns.DNSResolver.query') as mock_query: + ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4'] + mock_query.return_value = fake_result(ips) + resolver = AsyncResolver(loop=loop) + real = yield from resolver.resolve('www.google.com') + ips = [ipaddress.ip_address(x['host']) for x in real] + assert len(ips) > 3, "Expecting multiple addresses" + loop.run_until_complete(go()) + + +@pytest.mark.skipif(aiodns is None, reason="aiodns required") +def test_async_negative_lookup(loop): + @asyncio.coroutine + def go(): + with patch('aiodns.DNSResolver.query') as mock_query: + mock_query.side_effect = aiodns.error.DNSError() + resolver = AsyncResolver(loop=loop) + try: + yield from resolver.resolve('doesnotexist.bla') + assert False, "Expecting aiodns.error.DNSError" + except aiodns.error.DNSError: + pass + + loop.run_until_complete(go()) + + +def test_default_resolver_positive_lookup(loop): + @asyncio.coroutine + def go(): + loop.getaddrinfo = fake_addrinfo(["127.0.0.1"]) + resolver = DefaultResolver(loop=loop) + real = yield from resolver.resolve('www.python.org') + ipaddress.ip_address(real[0]['host']) + + loop.run_until_complete(go()) + + +def test_default_resolver_multiple_replies(loop): + @asyncio.coroutine + def go(): + ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4'] + loop.getaddrinfo = fake_addrinfo(ips) + resolver = DefaultResolver(loop=loop) + real = yield from resolver.resolve('www.google.com') + ips = [ipaddress.ip_address(x['host']) for x in real] + assert len(ips) > 3, "Expecting multiple addresses" + loop.run_until_complete(go()) + + +def test_default_negative_lookup(loop): + @asyncio.coroutine + def go(): + ips = [] + loop.getaddrinfo = fake_addrinfo(ips) + resolver = DefaultResolver(loop=loop) + try: + yield from resolver.resolve('doesnotexist.bla') + assert False, "Expecting socket.gaierror" + except socket.gaierror: + pass + + loop.run_until_complete(go()) diff --git a/tests/test_run_app.py b/tests/test_run_app.py new file mode 100644 index 0000000..a616222 --- /dev/null +++ b/tests/test_run_app.py @@ -0,0 +1,61 @@ +import asyncio +import ssl + +from unittest import mock +from aiohttp import web + + +def test_run_app_http(loop): + loop = mock.Mock(spec=asyncio.AbstractEventLoop, wrap=loop) + loop.call_later(0.01, loop.stop) + + app = web.Application(loop=loop) + + web.run_app(app) + + loop.close.assert_called_with() + loop.create_server.assert_called_with(mock.ANY, '0.0.0.0', 8080, + ssl=None, backlog=128) + + +def test_run_app_https(loop): + loop = mock.Mock(spec=asyncio.AbstractEventLoop, wrap=loop) + loop.call_later(0.01, loop.stop) + + app = web.Application(loop=loop) + + ssl_context = ssl.create_default_context() + + web.run_app(app, ssl_context=ssl_context) + + loop.close.assert_called_with() + loop.create_server.assert_called_with(mock.ANY, '0.0.0.0', 8443, + ssl=ssl_context, backlog=128) + + +def test_run_app_nondefault_host_port(loop, unused_port): + port = unused_port + host = 'localhost' + + loop = mock.Mock(spec=asyncio.AbstractEventLoop, wrap=loop) + loop.call_later(0.01, loop.stop) + + app = web.Application(loop=loop) + + web.run_app(app, host=host, port=port) + + loop.create_server.assert_called_with(mock.ANY, host, port, + ssl=None, backlog=128) + + +def test_run_app_custom_backlog(loop): + loop = mock.Mock(spec=asyncio.AbstractEventLoop, wrap=loop) + loop.call_later(0.01, loop.stop) + + app = web.Application(loop=loop) + + web.run_app(app, backlog=10) + + loop.close.assert_called_with() + loop.create_server.assert_called_with(mock.ANY, '0.0.0.0', 8080, + ssl=None, backlog=10) diff --git a/tests/test_server.py b/tests/test_server.py index 7c9c043..6ffae5a 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -9,6 +9,7 @@ from unittest import mock from aiohttp import server from aiohttp import errors +from aiohttp import helpers @pytest.yield_fixture @@ -17,7 +18,8 @@ def make_srv(loop): def maker(**kwargs): nonlocal srv - srv = server.ServerHttpProtocol(loop=loop, **kwargs) + srv = server.ServerHttpProtocol(loop=loop, access_log=None, + **kwargs) return srv yield maker @@ -506,7 +508,7 @@ def test_keep_alive_close_existing(make_srv, loop): srv._keep_alive_period = 15 keep_alive_handle = srv._keep_alive_handle = mock.Mock() srv.handle_request = mock.Mock() - srv.handle_request.return_value = asyncio.Future(loop=loop) + srv.handle_request.return_value = helpers.create_future(loop) srv.handle_request.return_value.set_result(1) srv.data_received( @@ -545,3 +547,34 @@ def test_keep_alive_timeout_default(srv): def test_keep_alive_timeout_nondefault(make_srv): srv = make_srv(keep_alive=10) assert 10 == srv.keep_alive_timeout + + +def test_supports_connect_method(srv, loop): + transport = mock.Mock() + srv.connection_made(transport) + + with mock.patch.object(srv, 'handle_request') as m_handle_request: + srv.reader.feed_data( + b'CONNECT aiohttp.readthedocs.org:80 HTTP/1.0\r\n' + b'Content-Length: 0\r\n\r\n') + + loop.run_until_complete(srv._request_handler) + + assert m_handle_request.called + assert m_handle_request.call_args[0] != (mock.ANY, server.EMPTY_PAYLOAD) + + +def test_content_length_0(srv, loop): + transport = mock.Mock() + srv.connection_made(transport) + + with mock.patch.object(srv, 'handle_request') as m_handle_request: + srv.reader.feed_data( + b'GET / HTTP/1.1\r\n' + b'Host: example.org\r\n' + b'Content-Length: 0\r\n\r\n') + + loop.run_until_complete(srv._request_handler) + + assert m_handle_request.called + assert m_handle_request.call_args[0] == (mock.ANY, server.EMPTY_PAYLOAD) diff --git a/tests/test_signals.py b/tests/test_signals.py index bf96798..4bfeb64 100644 --- a/tests/test_signals.py +++ b/tests/test_signals.py @@ -1,6 +1,6 @@ import asyncio from unittest import mock -from aiohttp.multidict import CIMultiDict +from multidict import CIMultiDict from aiohttp.signals import Signal from aiohttp.web import Application from aiohttp.web import Request, Response @@ -22,6 +22,8 @@ def debug_app(loop): def make_request(app, method, path, headers=CIMultiDict()): message = RawRequestMessage(method, path, HttpVersion11, headers, + [(k.encode('utf-8'), v.encode('utf-8')) + for k, v in headers.items()], False, False) return request_from_message(message, app) @@ -117,9 +119,15 @@ def test_copy_forbidden(app): def test_sort_forbidden(app): - l1 = lambda: None - l2 = lambda: None - l3 = lambda: None + def l1(): + pass + + def l2(): + pass + + def l3(): + pass + signal = Signal(app) signal.extend([l1, l2, l3]) with pytest.raises(NotImplementedError): diff --git a/tests/test_streams.py b/tests/test_streams.py index b760e15..f363ffc 100644 --- a/tests/test_streams.py +++ b/tests/test_streams.py @@ -6,6 +6,7 @@ from unittest import mock from aiohttp import streams from aiohttp import test_utils +from aiohttp import helpers class TestStreamReader(unittest.TestCase): @@ -24,7 +25,7 @@ class TestStreamReader(unittest.TestCase): def test_create_waiter(self): stream = self._make_one() - stream._waiter = asyncio.Future(loop=self.loop) + stream._waiter = helpers.create_future(self.loop) self.assertRaises(RuntimeError, stream._create_waiter, 'test') @mock.patch('aiohttp.streams.asyncio') @@ -371,6 +372,49 @@ class TestStreamReader(unittest.TestCase): self.assertRaises( ValueError, self.loop.run_until_complete, stream.readexactly(2)) + def test_unread_data(self): + stream = self._make_one() + stream.feed_data(b'line1') + stream.feed_data(b'line2') + stream.feed_data(b'onemoreline') + + data = self.loop.run_until_complete(stream.read(5)) + self.assertEqual(b'line1', data) + + stream.unread_data(data) + + data = self.loop.run_until_complete(stream.read(5)) + self.assertEqual(b'line1', data) + + data = self.loop.run_until_complete(stream.read(4)) + self.assertEqual(b'line', data) + + stream.unread_data(b'line1line') + + data = b'' + while len(data) < 10: + data += self.loop.run_until_complete(stream.read(10)) + self.assertEqual(b'line1line2', data) + + data = self.loop.run_until_complete(stream.read(7)) + self.assertEqual(b'onemore', data) + + stream.unread_data(data) + + data = b'' + while len(data) < 11: + data += self.loop.run_until_complete(stream.read(11)) + self.assertEqual(b'onemoreline', data) + + stream.unread_data(b'line') + data = self.loop.run_until_complete(stream.read(4)) + self.assertEqual(b'line', data) + + stream.feed_eof() + stream.unread_data(b'at_eof') + data = self.loop.run_until_complete(stream.read(6)) + self.assertEqual(b'at_eof', data) + def test_exception(self): stream = self._make_one() self.assertIsNone(stream.exception()) diff --git a/tests/test_test_utils.py b/tests/test_test_utils.py new file mode 100644 index 0000000..002e039 --- /dev/null +++ b/tests/test_test_utils.py @@ -0,0 +1,167 @@ +import asyncio +import aiohttp +from aiohttp import web +from aiohttp.test_utils import ( + TestClient, loop_context, + AioHTTPTestCase, unittest_run_loop, + setup_test_loop, teardown_test_loop +) +import pytest + + +def _create_example_app(loop): + + @asyncio.coroutine + def hello(request): + return web.Response(body=b"Hello, world") + + @asyncio.coroutine + def websocket_handler(request): + + ws = web.WebSocketResponse() + yield from ws.prepare(request) + msg = yield from ws.receive() + if msg.tp == aiohttp.MsgType.text: + if msg.data == 'close': + yield from ws.close() + else: + ws.send_str(msg.data + '/answer') + + return ws + + app = web.Application(loop=loop) + app.router.add_route('*', '/', hello) + app.router.add_route('*', '/websocket', websocket_handler) + return app + + +def test_full_server_scenario(): + with loop_context() as loop: + app = _create_example_app(loop) + with TestClient(app) as client: + + @asyncio.coroutine + def test_get_route(): + nonlocal client + resp = yield from client.request("GET", "/") + assert resp.status == 200 + text = yield from resp.text() + assert "Hello, world" in text + + loop.run_until_complete(test_get_route()) + + +def test_server_with_create_test_teardown(): + with loop_context() as loop: + app = _create_example_app(loop) + client = TestClient(app) + + @asyncio.coroutine + def test_get_route(): + resp = yield from client.request("GET", "/") + assert resp.status == 200 + text = yield from resp.text() + assert "Hello, world" in text + + loop.run_until_complete(test_get_route()) + client.close() + + +def test_test_client_close_is_idempotent(): + """ + a test client, called multiple times, should + not attempt to close the loop again. + """ + loop = setup_test_loop() + app = _create_example_app(loop) + client = TestClient(app) + client.close() + teardown_test_loop(loop) + client.close() + + +class TestAioHTTPTestCase(AioHTTPTestCase): + + def get_app(self, loop): + return _create_example_app(loop) + + @unittest_run_loop + @asyncio.coroutine + def test_example_with_loop(self): + request = yield from self.client.request("GET", "/") + assert request.status == 200 + text = yield from request.text() + assert "Hello, world" in text + + def test_example(self): + @asyncio.coroutine + def test_get_route(): + resp = yield from self.client.request("GET", "/") + assert resp.status == 200 + text = yield from resp.text() + assert "Hello, world" in text + + self.loop.run_until_complete(test_get_route()) + + +# these exist to test the pytest scenario +@pytest.yield_fixture +def loop(): + with loop_context() as loop: + yield loop + + +@pytest.fixture +def app(loop): + return _create_example_app(loop) + + +@pytest.yield_fixture +def test_client(loop, app): + client = TestClient(app) + yield client + client.close() + + +def test_get_route(loop, test_client): + @asyncio.coroutine + def test_get_route(): + nonlocal test_client + resp = yield from test_client.request("GET", "/") + assert resp.status == 200 + text = yield from resp.text() + assert "Hello, world" in text + + loop.run_until_complete(test_get_route()) + + +@pytest.mark.run_loop +@asyncio.coroutine +def test_client_websocket(loop, test_client): + resp = yield from test_client.ws_connect("/websocket") + resp.send_str("foo") + msg = yield from resp.receive() + assert msg.tp == aiohttp.MsgType.text + assert "foo" in msg.data + resp.send_str("close") + msg = yield from resp.receive() + assert msg.tp == aiohttp.MsgType.close + + +@pytest.mark.run_loop +@pytest.mark.parametrize("method", [ + "get", "post", "options", "post", "put", "patch", "delete" +]) +@asyncio.coroutine +def test_test_client_methods(method, loop, test_client): + resp = yield from getattr(test_client, method)("/") + assert resp.status == 200 + text = yield from resp.text() + assert "Hello, world" in text + + +@pytest.mark.run_loop +@asyncio.coroutine +def test_test_client_head(loop, test_client): + resp = yield from test_client.head("/") + assert resp.status == 200 diff --git a/tests/test_timeout.py b/tests/test_timeout.py index 58a2441..07e13a5 100644 --- a/tests/test_timeout.py +++ b/tests/test_timeout.py @@ -1,8 +1,9 @@ import asyncio +import os import time import pytest -from aiohttp.helpers import ensure_future, Timeout +from aiohttp.helpers import create_future, ensure_future, Timeout @pytest.mark.run_loop @@ -37,12 +38,12 @@ def test_timeout_finish_in_time(loop): assert resp == 'done' -def test_timeout_gloabal_loop(loop): +def test_timeout_global_loop(loop): asyncio.set_event_loop(loop) @asyncio.coroutine def run(): - with Timeout(0.1) as t: + with Timeout(10) as t: yield from asyncio.sleep(0.01) assert t._loop is loop @@ -50,6 +51,21 @@ def test_timeout_gloabal_loop(loop): @pytest.mark.run_loop +def test_timeout_disable(loop): + @asyncio.coroutine + def long_running_task(): + yield from asyncio.sleep(0.1, loop=loop) + return 'done' + + t0 = loop.time() + with Timeout(None, loop=loop): + resp = yield from long_running_task() + assert resp == 'done' + dt = loop.time() - t0 + assert 0.09 < dt < 0.12, dt + + +@pytest.mark.run_loop def test_timeout_not_relevant_exception(loop): yield from asyncio.sleep(0, loop=loop) with pytest.raises(KeyError): @@ -79,7 +95,7 @@ def test_timeout_blocking_loop(loop): @pytest.mark.run_loop def test_for_race_conditions(loop): - fut = asyncio.Future(loop=loop) + fut = create_future(loop) loop.call_later(0.1, fut.set_result('done')) with Timeout(0.2, loop=loop): resp = yield from fut @@ -99,7 +115,10 @@ def test_timeout_time(loop): finally: foo_running = False - assert abs(0.1 - (loop.time() - start)) < 0.01 + dt = loop.time() - start + if not (0.09 < dt < 0.11) and os.environ.get('APPVEYOR'): + pytest.xfail('appveyor sometimes is toooo sloooow') + assert 0.09 < dt < 0.11 assert not foo_running @@ -132,7 +151,7 @@ def test_outer_coro_is_not_cancelled(loop): @pytest.mark.run_loop def test_cancel_outer_coro(loop): - fut = asyncio.Future(loop=loop) + fut = create_future(loop) @asyncio.coroutine def outer(): @@ -146,3 +165,13 @@ def test_cancel_outer_coro(loop): yield from task assert task.cancelled() assert task.done() + + +@pytest.mark.run_loop +def test_timeout_suppress_exception_chain(loop): + + with pytest.raises(asyncio.TimeoutError) as ctx: + with Timeout(0.01, loop=loop) as t: + yield from asyncio.sleep(10, loop=loop) + assert t._loop is loop + assert ctx.value.__suppress_context__ diff --git a/tests/test_urldispatch.py b/tests/test_urldispatch.py index 11f745c..e7091eb 100644 --- a/tests/test_urldispatch.py +++ b/tests/test_urldispatch.py @@ -1,19 +1,23 @@ import asyncio import os +import pathlib +import re import unittest from collections.abc import Sized, Container, Iterable, Mapping, MutableMapping -from unittest import mock from urllib.parse import unquote import aiohttp.web from aiohttp import hdrs -from aiohttp.web import (UrlDispatcher, Request, Response, - HTTPMethodNotAllowed, HTTPNotFound) -from aiohttp.multidict import CIMultiDict -from aiohttp.protocol import HttpVersion, RawRequestMessage +from aiohttp.web import (UrlDispatcher, Response, + HTTPMethodNotAllowed, HTTPNotFound, + HTTPCreated) from aiohttp.web_urldispatcher import (_defaultExpectHandler, DynamicRoute, PlainRoute, - SystemRoute) + SystemRoute, + ResourceRoute, + AbstractResource, + View) +from aiohttp.test_utils import make_mocked_request class TestUrlDispatcher(unittest.TestCase): @@ -27,16 +31,7 @@ class TestUrlDispatcher(unittest.TestCase): self.loop.close() def make_request(self, method, path): - self.app = mock.Mock() - message = RawRequestMessage(method, path, HttpVersion(1, 1), - CIMultiDict(), False, False) - self.payload = mock.Mock() - self.transport = mock.Mock() - self.reader = mock.Mock() - self.writer = mock.Mock() - req = Request(self.app, message, self.payload, - self.transport, self.reader, self.writer) - return req + return make_mocked_request(method, path) def make_handler(self): @@ -47,7 +42,7 @@ class TestUrlDispatcher(unittest.TestCase): return handler def test_system_route(self): - route = SystemRoute(201, 'test') + route = SystemRoute(HTTPCreated(reason='test')) self.assertIsNone(route.match('any')) with self.assertRaises(RuntimeError): route.url() @@ -241,7 +236,7 @@ class TestUrlDispatcher(unittest.TestCase): def test_route_plain(self): handler = self.make_handler() route = self.router.add_route('GET', '/get', handler, name='name') - route2 = self.router['name'] + route2 = next(iter(self.router['name'])) url = route2.url() self.assertEqual('/get', url) self.assertIs(route, route2) @@ -255,7 +250,7 @@ class TestUrlDispatcher(unittest.TestCase): route = self.router.add_route('GET', '/get/{name}', handler, name='name') - route2 = self.router['name'] + route2 = next(iter(self.router['name'])) url = route2.url(parts={'name': 'John'}) self.assertEqual('/get/John', url) self.assertIs(route, route2) @@ -271,34 +266,34 @@ class TestUrlDispatcher(unittest.TestCase): route = self.router.add_static('/st', os.path.dirname(aiohttp.__file__), name='static') - route2 = self.router['static'] - url = route2.url(filename='/dir/a.txt') + resource = self.router['static'] + url = resource.url(filename='/dir/a.txt') self.assertEqual('/st/dir/a.txt', url) - self.assertIs(route, route2) + self.assertIs(route, next(iter(resource))) def test_plain_not_match(self): handler = self.make_handler() self.router.add_route('GET', '/get/path', handler, name='name') route = self.router['name'] - self.assertIsNone(route.match('/another/path')) + self.assertIsNone(route._match('/another/path')) def test_dynamic_not_match(self): handler = self.make_handler() self.router.add_route('GET', '/get/{name}', handler, name='name') route = self.router['name'] - self.assertIsNone(route.match('/another/path')) + self.assertIsNone(route._match('/another/path')) def test_static_not_match(self): self.router.add_static('/pre', os.path.dirname(aiohttp.__file__), name='name') route = self.router['name'] - self.assertIsNone(route.match('/another/path')) + self.assertIsNone(route._route.match('/another/path')) def test_dynamic_with_trailing_slash(self): handler = self.make_handler() self.router.add_route('GET', '/get/{name}/', handler, name='name') route = self.router['name'] - self.assertEqual({'name': 'John'}, route.match('/get/John/')) + self.assertEqual({'name': 'John'}, route._match('/get/John/')) def test_len(self): handler = self.make_handler() @@ -321,20 +316,21 @@ class TestUrlDispatcher(unittest.TestCase): def test_plain_repr(self): handler = self.make_handler() - self.router.add_route('GET', '/get/path', handler, name='name') - self.assertRegex(repr(self.router['name']), + route = PlainRoute('GET', handler, 'name', '/get/path') + self.assertRegex(repr(route), r"<PlainRoute 'name' \[GET\] /get/path") def test_dynamic_repr(self): handler = self.make_handler() - self.router.add_route('GET', '/get/{path}', handler, name='name') - self.assertRegex(repr(self.router['name']), + route = DynamicRoute('GET', handler, 'name', + 'pattern', '/get/{path}') + self.assertRegex(repr(route), r"<DynamicRoute 'name' \[GET\] /get/{path}") def test_static_repr(self): self.router.add_static('/get', os.path.dirname(aiohttp.__file__), name='name') - self.assertRegex(repr(self.router['name']), + self.assertRegex(repr(next(iter(self.router['name']))), r"<StaticRoute 'name' \[GET\] /get/") def test_static_adds_slash(self): @@ -435,9 +431,10 @@ class TestUrlDispatcher(unittest.TestCase): req = self.make_request('GET', '/get/john') match_info = yield from self.router.resolve(req) + self.assertEqual({'name': 'john'}, match_info) self.maxDiff = None self.assertRegex(repr(match_info), - "<MatchInfo {'name': 'john'}: <DynamicRoute.+>>") + "<MatchInfo {'name': 'john'}: .+<Dynamic.+>>") self.loop.run_until_complete(go()) @@ -447,7 +444,8 @@ class TestUrlDispatcher(unittest.TestCase): def go(): req = self.make_request('POST', '/path/to') match_info = yield from self.router.resolve(req) - self.assertEqual("<MatchInfo: not found>", repr(match_info)) + self.assertEqual("<MatchInfoError 404: Not Found>", + repr(match_info)) self.loop.run_until_complete(go()) @@ -463,8 +461,8 @@ class TestUrlDispatcher(unittest.TestCase): req = self.make_request('PUT', '/path/to') match_info = yield from self.router.resolve(req) - self.assertEqual("<MatchInfo: method PUT is not allowed " - "(allowed methods: GET, POST>", repr(match_info)) + self.assertEqual("<MatchInfoError 405: Method Not Allowed>", + repr(match_info)) self.loop.run_until_complete(go()) @@ -481,7 +479,7 @@ class TestUrlDispatcher(unittest.TestCase): route = self.router.add_route( 'GET', '/', self.make_handler(), expect_handler=handler) self.assertIs(route._expect_handler, handler) - self.assertIsInstance(route, PlainRoute) + self.assertIsInstance(route, ResourceRoute) def test_custom_expect_handler_dynamic(self): @@ -492,7 +490,7 @@ class TestUrlDispatcher(unittest.TestCase): route = self.router.add_route( 'GET', '/get/{name}', self.make_handler(), expect_handler=handler) self.assertIs(route._expect_handler, handler) - self.assertIsInstance(route, DynamicRoute) + self.assertIsInstance(route, ResourceRoute) def test_expect_handler_non_coroutine(self): @@ -567,56 +565,6 @@ class TestUrlDispatcher(unittest.TestCase): handler = self.make_handler() self.router.add_route('INVALID_METHOD', '/path', handler) - def test_static_handle_eof(self): - loop = mock.Mock() - route = self.router.add_static('/st', - os.path.dirname(aiohttp.__file__)) - with mock.patch('aiohttp.web_urldispatcher.os') as m_os: - out_fd = 30 - in_fd = 31 - fut = asyncio.Future(loop=self.loop) - m_os.sendfile.return_value = 0 - route._sendfile_cb(fut, out_fd, in_fd, 0, 100, loop, False) - m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100) - self.assertTrue(fut.done()) - self.assertIsNone(fut.result()) - self.assertFalse(loop.add_writer.called) - self.assertFalse(loop.remove_writer.called) - - def test_static_handle_again(self): - loop = mock.Mock() - route = self.router.add_static('/st', - os.path.dirname(aiohttp.__file__)) - with mock.patch('aiohttp.web_urldispatcher.os') as m_os: - out_fd = 30 - in_fd = 31 - fut = asyncio.Future(loop=self.loop) - m_os.sendfile.side_effect = BlockingIOError() - route._sendfile_cb(fut, out_fd, in_fd, 0, 100, loop, False) - m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100) - self.assertFalse(fut.done()) - loop.add_writer.assert_called_with(out_fd, route._sendfile_cb, - fut, out_fd, in_fd, 0, 100, - loop, True) - self.assertFalse(loop.remove_writer.called) - - def test_static_handle_exception(self): - loop = mock.Mock() - route = self.router.add_static('/st', - os.path.dirname(aiohttp.__file__)) - with mock.patch('aiohttp.web_urldispatcher.os') as m_os: - out_fd = 30 - in_fd = 31 - fut = asyncio.Future(loop=self.loop) - exc = OSError() - m_os.sendfile.side_effect = exc - route._sendfile_cb(fut, out_fd, in_fd, 0, 100, loop, False) - m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100) - self.assertTrue(fut.done()) - self.assertIs(exc, fut.exception()) - self.assertFalse(loop.add_writer.called) - self.assertFalse(loop.remove_writer.called) - def fill_routes(self): route1 = self.router.add_route('GET', '/plain', self.make_handler()) route2 = self.router.add_route('GET', '/variable/{name}', @@ -643,7 +591,7 @@ class TestUrlDispatcher(unittest.TestCase): self.assertIsInstance(self.router.routes(), Iterable) self.assertIsInstance(self.router.routes(), Container) - def fill_named_routes(self): + def fill_named_resources(self): route1 = self.router.add_route('GET', '/plain', self.make_handler(), name='route1') route2 = self.router.add_route('GET', '/variable/{name}', @@ -651,17 +599,255 @@ class TestUrlDispatcher(unittest.TestCase): route3 = self.router.add_static('/static', os.path.dirname(aiohttp.__file__), name='route3') - return route1, route2, route3 + return route1.name, route2.name, route3.name def test_named_routes_abc(self): self.assertIsInstance(self.router.named_routes(), Mapping) self.assertNotIsInstance(self.router.named_routes(), MutableMapping) + def test_named_resources_abc(self): + self.assertIsInstance(self.router.named_resources(), Mapping) + self.assertNotIsInstance(self.router.named_resources(), MutableMapping) + def test_named_routes(self): - named_routes = self.fill_named_routes() + self.fill_named_resources() + + with self.assertWarns(DeprecationWarning): + self.assertEqual(3, len(self.router.named_routes())) + + def test_named_resources(self): + names = self.fill_named_resources() + + self.assertEqual(3, len(self.router.named_resources())) + + for name in names: + self.assertIn(name, self.router.named_routes()) + self.assertIsInstance(self.router.named_routes()[name], + AbstractResource) + + def test_resource_adapter_not_match(self): + route = PlainRoute('GET', lambda req: None, None, '/path') + self.router.register_route(route) + resource = route.resource + self.assertIsNotNone(resource) + self.assertIsNone(resource._route.match('/another/path')) + + def test_resource_adapter_resolve_not_math(self): + route = PlainRoute('GET', lambda req: None, None, '/path') + self.router.register_route(route) + resource = route.resource + self.assertEqual((None, set()), + self.loop.run_until_complete( + resource.resolve('GET', '/another/path'))) + + def test_resource_adapter_resolve_bad_method(self): + route = PlainRoute('POST', lambda req: None, None, '/path') + self.router.register_route(route) + resource = route.resource + self.assertEqual((None, {'POST'}), + self.loop.run_until_complete( + resource.resolve('GET', '/path'))) + + def test_resource_adapter_resolve_wildcard(self): + route = PlainRoute('*', lambda req: None, None, '/path') + self.router.register_route(route) + resource = route.resource + match_info, allowed = self.loop.run_until_complete( + resource.resolve('GET', '/path')) + self.assertEqual(allowed, {'*'}) # TODO: expand wildcard + self.assertIsNotNone(match_info) + + def test_resource_adapter_iter(self): + route = PlainRoute('GET', lambda req: None, None, '/path') + self.router.register_route(route) + resource = route.resource + self.assertEqual(1, len(resource)) + self.assertEqual([route], list(resource)) + + def test_resource_iter(self): + resource = self.router.add_resource('/path') + r1 = resource.add_route('GET', lambda req: None) + r2 = resource.add_route('POST', lambda req: None) + self.assertEqual(2, len(resource)) + self.assertEqual([r1, r2], list(resource)) + + def test_deprecate_bare_generators(self): + resource = self.router.add_resource('/path') + + def gen(request): + yield + + with self.assertWarns(DeprecationWarning): + resource.add_route('GET', gen) + + def test_view_route(self): + resource = self.router.add_resource('/path') + + route = resource.add_route('GET', View) + self.assertIs(View, route.handler) + + def test_resource_route_match(self): + resource = self.router.add_resource('/path') + route = resource.add_route('GET', lambda req: None) + self.assertEqual({}, route.resource._match('/path')) + + def test_plain_route_url(self): + route = PlainRoute('GET', lambda req: None, None, '/path') + self.router.register_route(route) + self.assertEqual('/path?arg=1', route.url(query={'arg': 1})) + + def test_dynamic_route_url(self): + route = DynamicRoute('GET', lambda req: None, None, + '<pattern>', '/{path}') + self.router.register_route(route) + self.assertEqual('/path?arg=1', route.url(parts={'path': 'path'}, + query={'arg': 1})) + + def test_dynamic_route_match_not_found(self): + route = DynamicRoute('GET', lambda req: None, None, + re.compile('/path/(?P<to>.+)'), '/path/{to}') + self.router.register_route(route) + self.assertEqual(None, route.match('/another/path')) + + def test_dynamic_route_match_found(self): + route = DynamicRoute('GET', lambda req: None, None, + re.compile('/path/(?P<to>.+)'), '/path/{to}') + self.router.register_route(route) + self.assertEqual({'to': 'to'}, route.match('/path/to')) + + def test_deprecate_register_route(self): + route = PlainRoute('GET', lambda req: None, None, '/path') + with self.assertWarns(DeprecationWarning): + self.router.register_route(route) - self.assertEqual(3, len(self.router.named_routes())) + def test_error_on_double_route_adding(self): + resource = self.router.add_resource('/path') - for route in named_routes: - self.assertIn(route.name, self.router.named_routes()) - self.assertEqual(route, self.router.named_routes()[route.name]) + resource.add_route('GET', lambda: None) + with self.assertRaises(RuntimeError): + resource.add_route('GET', lambda: None) + + def test_error_on_adding_route_after_wildcard(self): + resource = self.router.add_resource('/path') + + resource.add_route('*', lambda: None) + with self.assertRaises(RuntimeError): + resource.add_route('GET', lambda: None) + + def test_http_exception_is_none_when_resolved(self): + handler = self.make_handler() + self.router.add_route('GET', '/', handler) + req = self.make_request('GET', '/') + info = self.loop.run_until_complete(self.router.resolve(req)) + self.assertIsNone(info.http_exception) + + def test_http_exception_is_not_none_when_not_resolved(self): + handler = self.make_handler() + self.router.add_route('GET', '/', handler) + req = self.make_request('GET', '/abc') + info = self.loop.run_until_complete(self.router.resolve(req)) + self.assertEqual(info.http_exception.status, 404) + + def test_match_info_get_info_plain(self): + handler = self.make_handler() + self.router.add_route('GET', '/', handler) + req = self.make_request('GET', '/') + info = self.loop.run_until_complete(self.router.resolve(req)) + self.assertEqual(info.get_info(), {'path': '/'}) + + def test_match_info_get_info_dynamic(self): + handler = self.make_handler() + self.router.add_route('GET', '/{a}', handler) + req = self.make_request('GET', '/value') + info = self.loop.run_until_complete(self.router.resolve(req)) + self.assertEqual(info.get_info(), + {'pattern': re.compile('^\\/(?P<a>[^{}/]+)$'), + 'formatter': '/{a}'}) + + def test_resource_adapter_get_info(self): + directory = pathlib.Path(aiohttp.__file__).parent + route = self.router.add_static('/st', directory) + self.assertEqual(route.resource.get_info(), {'directory': directory, + 'prefix': '/st/'}) + + def test_plain_old_style_route_get_info(self): + handler = self.make_handler() + route = PlainRoute('GET', handler, 'test', '/handler/to/path') + self.router.register_route(route) + self.assertEqual(route.get_info(), {'path': '/handler/to/path'}) + + def test_dynamic_old_style_get_info(self): + handler = self.make_handler() + route = DynamicRoute('GET', handler, 'name', + '<pattern>', '/get/{path}') + self.router.register_route(route) + self.assertEqual(route.get_info(), {'formatter': '/get/{path}', + 'pattern': '<pattern>'}) + + def test_system_route_get_info(self): + handler = self.make_handler() + self.router.add_route('GET', '/', handler) + req = self.make_request('GET', '/abc') + info = self.loop.run_until_complete(self.router.resolve(req)) + self.assertEqual(info.get_info()['http_exception'].status, 404) + + def fill_resources(self): + resource1 = self.router.add_resource('/plain') + resource2 = self.router.add_resource('/variable/{name}') + return resource1, resource2 + + def test_resources_view_len(self): + self.fill_resources() + self.assertEqual(2, len(self.router.resources())) + + def test_resources_view_iter(self): + resources = self.fill_resources() + self.assertEqual(list(resources), list(self.router.resources())) + + def test_resources_view_contains(self): + resources = self.fill_resources() + for resource in resources: + self.assertIn(resource, self.router.resources()) + + def test_resources_abc(self): + self.assertIsInstance(self.router.resources(), Sized) + self.assertIsInstance(self.router.resources(), Iterable) + self.assertIsInstance(self.router.resources(), Container) + + def test_static_route_user_home(self): + here = pathlib.Path(aiohttp.__file__).parent + home = pathlib.Path(os.path.expanduser('~')) + if not str(here).startswith(str(home)): # pragma: no cover + self.skipTest("aiohttp folder is not placed in user's HOME") + static_dir = '~/' + str(here.relative_to(home)) + route = self.router.add_static('/st', static_dir) + self.assertEqual(here, route.get_info()['directory']) + + def test_static_route_points_to_file(self): + here = pathlib.Path(aiohttp.__file__).parent / '__init__.py' + with self.assertRaises(ValueError): + self.router.add_static('/st', here) + + def test_404_for_resource_adapter(self): + route = self.router.add_static('/st', + os.path.dirname(aiohttp.__file__)) + resource = route.resource + ret = self.loop.run_until_complete( + resource.resolve('GET', '/unknown/path')) + self.assertEqual((None, set()), ret) + + def test_405_for_resource_adapter(self): + route = self.router.add_static('/st', + os.path.dirname(aiohttp.__file__)) + resource = route.resource + ret = self.loop.run_until_complete( + resource.resolve('POST', '/st/abc.py')) + self.assertEqual((None, {'GET'}), ret) + + def test_check_allowed_method_for_found_resource(self): + handler = self.make_handler() + resource = self.router.add_resource('/') + resource.add_route('GET', handler) + ret = self.loop.run_until_complete(resource.resolve('GET', '/')) + self.assertIsNotNone(ret[0]) + self.assertEqual({'GET'}, ret[1]) diff --git a/tests/test_web_application.py b/tests/test_web_application.py index aad060a..e54c5a7 100644 --- a/tests/test_web_application.py +++ b/tests/test_web_application.py @@ -1,7 +1,7 @@ import asyncio import pytest -from aiohttp import web, log +from aiohttp import web, log, helpers from unittest import mock @@ -33,43 +33,43 @@ def test_app_register_on_finish(loop): app = web.Application(loop=loop) cb1 = mock.Mock() cb2 = mock.Mock() - app.register_on_finish(cb1, 1, b=2) - app.register_on_finish(cb2, 2, c=3) - yield from app.finish() - cb1.assert_called_once_with(app, 1, b=2) - cb2.assert_called_once_with(app, 2, c=3) + app.on_cleanup.append(cb1) + app.on_cleanup.append(cb2) + yield from app.cleanup() + cb1.assert_called_once_with(app) + cb2.assert_called_once_with(app) @pytest.mark.run_loop def test_app_register_coro(loop): app = web.Application(loop=loop) - fut = asyncio.Future(loop=loop) + fut = helpers.create_future(loop) @asyncio.coroutine def cb(app): yield from asyncio.sleep(0.001, loop=loop) fut.set_result(123) - app.register_on_finish(cb) - yield from app.finish() + app.on_cleanup.append(cb) + yield from app.cleanup() assert fut.done() assert 123 == fut.result() @pytest.mark.run_loop -def test_app_error_in_finish_callbacks(loop): +def test_app_register_and_finish_are_deprecated(loop, warning): app = web.Application(loop=loop) - - err = RuntimeError('bad call') - app.register_on_finish(mock.Mock(side_effect=err)) - handler = mock.Mock() - loop.set_exception_handler(handler) - yield from app.finish() - exc_info = {'exception': err, - 'application': app, - 'message': 'Error in finish callback'} - handler.assert_called_once_with(loop, exc_info) + cb1 = mock.Mock() + cb2 = mock.Mock() + with warning(DeprecationWarning): + app.register_on_finish(cb1, 1, b=2) + with warning(DeprecationWarning): + app.register_on_finish(cb2, 2, c=3) + with warning(DeprecationWarning): + yield from app.finish() + cb1.assert_called_once_with(app, 1, b=2) + cb2.assert_called_once_with(app, 2, c=3) def test_non_default_router(loop): @@ -82,3 +82,20 @@ def test_non_default_router(loop): app = web.Application(loop=self.loop) app.logger = logger self.assertIs(app.logger, logger) + + +@pytest.mark.run_loop +def test_on_shutdown(loop): + app = web.Application(loop=loop) + called = False + + @asyncio.coroutine + def on_shutdown(app_param): + nonlocal called + assert app is app_param + called = True + + app.on_shutdown.append(on_shutdown) + + yield from app.shutdown() + assert called diff --git a/tests/test_web_cli.py b/tests/test_web_cli.py new file mode 100644 index 0000000..99b7c52 --- /dev/null +++ b/tests/test_web_cli.py @@ -0,0 +1,121 @@ +import pytest + + +from aiohttp import web +from unittest import mock + + +@mock.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) +def test_entry_func_empty(error): + argv = [""] + + with pytest.raises(SystemExit): + web.main(argv) + + error.assert_called_with( + "'entry-func' not in 'module:function' syntax" + ) + + +@mock.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) +def test_entry_func_only_module(error): + argv = ["test"] + + with pytest.raises(SystemExit): + web.main(argv) + + error.assert_called_with( + "'entry-func' not in 'module:function' syntax" + ) + + +@mock.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) +def test_entry_func_only_function(error): + argv = [":test"] + + with pytest.raises(SystemExit): + web.main(argv) + + error.assert_called_with( + "'entry-func' not in 'module:function' syntax" + ) + + +@mock.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) +def test_entry_func_only_seperator(error): + argv = [":"] + + with pytest.raises(SystemExit): + web.main(argv) + + error.assert_called_with( + "'entry-func' not in 'module:function' syntax" + ) + + +@mock.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) +def test_entry_func_relative_module(error): + argv = [".a.b:c"] + + with pytest.raises(SystemExit): + web.main(argv) + + error.assert_called_with("relative module names not supported") + + +@mock.patch("aiohttp.web.import_module", side_effect=ImportError) +@mock.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) +def test_entry_func_non_existent_module(error, import_module): + argv = ["alpha.beta:func"] + + with pytest.raises(SystemExit): + web.main(argv) + + error.assert_called_with("module %r not found" % "alpha.beta") + + +@mock.patch("aiohttp.web.import_module") +@mock.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) +def test_entry_func_non_existent_attribute(error, import_module): + argv = ["alpha.beta:func"] + module = import_module("alpha.beta") + del module.func + + with pytest.raises(SystemExit): + web.main(argv) + + error.assert_called_with( + "module %r has no attribute %r" % ("alpha.beta", "func") + ) + + +@mock.patch("aiohttp.web.run_app") +@mock.patch("aiohttp.web.import_module") +def test_entry_func_call(import_module, run_app): + argv = ("-H testhost -P 6666 --extra-optional-eins alpha.beta:func " + "--extra-optional-zwei extra positional args").split() + module = import_module("alpha.beta") + + with pytest.raises(SystemExit): + web.main(argv) + + module.func.assert_called_with( + ("--extra-optional-eins --extra-optional-zwei extra positional " + "args").split() + ) + + +@mock.patch("aiohttp.web.run_app") +@mock.patch("aiohttp.web.import_module") +@mock.patch("aiohttp.web.ArgumentParser.exit", side_effect=SystemExit) +def test_running_application(exit, import_module, run_app): + argv = ("-H testhost -P 6666 --extra-optional-eins alpha.beta:func " + "--extra-optional-zwei extra positional args").split() + module = import_module("alpha.beta") + app = module.func() + + with pytest.raises(SystemExit): + web.main(argv) + + run_app.assert_called_with(app, host="testhost", port=6666) + exit.assert_called_with(message="Stopped\n") diff --git a/tests/test_web_exceptions.py b/tests/test_web_exceptions.py index 12a15f0..846f0a8 100644 --- a/tests/test_web_exceptions.py +++ b/tests/test_web_exceptions.py @@ -1,8 +1,8 @@ import collections import pytest import re +from multidict import CIMultiDict from unittest import mock -from aiohttp.multidict import CIMultiDict from aiohttp.web import Request from aiohttp.protocol import RawRequestMessage, HttpVersion11 @@ -31,7 +31,7 @@ def request(buf): app = mock.Mock() app._debug = False app.on_response_prepare = signals.Signal(app) - message = RawRequestMessage(method, path, HttpVersion11, headers, + message = RawRequestMessage(method, path, HttpVersion11, headers, [], False, False) req = Request(app, message, payload, transport, reader, writer) @@ -57,7 +57,6 @@ def test_HTTPOk(buf, request): assert re.match(('HTTP/1.1 200 OK\r\n' 'CONTENT-TYPE: text/plain; charset=utf-8\r\n' 'CONTENT-LENGTH: 7\r\n' - 'CONNECTION: keep-alive\r\n' 'DATE: .+\r\n' 'SERVER: .+\r\n\r\n' '200: OK'), txt) @@ -95,7 +94,6 @@ def test_HTTPFound(buf, request): 'CONTENT-TYPE: text/plain; charset=utf-8\r\n' 'CONTENT-LENGTH: 10\r\n' 'LOCATION: /redirect\r\n' - 'CONNECTION: keep-alive\r\n' 'DATE: .+\r\n' 'SERVER: .+\r\n\r\n' '302: Found', txt) @@ -122,7 +120,6 @@ def test_HTTPMethodNotAllowed(buf, request): 'CONTENT-TYPE: text/plain; charset=utf-8\r\n' 'CONTENT-LENGTH: 23\r\n' 'ALLOW: POST,PUT\r\n' - 'CONNECTION: keep-alive\r\n' 'DATE: .+\r\n' 'SERVER: .+\r\n\r\n' '405: Method Not Allowed', txt) @@ -166,3 +163,10 @@ def test_empty_body_205(): def test_empty_body_304(): resp = web.HTTPNoContent() resp.body is None + + +def test_link_header_451(buf, request): + resp = web.HTTPUnavailableForLegalReasons(link='http://warning.or.kr/') + + assert 'http://warning.or.kr/' == resp.link + assert '<http://warning.or.kr/>; rel="blocked-by"' == resp.headers['Link'] diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py index 8fab9d9..7291f6b 100644 --- a/tests/test_web_functional.py +++ b/tests/test_web_functional.py @@ -5,8 +5,10 @@ import os import os.path import socket import unittest +import zlib +from multidict import MultiDict from aiohttp import log, web, request, FormData, ClientSession, TCPConnector -from aiohttp.multidict import MultiDict +from aiohttp.file_sender import FileSender from aiohttp.protocol import HttpVersion, HttpVersion10, HttpVersion11 from aiohttp.streams import EOF_MARKER @@ -41,15 +43,19 @@ class WebFunctionalSetupMixin: return port @asyncio.coroutine - def create_server(self, method, path, handler=None, ssl_ctx=None): - app = web.Application(loop=self.loop) + def create_server(self, method, path, handler=None, ssl_ctx=None, + logger=log.server_logger, handler_kwargs=None): + app = web.Application( + loop=self.loop) if handler: app.router.add_route(method, path, handler) port = self.find_unused_port() self.handler = app.make_handler( keep_alive_on=False, - access_log=log.access_logger) + access_log=log.access_logger, + logger=logger, + **(handler_kwargs or {})) srv = yield from self.loop.create_server( self.handler, '127.0.0.1', port, ssl=ssl_ctx) protocol = "https" if ssl_ctx else "http" @@ -79,6 +85,7 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): self.loop.run_until_complete(go()) def test_handler_returns_not_response(self): + logger = mock.Mock() @asyncio.coroutine def handler(request): @@ -86,13 +93,40 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): @asyncio.coroutine def go(): - _, _, url = yield from self.create_server('GET', '/', handler) + _, _, url = yield from self.create_server('GET', '/', handler, + logger=logger) resp = yield from request('GET', url, loop=self.loop) self.assertEqual(500, resp.status) resp.close() - with mock.patch('aiohttp.server.server_logger'): - self.loop.run_until_complete(go()) + self.loop.run_until_complete(go()) + logger.exception.assert_called_with("Error handling request") + + def test_head_returns_empty_body(self): + + @asyncio.coroutine + def handler(request): + body = yield from request.read() + self.assertEqual(b'', body) + return web.Response(body=b'test') + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('HEAD', '/', handler) + with ClientSession(loop=self.loop) as session: + resp = yield from session.head(url, version=HttpVersion11) + self.assertEqual(200, resp.status) + txt = yield from resp.text() + self.assertEqual('', txt) + resp.close() + + resp = yield from session.head(url, version=HttpVersion11) + self.assertEqual(200, resp.status) + txt = yield from resp.text() + self.assertEqual('', txt) + resp.close() + + self.loop.run_until_complete(go()) def test_post_form(self): @@ -142,8 +176,11 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): def handler(request): data = yield from request.json() self.assertEqual(dct, data) - data2 = yield from request.json() + data2 = yield from request.json(loads=json.loads) self.assertEqual(data, data2) + with self.assertWarns(DeprecationWarning): + data3 = yield from request.json(loader=json.loads) + self.assertEqual(data, data3) resp = web.Response() resp.content_type = 'application/json' resp.body = json.dumps(data).encode('utf8') @@ -357,6 +394,32 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): self.loop.run_until_complete(go()) + def test_expect_default_handler_unknown(self): + """Test default Expect handler for unknown Expect value. + + A server that does not understand or is unable to comply with any of + the expectation values in the Expect field of a request MUST respond + with appropriate error status. The server MUST respond with a 417 + (Expectation Failed) status if any of the expectations cannot be met + or, if there are other problems with the request, some other 4xx + status. + + http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20 + """ + @asyncio.coroutine + def handler(request): + yield from request.post() + self.fail('Handler should not proceed to this point in case of ' + 'unknown Expect header') + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('POST', '/', handler) + resp = yield from request('POST', url, headers={'Expect': 'SPAM'}, + loop=self.loop) + self.assertEqual(417, resp.status) + self.loop.run_until_complete(go()) + def test_100_continue(self): @asyncio.coroutine def handler(request): @@ -520,7 +583,7 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): self.loop.run_until_complete(go()) - def test_http10_keep_alive_default(self): + def test_http11_keep_alive_default(self): @asyncio.coroutine def handler(request): @@ -531,12 +594,31 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): def go(): _, _, url = yield from self.create_server('GET', '/', handler) resp = yield from request('GET', url, loop=self.loop, - version=HttpVersion10) - self.assertEqual('close', resp.headers['CONNECTION']) + version=HttpVersion11) + self.assertNotIn('CONNECTION', resp.headers) resp.close() self.loop.run_until_complete(go()) + def test_http10_keep_alive_default(self): + + @asyncio.coroutine + def handler(request): + yield from request.read() + return web.Response(body=b'OK') + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + with ClientSession(loop=self.loop) as session: + resp = yield from session.get(url, + version=HttpVersion10) + self.assertEqual(resp.version, HttpVersion10) + self.assertEqual('keep-alive', resp.headers['CONNECTION']) + resp.close() + + self.loop.run_until_complete(go()) + def test_http09_keep_alive_default(self): @asyncio.coroutine @@ -551,7 +633,7 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): resp = yield from request('GET', url, loop=self.loop, headers=headers, version=HttpVersion(0, 9)) - self.assertEqual('close', resp.headers['CONNECTION']) + self.assertNotIn('CONNECTION', resp.headers) resp.close() self.loop.run_until_complete(go()) @@ -569,7 +651,7 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): headers = {'Connection': 'close'} resp = yield from request('GET', url, loop=self.loop, headers=headers, version=HttpVersion10) - self.assertEqual('close', resp.headers['CONNECTION']) + self.assertNotIn('CONNECTION', resp.headers) resp.close() self.loop.run_until_complete(go()) @@ -697,6 +779,44 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): self.loop.run_until_complete(go()) + def test_large_header(self): + + @asyncio.coroutine + def handler(request): + return web.Response() + + @asyncio.coroutine + def go(): + _, srv, url = yield from self.create_server('GET', '/', handler) + headers = {'Long-Header': 'ab' * 8129} + resp = yield from request('GET', url, + headers=headers, + loop=self.loop) + self.assertEqual(400, resp.status) + yield from resp.release() + + self.loop.run_until_complete(go()) + + def test_large_header_allowed(self): + + @asyncio.coroutine + def handler(request): + return web.Response() + + @asyncio.coroutine + def go(): + handler_kwargs = {'max_field_size': 81920} + _, srv, url = yield from self.create_server( + 'GET', '/', handler, handler_kwargs=handler_kwargs) + headers = {'Long-Header': 'ab' * 8129} + resp = yield from request('GET', url, + headers=headers, + loop=self.loop) + self.assertEqual(200, resp.status) + yield from resp.release() + + self.loop.run_until_complete(go()) + def test_get_with_empty_arg_with_equal(self): @asyncio.coroutine @@ -714,6 +834,25 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): self.loop.run_until_complete(go()) + def test_response_with_precompressed_body(self): + @asyncio.coroutine + def handler(request): + headers = {'Content-Encoding': 'gzip'} + deflated_data = zlib.compress(b'mydata') + return web.Response(body=deflated_data, headers=headers) + + @asyncio.coroutine + def go(): + _, srv, url = yield from self.create_server('GET', '/', handler) + client = ClientSession(loop=self.loop) + resp = yield from client.get(url) + self.assertEqual(200, resp.status) + data = yield from resp.read() + self.assertEqual(b'mydata', data) + self.assertEqual(resp.headers.get('CONTENT-ENCODING'), 'deflate') + yield from resp.release() + client.close() + def test_stream_response_multiple_chunks(self): @asyncio.coroutine def handler(request): @@ -738,6 +877,18 @@ class TestWebFunctional(WebFunctionalSetupMixin, unittest.TestCase): self.loop.run_until_complete(go()) + def test_start_without_routes(self): + @asyncio.coroutine + def go(): + _, srv, url = yield from self.create_server(None, '/', None) + client = ClientSession(loop=self.loop) + resp = yield from client.get(url) + self.assertEqual(404, resp.status) + yield from resp.release() + client.close() + + self.loop.run_until_complete(go()) + class StaticFileMixin(WebFunctionalSetupMixin): @@ -772,6 +923,10 @@ class StaticFileMixin(WebFunctionalSetupMixin): self.assertEqual(404, resp.status) resp.close() + resp = yield from request('GET', url + 'x' * 500, loop=self.loop) + self.assertEqual(404, resp.status) + resp.close() + resp = yield from request('GET', url + '/../../', loop=self.loop) self.assertEqual(404, resp.status) resp.close() @@ -1019,33 +1174,13 @@ class StaticFileMixin(WebFunctionalSetupMixin): self.loop.run_until_complete(go(here, filename)) - def test_env_nosendfile(self): - directory = os.path.dirname(__file__) - - with mock.patch.dict(os.environ, {'AIOHTTP_NOSENDFILE': '1'}): - route = web.StaticRoute(None, "/", directory) - self.assertEqual(route._sendfile, route._sendfile_fallback) - class TestStaticFileSendfileFallback(StaticFileMixin, unittest.TestCase): - - def patch_sendfile(self, add_static): - def f(*args, **kwargs): - route = add_static(*args, **kwargs) - route._sendfile = route._sendfile_fallback - return route - return f - - -@unittest.skipUnless(hasattr(os, "sendfile"), - "sendfile system call not supported") -class TestStaticFileSendfile(StaticFileMixin, - unittest.TestCase): - def patch_sendfile(self, add_static): def f(*args, **kwargs): route = add_static(*args, **kwargs) - route._sendfile = route._sendfile_system + file_sender = FileSender() + file_sender._sendfile = file_sender._sendfile_fallback return route return f diff --git a/tests/test_web_request.py b/tests/test_web_request.py index 66d5358..ff9692d 100644 --- a/tests/test_web_request.py +++ b/tests/test_web_request.py @@ -1,47 +1,14 @@ import pytest from unittest import mock -from aiohttp.signals import Signal -from aiohttp.web import Request -from aiohttp.multidict import MultiDict, CIMultiDict + +from multidict import MultiDict, CIMultiDict from aiohttp.protocol import HttpVersion -from aiohttp.protocol import RawRequestMessage +from aiohttp.test_utils import make_mocked_request @pytest.fixture def make_request(): - def maker(method, path, headers=CIMultiDict(), *, - version=HttpVersion(1, 1), closing=False, - sslcontext=None, - secure_proxy_ssl_header=None): - if version < HttpVersion(1, 1): - closing = True - app = mock.Mock() - app._debug = False - app.on_response_prepare = Signal(app) - message = RawRequestMessage(method, path, version, headers, closing, - False) - payload = mock.Mock() - transport = mock.Mock() - - def get_extra_info(key): - if key == 'sslcontext': - return sslcontext - else: - return None - - transport.get_extra_info.side_effect = get_extra_info - writer = mock.Mock() - reader = mock.Mock() - req = Request(app, message, payload, - transport, reader, writer, - secure_proxy_ssl_header=secure_proxy_ssl_header) - - assert req.app is app - assert req.content is payload - assert req.transport is transport - - return req - return maker + return make_mocked_request def test_ctor(make_request, warning): @@ -59,11 +26,22 @@ def test_ctor(make_request, warning): # second call should return the same object assert get is req.GET - with warning(DeprecationWarning): - req.payload - assert req.keep_alive + # just make sure that all lines of make_mocked_request covered + reader = mock.Mock() + writer = mock.Mock() + payload = mock.Mock() + transport = mock.Mock() + app = mock.Mock() + req = make_request('GET', '/path/to?a=1&b=2', writer=writer, reader=reader, + payload=payload, transport=transport, app=app) + assert req.app is app + assert req.content is payload + assert req.transport is transport + assert req._reader is reader + assert req._writer is writer + def test_doubleslashes(make_request): req = make_request('GET', '//foo/') @@ -216,6 +194,11 @@ def test___repr__(make_request): assert "<Request GET /path/to >" == repr(req) +def test___repr___non_ascii_path(make_request): + req = make_request('GET', '/path/\U0001f415\U0001f308') + assert "<Request GET /path/\\U0001f415\\U0001f308 >" == repr(req) + + def test_http_scheme(make_request): req = make_request('GET', '/') assert "http" == req.scheme @@ -238,3 +221,9 @@ def test_https_scheme_by_secure_proxy_ssl_header_false_test(make_request): secure_proxy_ssl_header=('X-HEADER', '1'), headers=CIMultiDict({'X-HEADER': '0'})) assert "http" == req.scheme + + +def test_raw_headers(make_request): + req = make_request('GET', '/', + headers=CIMultiDict({'X-HEADER': 'aaa'})) + assert req.raw_headers == ((b'X-HEADER', b'aaa'),) diff --git a/tests/test_web_response.py b/tests/test_web_response.py index dadf0b9..f434caf 100644 --- a/tests/test_web_response.py +++ b/tests/test_web_response.py @@ -3,8 +3,8 @@ import json import pytest import re from unittest import mock +from multidict import CIMultiDict from aiohttp import hdrs, signals -from aiohttp.multidict import CIMultiDict from aiohttp.web import ( ContentCoding, Request, StreamResponse, Response, json_response ) @@ -15,6 +15,8 @@ from aiohttp.protocol import RawRequestMessage def make_request(method, path, headers=CIMultiDict(), version=HttpVersion11, **kwargs): message = RawRequestMessage(method, path, version, headers, + [(k.encode('utf-8'), v.encode('utf-8')) + for k, v in headers.items()], False, False) return request_from_message(message, **kwargs) @@ -539,7 +541,7 @@ def test___repr__not_started(): @pytest.mark.run_loop def test_keep_alive_http10_default(): message = RawRequestMessage('GET', '/', HttpVersion10, CIMultiDict(), - True, False) + [], True, False) req = request_from_message(message) resp = StreamResponse() yield from resp.prepare(req) @@ -550,6 +552,7 @@ def test_keep_alive_http10_default(): def test_keep_alive_http10_switched_on(): headers = CIMultiDict(Connection='keep-alive') message = RawRequestMessage('GET', '/', HttpVersion10, headers, + [(b'Connection', b'keep-alive')], False, False) req = request_from_message(message) resp = StreamResponse() @@ -561,6 +564,7 @@ def test_keep_alive_http10_switched_on(): def test_keep_alive_http09(): headers = CIMultiDict(Connection='keep-alive') message = RawRequestMessage('GET', '/', HttpVersion(0, 9), headers, + [(b'Connection', b'keep-alive')], False, False) req = request_from_message(message) resp = StreamResponse() @@ -809,7 +813,6 @@ def test_send_headers_for_empty_body(): yield from resp.write_eof() txt = buf.decode('utf8') assert re.match('HTTP/1.1 200 OK\r\nCONTENT-LENGTH: 0\r\n' - 'CONNECTION: keep-alive\r\n' 'DATE: .+\r\nSERVER: .+\r\n\r\n', txt) @@ -832,7 +835,6 @@ def test_render_with_body(): yield from resp.write_eof() txt = buf.decode('utf8') assert re.match('HTTP/1.1 200 OK\r\nCONTENT-LENGTH: 4\r\n' - 'CONNECTION: keep-alive\r\n' 'DATE: .+\r\nSERVER: .+\r\n\r\ndata', txt) @@ -857,7 +859,6 @@ def test_send_set_cookie_header(): txt = buf.decode('utf8') assert re.match('HTTP/1.1 200 OK\r\nCONTENT-LENGTH: 0\r\n' 'SET-COOKIE: name=value\r\n' - 'CONNECTION: keep-alive\r\n' 'DATE: .+\r\nSERVER: .+\r\n\r\n', txt) diff --git a/tests/test_web_urldispatcher.py b/tests/test_web_urldispatcher.py new file mode 100644 index 0000000..689bfbc --- /dev/null +++ b/tests/test_web_urldispatcher.py @@ -0,0 +1,65 @@ +import pytest +import os +import shutil +import tempfile +import functools +import asyncio +import aiohttp.web + + +@pytest.fixture(scope='function') +def tmp_dir_path(request): + """ + Give a path for a temporary directory + The directory is destroyed at the end of the test. + """ + # Temporary directory. + tmp_dir = tempfile.mkdtemp() + + def teardown(): + # Delete the whole directory: + shutil.rmtree(tmp_dir) + + request.addfinalizer(teardown) + return tmp_dir + + +@pytest.mark.run_loop +def test_access_root_of_static_handler(tmp_dir_path, create_app_and_client): + """ + Tests the operation of static file server. + Try to access the root of static file server, and make + sure that a proper not found error is returned. + """ + # Put a file inside tmp_dir_path: + my_file_path = os.path.join(tmp_dir_path, 'my_file') + with open(my_file_path, 'w') as fw: + fw.write('hello') + + app, client = yield from create_app_and_client() + + # Register global static route: + app.router.add_static('/', tmp_dir_path) + + # Request the root of the static directory. + # Expect an 404 error page. + r = yield from client.get('/') + assert r.status == 404 + # data = (yield from r.read()) + yield from r.release() + + +@pytest.mark.run_loop +def test_partialy_applied_handler(create_app_and_client): + app, client = yield from create_app_and_client() + + @asyncio.coroutine + def handler(data, request): + return aiohttp.web.Response(body=data) + + app.router.add_route('GET', '/', functools.partial(handler, b'hello')) + + r = yield from client.get('/') + data = (yield from r.read()) + assert data == b'hello' + yield from r.release() diff --git a/tests/test_web_websocket.py b/tests/test_web_websocket.py index 6af3354..cd53ead 100644 --- a/tests/test_web_websocket.py +++ b/tests/test_web_websocket.py @@ -1,7 +1,7 @@ import asyncio import unittest from unittest import mock -from aiohttp import CIMultiDict +from aiohttp import CIMultiDict, helpers from aiohttp.web import ( MsgType, Request, WebSocketResponse, HTTPMethodNotAllowed, HTTPBadRequest) from aiohttp.protocol import RawRequestMessage, HttpVersion11 @@ -32,6 +32,8 @@ class TestWebWebSocket(unittest.TestCase): headers['SEC-WEBSOCKET-PROTOCOL'] = 'chat, superchat' message = RawRequestMessage(method, path, HttpVersion11, headers, + [(k.encode('utf-8'), v.encode('utf-8')) + for k, v in headers.items()], False, False) self.payload = mock.Mock() self.transport = mock.Mock() @@ -275,7 +277,7 @@ class TestWebWebSocket(unittest.TestCase): self.loop.run_until_complete(ws.prepare(req)) exc = ValueError() - res = asyncio.Future(loop=self.loop) + res = helpers.create_future(self.loop) res.set_exception(exc) ws._reader.read.return_value = res @@ -293,7 +295,7 @@ class TestWebWebSocket(unittest.TestCase): ws = WebSocketResponse() self.loop.run_until_complete(ws.prepare(req)) - res = asyncio.Future(loop=self.loop) + res = helpers.create_future(self.loop) res.set_exception(asyncio.CancelledError()) ws._reader.read.return_value = res @@ -306,7 +308,7 @@ class TestWebWebSocket(unittest.TestCase): ws = WebSocketResponse() self.loop.run_until_complete(ws.prepare(req)) - res = asyncio.Future(loop=self.loop) + res = helpers.create_future(self.loop) res.set_exception(asyncio.TimeoutError()) ws._reader.read.return_value = res @@ -320,7 +322,7 @@ class TestWebWebSocket(unittest.TestCase): self.loop.run_until_complete(ws.prepare(req)) exc = errors.ClientDisconnectedError() - res = asyncio.Future(loop=self.loop) + res = helpers.create_future(self.loop) res.set_exception(exc) ws._reader.read.return_value = res @@ -363,7 +365,7 @@ class TestWebWebSocket(unittest.TestCase): self.loop.run_until_complete(ws.prepare(req)) exc = ValueError() - reader.read.return_value = asyncio.Future(loop=self.loop) + reader.read.return_value = helpers.create_future(self.loop) reader.read.return_value.set_exception(exc) self.loop.run_until_complete(ws.close()) @@ -371,7 +373,7 @@ class TestWebWebSocket(unittest.TestCase): self.assertIs(ws.exception(), exc) ws._closed = False - reader.read.return_value = asyncio.Future(loop=self.loop) + reader.read.return_value = helpers.create_future(self.loop) reader.read.return_value.set_exception(asyncio.CancelledError()) self.assertRaises(asyncio.CancelledError, self.loop.run_until_complete, ws.close()) diff --git a/tests/test_web_websocket_functional.py b/tests/test_web_websocket_functional.py index a1e7338..e7c5a5f 100644 --- a/tests/test_web_websocket_functional.py +++ b/tests/test_web_websocket_functional.py @@ -1,439 +1,87 @@ -import asyncio -import base64 -import hashlib -import os -import socket -import unittest - -import aiohttp -from aiohttp import web, websocket - - -WS_KEY = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" - - -class TestWebWebSocketFunctional(unittest.TestCase): +"""HTTP websocket server functional tests""" - def setUp(self): - self.loop = asyncio.new_event_loop() - asyncio.set_event_loop(None) - - def tearDown(self): - self.loop.close() - - def find_unused_port(self): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.bind(('127.0.0.1', 0)) - port = s.getsockname()[1] - s.close() - return port - - @asyncio.coroutine - def create_server(self, method, path, handler): - app = web.Application(loop=self.loop) - app.router.add_route(method, path, handler) +import asyncio +import pytest +from aiohttp import web - port = self.find_unused_port() - srv = yield from self.loop.create_server( - app.make_handler(), '127.0.0.1', port) - url = "http://127.0.0.1:{}".format(port) + path - self.addCleanup(srv.close) - return app, srv, url +@pytest.mark.run_loop +def test_websocket_json(create_app_and_client): @asyncio.coroutine - def connect_ws(self, url, protocol=None): - sec_key = base64.b64encode(os.urandom(16)) - - conn = aiohttp.TCPConnector(loop=self.loop) - self.addCleanup(conn.close) - - headers = { - 'UPGRADE': 'WebSocket', - 'CONNECTION': 'Upgrade', - 'SEC-WEBSOCKET-VERSION': '13', - 'SEC-WEBSOCKET-KEY': sec_key.decode(), - } - - if protocol: - headers['SEC-WEBSOCKET-PROTOCOL'] = protocol - - # send request - response = yield from aiohttp.request( - 'get', url, - headers=headers, - connector=conn, - loop=self.loop) - self.addCleanup(response.close, True) - - self.assertEqual(101, response.status) - self.assertEqual(response.headers.get('upgrade', '').lower(), - 'websocket') - self.assertEqual(response.headers.get('connection', '').lower(), - 'upgrade') - - key = response.headers.get('sec-websocket-accept', '').encode() - match = base64.b64encode(hashlib.sha1(sec_key + WS_KEY).digest()) - self.assertEqual(key, match) - - # switch to websocket protocol - connection = response.connection - reader = connection.reader.set_parser(websocket.WebSocketParser) - writer = websocket.WebSocketWriter(connection.writer) - - return response, reader, writer - - def test_send_recv_text(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse() - yield from ws.prepare(request) - msg = yield from ws.receive_str() - ws.send_str(msg+'/answer') - yield from ws.close() - closed.set_result(1) - return ws - - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, reader, writer = yield from self.connect_ws(url) - writer.send('ask') - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_TEXT) - self.assertEqual('ask/answer', msg.data) - - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_CLOSE) - self.assertEqual(msg.data, 1000) - self.assertEqual(msg.extra, '') - - writer.close() - - yield from closed - resp.close() - - self.loop.run_until_complete(go()) - - def test_send_recv_bytes(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse() - yield from ws.prepare(request) - - msg = yield from ws.receive_bytes() - ws.send_bytes(msg+b'/answer') - yield from ws.close() - closed.set_result(1) - return ws - - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, reader, writer = yield from self.connect_ws(url) - writer.send(b'ask', binary=True) - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_BINARY) - self.assertEqual(b'ask/answer', msg.data) - - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_CLOSE) - self.assertEqual(msg.data, 1000) - self.assertEqual(msg.extra, '') - - writer.close() - yield from closed - resp.close() - - self.loop.run_until_complete(go()) - - def test_auto_pong_with_closing_by_peer(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse() - yield from ws.prepare(request) - yield from ws.receive() - - msg = yield from ws.receive() - self.assertEqual(msg.tp, web.MsgType.close) - self.assertEqual(msg.data, 1000) - self.assertEqual(msg.extra, 'exit message') - closed.set_result(None) - return ws - - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, reader, writer = yield from self.connect_ws(url) - writer.ping() - writer.send('ask') - - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_PONG) - writer.close(1000, 'exit message') - yield from closed - resp.close() - - self.loop.run_until_complete(go()) - - def test_ping(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse() - yield from ws.prepare(request) + def handler(request): + ws = web.WebSocketResponse() + yield from ws.prepare(request) + msg = yield from ws.receive() - ws.ping('data') - yield from ws.receive() - closed.set_result(None) - return ws + msg_json = msg.json() + answer = msg_json['test'] + ws.send_str(answer) - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, reader, writer = yield from self.connect_ws(url) - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_PING) - self.assertEqual(msg.data, b'data') - writer.pong() - writer.close(2, 'exit message') - yield from closed - resp.close() + yield from ws.close() + return ws - self.loop.run_until_complete(go()) + app, client = yield from create_app_and_client() + app.router.add_route('GET', '/', handler) - def test_client_ping(self): + ws = yield from client.ws_connect('/') + expected_value = 'value' + payload = '{"test": "%s"}' % expected_value + ws.send_str(payload) - closed = asyncio.Future(loop=self.loop) + resp = yield from ws.receive() + assert resp.data == expected_value - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse() - yield from ws.prepare(request) - yield from ws.receive() - closed.set_result(None) - return ws - - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, reader, writer = yield from self.connect_ws(url) - writer.ping('data') - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_PONG) - self.assertEqual(msg.data, b'data') - writer.pong() - writer.close() - yield from closed - resp.close() - - self.loop.run_until_complete(go()) - - def test_pong(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse(autoping=False) - yield from ws.prepare(request) - - msg = yield from ws.receive() - self.assertEqual(msg.tp, web.MsgType.ping) - ws.pong('data') - - msg = yield from ws.receive() - self.assertEqual(msg.tp, web.MsgType.close) - self.assertEqual(msg.data, 1000) - self.assertEqual(msg.extra, 'exit message') - closed.set_result(None) - return ws - - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, reader, writer = yield from self.connect_ws(url) - writer.ping('data') - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_PONG) - self.assertEqual(msg.data, b'data') - writer.close(1000, 'exit message') - - yield from closed - resp.close() - - self.loop.run_until_complete(go()) - - def test_change_status(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse() - ws.set_status(200) - self.assertEqual(200, ws.status) - yield from ws.prepare(request) - self.assertEqual(101, ws.status) - yield from ws.close() - closed.set_result(None) - return ws - - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, _, writer = yield from self.connect_ws(url) - writer.close() - yield from closed - resp.close() - - self.loop.run_until_complete(go()) - - def test_handle_protocol(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse(protocols=('foo', 'bar')) - yield from ws.prepare(request) - yield from ws.close() - self.assertEqual('bar', ws.protocol) - closed.set_result(None) - return ws - - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, _, writer = yield from self.connect_ws(url, 'eggs, bar') - writer.close() - - yield from closed - resp.close() - - self.loop.run_until_complete(go()) - - def test_server_close_handshake(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse(protocols=('foo', 'bar')) - yield from ws.prepare(request) - yield from ws.close() - closed.set_result(None) - return ws - - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, reader, writer = yield from self.connect_ws(url, 'eggs, bar') - - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_CLOSE) - writer.close() - yield from closed - resp.close() - - self.loop.run_until_complete(go()) - - def test_client_close_handshake(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse( - autoclose=False, protocols=('foo', 'bar')) - yield from ws.prepare(request) - - msg = yield from ws.receive() - self.assertEqual(msg.tp, web.MsgType.close) - self.assertFalse(ws.closed) - yield from ws.close() - self.assertTrue(ws.closed) - self.assertEqual(ws.close_code, 1007) - - msg = yield from ws.receive() - self.assertEqual(msg.tp, web.MsgType.closed) - - closed.set_result(None) - return ws - - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp, reader, writer = yield from self.connect_ws(url, 'eggs, bar') - - writer.close(code=1007) - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_CLOSE) - yield from closed - resp.close() - - self.loop.run_until_complete(go()) - - def test_server_close_handshake_server_eats_client_messages(self): - - closed = asyncio.Future(loop=self.loop) - - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse(protocols=('foo', 'bar')) - yield from ws.prepare(request) +@pytest.mark.run_loop +def test_websocket_json_invalid_message(create_app_and_client): + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse() + yield from ws.prepare(request) + msg = yield from ws.receive() + + try: + msg.json() + except ValueError: + ws.send_str("ValueError raised: '%s'" % msg.data) + else: + raise Exception("No ValueError was raised") + finally: yield from ws.close() - closed.set_result(None) - return ws + return ws - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - response, reader, writer = yield from self.connect_ws( - url, 'eggs, bar') + app, client = yield from create_app_and_client() + app.router.add_route('GET', '/', handler) - msg = yield from reader.read() - self.assertEqual(msg.tp, websocket.MSG_CLOSE) + ws = yield from client.ws_connect('/') + payload = 'NOT A VALID JSON STRING' + ws.send_str(payload) - writer.send('text') - writer.send(b'bytes', binary=True) - writer.ping() + resp = yield from ws.receive() + assert payload in resp.data - writer.close() - yield from closed - response.close() +@pytest.mark.run_loop +def test_websocket_receive_json(create_app_and_client): + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse() + yield from ws.prepare(request) - self.loop.run_until_complete(go()) + data = yield from ws.receive_json() + answer = data['test'] + ws.send_str(answer) - def test_receive_msg(self): - @asyncio.coroutine - def handler(request): - ws = web.WebSocketResponse() - yield from ws.prepare(request) + yield from ws.close() + return ws - with self.assertWarns(DeprecationWarning): - msg = yield from ws.receive_msg() - self.assertEqual(msg.data, b'data') - yield from ws.close() - return ws + app, client = yield from create_app_and_client() + app.router.add_route('GET', '/', handler) - @asyncio.coroutine - def go(): - _, _, url = yield from self.create_server('GET', '/', handler) - resp = yield from aiohttp.ws_connect(url, loop=self.loop) - resp.send_bytes(b'data') - yield from resp.close() + ws = yield from client.ws_connect('/') + expected_value = 'value' + payload = '{"test": "%s"}' % expected_value + ws.send_str(payload) - self.loop.run_until_complete(go()) + resp = yield from ws.receive() + assert resp.data == expected_value diff --git a/tests/test_web_websocket_functional_oldstyle.py b/tests/test_web_websocket_functional_oldstyle.py new file mode 100644 index 0000000..cf3dd2b --- /dev/null +++ b/tests/test_web_websocket_functional_oldstyle.py @@ -0,0 +1,439 @@ +import asyncio +import base64 +import hashlib +import os +import socket +import unittest + +import aiohttp +from aiohttp import helpers, web, websocket + + +WS_KEY = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + +class TestWebWebSocketFunctional(unittest.TestCase): + + def setUp(self): + self.loop = asyncio.new_event_loop() + asyncio.set_event_loop(None) + + def tearDown(self): + self.loop.close() + + def find_unused_port(self): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(('127.0.0.1', 0)) + port = s.getsockname()[1] + s.close() + return port + + @asyncio.coroutine + def create_server(self, method, path, handler): + app = web.Application(loop=self.loop) + app.router.add_route(method, path, handler) + + port = self.find_unused_port() + srv = yield from self.loop.create_server( + app.make_handler(), '127.0.0.1', port) + url = "http://127.0.0.1:{}".format(port) + path + self.addCleanup(srv.close) + return app, srv, url + + @asyncio.coroutine + def connect_ws(self, url, protocol=None): + sec_key = base64.b64encode(os.urandom(16)) + + conn = aiohttp.TCPConnector(loop=self.loop) + self.addCleanup(conn.close) + + headers = { + 'UPGRADE': 'WebSocket', + 'CONNECTION': 'Upgrade', + 'SEC-WEBSOCKET-VERSION': '13', + 'SEC-WEBSOCKET-KEY': sec_key.decode(), + } + + if protocol: + headers['SEC-WEBSOCKET-PROTOCOL'] = protocol + + # send request + response = yield from aiohttp.request( + 'get', url, + headers=headers, + connector=conn, + loop=self.loop) + self.addCleanup(response.close, True) + + self.assertEqual(101, response.status) + self.assertEqual(response.headers.get('upgrade', '').lower(), + 'websocket') + self.assertEqual(response.headers.get('connection', '').lower(), + 'upgrade') + + key = response.headers.get('sec-websocket-accept', '').encode() + match = base64.b64encode(hashlib.sha1(sec_key + WS_KEY).digest()) + self.assertEqual(key, match) + + # switch to websocket protocol + connection = response.connection + reader = connection.reader.set_parser(websocket.WebSocketParser) + writer = websocket.WebSocketWriter(connection.writer) + + return response, reader, writer + + def test_send_recv_text(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse() + yield from ws.prepare(request) + msg = yield from ws.receive_str() + ws.send_str(msg+'/answer') + yield from ws.close() + closed.set_result(1) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, reader, writer = yield from self.connect_ws(url) + writer.send('ask') + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_TEXT) + self.assertEqual('ask/answer', msg.data) + + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_CLOSE) + self.assertEqual(msg.data, 1000) + self.assertEqual(msg.extra, '') + + writer.close() + + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_send_recv_bytes(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse() + yield from ws.prepare(request) + + msg = yield from ws.receive_bytes() + ws.send_bytes(msg+b'/answer') + yield from ws.close() + closed.set_result(1) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, reader, writer = yield from self.connect_ws(url) + writer.send(b'ask', binary=True) + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_BINARY) + self.assertEqual(b'ask/answer', msg.data) + + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_CLOSE) + self.assertEqual(msg.data, 1000) + self.assertEqual(msg.extra, '') + + writer.close() + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_auto_pong_with_closing_by_peer(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse() + yield from ws.prepare(request) + yield from ws.receive() + + msg = yield from ws.receive() + self.assertEqual(msg.tp, web.MsgType.close) + self.assertEqual(msg.data, 1000) + self.assertEqual(msg.extra, 'exit message') + closed.set_result(None) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, reader, writer = yield from self.connect_ws(url) + writer.ping() + writer.send('ask') + + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_PONG) + writer.close(1000, 'exit message') + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_ping(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse() + yield from ws.prepare(request) + + ws.ping('data') + yield from ws.receive() + closed.set_result(None) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, reader, writer = yield from self.connect_ws(url) + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_PING) + self.assertEqual(msg.data, b'data') + writer.pong() + writer.close(2, 'exit message') + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_client_ping(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse() + yield from ws.prepare(request) + + yield from ws.receive() + closed.set_result(None) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, reader, writer = yield from self.connect_ws(url) + writer.ping('data') + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_PONG) + self.assertEqual(msg.data, b'data') + writer.pong() + writer.close() + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_pong(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse(autoping=False) + yield from ws.prepare(request) + + msg = yield from ws.receive() + self.assertEqual(msg.tp, web.MsgType.ping) + ws.pong('data') + + msg = yield from ws.receive() + self.assertEqual(msg.tp, web.MsgType.close) + self.assertEqual(msg.data, 1000) + self.assertEqual(msg.extra, 'exit message') + closed.set_result(None) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, reader, writer = yield from self.connect_ws(url) + writer.ping('data') + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_PONG) + self.assertEqual(msg.data, b'data') + writer.close(1000, 'exit message') + + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_change_status(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse() + ws.set_status(200) + self.assertEqual(200, ws.status) + yield from ws.prepare(request) + self.assertEqual(101, ws.status) + yield from ws.close() + closed.set_result(None) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, _, writer = yield from self.connect_ws(url) + writer.close() + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_handle_protocol(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse(protocols=('foo', 'bar')) + yield from ws.prepare(request) + yield from ws.close() + self.assertEqual('bar', ws.protocol) + closed.set_result(None) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, _, writer = yield from self.connect_ws(url, 'eggs, bar') + writer.close() + + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_server_close_handshake(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse(protocols=('foo', 'bar')) + yield from ws.prepare(request) + yield from ws.close() + closed.set_result(None) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, reader, writer = yield from self.connect_ws(url, 'eggs, bar') + + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_CLOSE) + writer.close() + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_client_close_handshake(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse( + autoclose=False, protocols=('foo', 'bar')) + yield from ws.prepare(request) + + msg = yield from ws.receive() + self.assertEqual(msg.tp, web.MsgType.close) + self.assertFalse(ws.closed) + yield from ws.close() + self.assertTrue(ws.closed) + self.assertEqual(ws.close_code, 1007) + + msg = yield from ws.receive() + self.assertEqual(msg.tp, web.MsgType.closed) + + closed.set_result(None) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp, reader, writer = yield from self.connect_ws(url, 'eggs, bar') + + writer.close(code=1007) + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_CLOSE) + yield from closed + resp.close() + + self.loop.run_until_complete(go()) + + def test_server_close_handshake_server_eats_client_messages(self): + + closed = helpers.create_future(self.loop) + + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse(protocols=('foo', 'bar')) + yield from ws.prepare(request) + yield from ws.close() + closed.set_result(None) + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + response, reader, writer = yield from self.connect_ws( + url, 'eggs, bar') + + msg = yield from reader.read() + self.assertEqual(msg.tp, websocket.MSG_CLOSE) + + writer.send('text') + writer.send(b'bytes', binary=True) + writer.ping() + + writer.close() + yield from closed + + response.close() + + self.loop.run_until_complete(go()) + + def test_receive_msg(self): + @asyncio.coroutine + def handler(request): + ws = web.WebSocketResponse() + yield from ws.prepare(request) + + with self.assertWarns(DeprecationWarning): + msg = yield from ws.receive_msg() + self.assertEqual(msg.data, b'data') + yield from ws.close() + return ws + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('GET', '/', handler) + resp = yield from aiohttp.ws_connect(url, loop=self.loop) + resp.send_bytes(b'data') + yield from resp.close() + + self.loop.run_until_complete(go()) diff --git a/tests/test_websendfile.py b/tests/test_websendfile.py new file mode 100644 index 0000000..d4b539c --- /dev/null +++ b/tests/test_websendfile.py @@ -0,0 +1,71 @@ +import asyncio +import os +import unittest +from unittest import mock +from aiohttp import helpers +from aiohttp.web import UrlDispatcher +from aiohttp.file_sender import FileSender + + +class TestWebSendFile(unittest.TestCase): + def setUp(self): + self.loop = asyncio.new_event_loop() + asyncio.set_event_loop(None) + self.router = UrlDispatcher() + + def tearDown(self): + self.loop.close() + + def test_env_nosendfile(self): + with mock.patch.dict(os.environ, {'AIOHTTP_NOSENDFILE': '1'}): + file_sender = FileSender() + self.assertEqual(file_sender._sendfile, + file_sender._sendfile_fallback) + + def test_static_handle_eof(self): + loop = mock.Mock() + with mock.patch('aiohttp.file_sender.os') as m_os: + out_fd = 30 + in_fd = 31 + fut = helpers.create_future(self.loop) + m_os.sendfile.return_value = 0 + file_sender = FileSender() + file_sender._sendfile_cb(fut, out_fd, in_fd, 0, 100, loop, False) + m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100) + self.assertTrue(fut.done()) + self.assertIsNone(fut.result()) + self.assertFalse(loop.add_writer.called) + self.assertFalse(loop.remove_writer.called) + + def test_static_handle_again(self): + loop = mock.Mock() + with mock.patch('aiohttp.file_sender.os') as m_os: + out_fd = 30 + in_fd = 31 + fut = helpers.create_future(self.loop) + m_os.sendfile.side_effect = BlockingIOError() + file_sender = FileSender() + file_sender._sendfile_cb(fut, out_fd, in_fd, 0, 100, loop, False) + m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100) + self.assertFalse(fut.done()) + loop.add_writer.assert_called_with(out_fd, + file_sender._sendfile_cb, + fut, out_fd, in_fd, 0, 100, + loop, True) + self.assertFalse(loop.remove_writer.called) + + def test_static_handle_exception(self): + loop = mock.Mock() + with mock.patch('aiohttp.file_sender.os') as m_os: + out_fd = 30 + in_fd = 31 + fut = helpers.create_future(self.loop) + exc = OSError() + m_os.sendfile.side_effect = exc + file_sender = FileSender() + file_sender._sendfile_cb(fut, out_fd, in_fd, 0, 100, loop, False) + m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100) + self.assertTrue(fut.done()) + self.assertIs(exc, fut.exception()) + self.assertFalse(loop.add_writer.called) + self.assertFalse(loop.remove_writer.called) diff --git a/tests/test_websocket_client.py b/tests/test_websocket_client.py index 07176e4..3aeb022 100644 --- a/tests/test_websocket_client.py +++ b/tests/test_websocket_client.py @@ -6,7 +6,7 @@ import unittest from unittest import mock import aiohttp -from aiohttp import errors, hdrs, websocket, websocket_client +from aiohttp import errors, hdrs, helpers, websocket, websocket_client class TestWebSocketClient(unittest.TestCase): @@ -35,7 +35,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_PROTOCOL: 'chat' } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) res = self.loop.run_until_complete( @@ -54,7 +54,7 @@ class TestWebSocketClient(unittest.TestCase): resp = mock.Mock() resp.status = 403 m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) origin = 'https://example.org/page.html' @@ -84,7 +84,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key, } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) res = self.loop.run_until_complete( @@ -108,7 +108,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) resp = self.loop.run_until_complete( @@ -128,7 +128,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) with self.assertRaises(errors.WSServerHandshakeError) as ctx: @@ -151,7 +151,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) with self.assertRaises(errors.WSServerHandshakeError) as ctx: @@ -174,7 +174,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) with self.assertRaises(errors.WSServerHandshakeError) as ctx: @@ -197,7 +197,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: 'asdfasdfasdfasdfasdfasdf' } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) with self.assertRaises(errors.WSServerHandshakeError) as ctx: @@ -221,7 +221,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key, } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) writer = WebSocketWriter.return_value = mock.Mock() reader = resp.connection.reader.set_parser.return_value = mock.Mock() @@ -231,7 +231,7 @@ class TestWebSocketClient(unittest.TestCase): self.assertFalse(resp.closed) msg = websocket.Message(websocket.MSG_CLOSE, b'', b'') - reader.read.return_value = asyncio.Future(loop=self.loop) + reader.read.return_value = helpers.create_future(self.loop) reader.read.return_value.set_result(msg) res = self.loop.run_until_complete(resp.close()) @@ -257,7 +257,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key, } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) WebSocketWriter.return_value = mock.Mock() reader = resp.connection.reader.set_parser.return_value = mock.Mock() @@ -268,7 +268,7 @@ class TestWebSocketClient(unittest.TestCase): self.assertFalse(resp.closed) exc = ValueError() - reader.read.return_value = asyncio.Future(loop=self.loop) + reader.read.return_value = helpers.create_future(self.loop) reader.read.return_value.set_exception(exc) self.loop.run_until_complete(resp.close()) @@ -287,7 +287,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key, } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) writer = WebSocketWriter.return_value = mock.Mock() resp.connection.reader.set_parser.return_value = mock.Mock() @@ -321,7 +321,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key, } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) WebSocketWriter.return_value = mock.Mock() @@ -347,7 +347,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key, } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) WebSocketWriter.return_value = mock.Mock() @@ -370,7 +370,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key, } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(hresp) WebSocketWriter.return_value = mock.Mock() reader = hresp.connection.reader.set_parser.return_value = mock.Mock() @@ -380,7 +380,7 @@ class TestWebSocketClient(unittest.TestCase): 'http://test.org', loop=self.loop)) exc = ValueError() - reader.read.return_value = asyncio.Future(loop=self.loop) + reader.read.return_value = helpers.create_future(self.loop) reader.read.return_value.set_exception(exc) msg = self.loop.run_until_complete(resp.receive()) @@ -407,7 +407,7 @@ class TestWebSocketClient(unittest.TestCase): hdrs.SEC_WEBSOCKET_ACCEPT: self.ws_key } m_os.urandom.return_value = self.key_data - m_req.return_value = asyncio.Future(loop=self.loop) + m_req.return_value = helpers.create_future(self.loop) m_req.return_value.set_result(resp) with self.assertRaises(errors.WSServerHandshakeError): diff --git a/tests/test_websocket_client_functional.py b/tests/test_websocket_client_functional.py index 335722c..c699235 100644 --- a/tests/test_websocket_client_functional.py +++ b/tests/test_websocket_client_functional.py @@ -1,7 +1,7 @@ import aiohttp import asyncio import pytest -from aiohttp import web +from aiohttp import helpers, hdrs, web @pytest.mark.run_loop @@ -55,7 +55,7 @@ def test_send_recv_bytes(create_app_and_client): @pytest.mark.run_loop def test_ping_pong(create_app_and_client, loop): - closed = asyncio.Future(loop=loop) + closed = helpers.create_future(loop) @asyncio.coroutine def handler(request): @@ -92,7 +92,7 @@ def test_ping_pong(create_app_and_client, loop): @pytest.mark.run_loop def test_ping_pong_manual(create_app_and_client, loop): - closed = asyncio.Future(loop=loop) + closed = helpers.create_future(loop) @asyncio.coroutine def handler(request): @@ -163,7 +163,7 @@ def test_close(create_app_and_client): @pytest.mark.run_loop def test_close_from_server(create_app_and_client, loop): - closed = asyncio.Future(loop=loop) + closed = helpers.create_future(loop) @asyncio.coroutine def handler(request): @@ -196,7 +196,7 @@ def test_close_from_server(create_app_and_client, loop): @pytest.mark.run_loop def test_close_manual(create_app_and_client, loop): - closed = asyncio.Future(loop=loop) + closed = helpers.create_future(loop) @asyncio.coroutine def handler(request): @@ -283,3 +283,46 @@ def test_close_cancel(create_app_and_client, loop): yield from asyncio.sleep(0.1, loop=loop) assert resp.closed assert resp.exception() is None + + +@pytest.mark.run_loop +def test_override_default_headers(create_app_and_client, loop): + + @asyncio.coroutine + def handler(request): + assert request.headers[hdrs.SEC_WEBSOCKET_VERSION] == '8' + ws = web.WebSocketResponse() + yield from ws.prepare(request) + + ws.send_str('answer') + yield from ws.close() + return ws + + app, client = yield from create_app_and_client() + app.router.add_route('GET', '/', handler) + headers = {hdrs.SEC_WEBSOCKET_VERSION: '8'} + resp = yield from client.ws_connect('/', headers=headers) + msg = yield from resp.receive() + assert msg.data == 'answer' + yield from resp.close() + + +@pytest.mark.run_loop +def test_additional_headers(create_app_and_client, loop): + + @asyncio.coroutine + def handler(request): + assert request.headers['x-hdr'] == 'xtra' + ws = web.WebSocketResponse() + yield from ws.prepare(request) + + ws.send_str('answer') + yield from ws.close() + return ws + + app, client = yield from create_app_and_client() + app.router.add_route('GET', '/', handler) + resp = yield from client.ws_connect('/', headers={'x-hdr': 'xtra'}) + msg = yield from resp.receive() + assert msg.data == 'answer' + yield from resp.close() diff --git a/tests/test_websocket_handshake.py b/tests/test_websocket_handshake.py index 90c0d4e..6a59767 100644 --- a/tests/test_websocket_handshake.py +++ b/tests/test_websocket_handshake.py @@ -18,7 +18,7 @@ def transport(): def message(): headers = multidict.MultiDict() return protocol.RawRequestMessage( - 'GET', '/path', (1, 0), headers, True, None) + 'GET', '/path', (1, 0), headers, [], True, None) def gen_ws_headers(protocols=''): diff --git a/tests/test_websocket_writer.py b/tests/test_websocket_writer.py index 364f0df..eb32adb 100644 --- a/tests/test_websocket_writer.py +++ b/tests/test_websocket_writer.py @@ -53,6 +53,10 @@ def test_close(transport, writer): writer.close(1001, b'msg') transport.write.assert_called_with(b'\x88\x05\x03\xe9msg') + # Test that Service Restart close code is also supported + writer.close(1012, b'msg') + transport.write.assert_called_with(b'\x88\x05\x03\xf4msg') + def test_send_text_masked(transport, writer): writer = websocket.WebSocketWriter(transport, diff --git a/tests/test_worker.py b/tests/test_worker.py index 182aa22..15abe1d 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -1,13 +1,18 @@ """Tests for aiohttp/worker.py""" import asyncio import pytest +import sys + from unittest import mock +from aiohttp import helpers + base_worker = pytest.importorskip('aiohttp.worker') +pytest.importorskip('uvloop') -class MyWorker(base_worker.GunicornWebWorker): +class BaseTestWorker: def __init__(self): self.servers = [] @@ -16,9 +21,23 @@ class MyWorker(base_worker.GunicornWebWorker): self.cfg.graceful_timeout = 100 -@pytest.fixture -def worker(): - return MyWorker() +class AsyncioWorker(BaseTestWorker, base_worker.GunicornWebWorker): + pass + + +class UvloopWorker(BaseTestWorker, base_worker.GunicornUVLoopWebWorker): + + def __init__(self): + if sys.version_info < (3, 5) \ + or sys.platform in ('win32', 'cygwin', 'cli'): + raise pytest.skip("uvloop requires Python 3.5 and *nix.") + + super().__init__() + + +@pytest.fixture(params=[AsyncioWorker, UvloopWorker]) +def worker(request): + return request.param() def test_init_process(worker): @@ -41,7 +60,12 @@ def test_run(worker, loop): worker.run() assert worker._run.called - assert loop._closed + is_closed = getattr(loop, 'is_closed') + if is_closed is not None: + closed = is_closed() + else: + closed = loop._closed + assert closed def test_handle_quit(worker): @@ -56,9 +80,9 @@ def test_handle_abort(worker): assert worker.exit_code == 1 -def test_init_signal(worker): +def test_init_signals(worker): worker.loop = mock.Mock() - worker.init_signal() + worker.init_signals() assert worker.loop.add_signal_handler.called @@ -68,8 +92,7 @@ def test_make_handler(worker): worker.log = mock.Mock() worker.cfg = mock.Mock() - f = worker.make_handler( - worker.wsgi, 'localhost', 8080) + f = worker.make_handler(worker.wsgi) assert f is worker.wsgi.make_handler.return_value @@ -82,12 +105,12 @@ def test__run_ok(worker, loop): worker.sockets = [sock] worker.wsgi = mock.Mock() worker.close = mock.Mock() - worker.close.return_value = asyncio.Future(loop=loop) + worker.close.return_value = helpers.create_future(loop) worker.close.return_value.set_result(()) worker.log = mock.Mock() worker.notify = mock.Mock() worker.loop = loop - ret = asyncio.Future(loop=loop) + ret = helpers.create_future(loop) loop.create_server = mock.Mock( wraps=asyncio.coroutine(lambda *a, **kw: ret)) ret.set_result(sock) @@ -117,12 +140,12 @@ def test__run_exc(worker, loop): worker.notify = mock.Mock() with mock.patch('aiohttp.worker.asyncio.sleep') as m_sleep: - slp = asyncio.Future(loop=loop) + slp = helpers.create_future(loop) slp.set_exception(KeyboardInterrupt) m_sleep.return_value = slp worker.close = mock.Mock() - worker.close.return_value = asyncio.Future(loop=loop) + worker.close.return_value = helpers.create_future(loop) worker.close.return_value.set_result(1) loop.run_until_complete(worker._run()) @@ -138,14 +161,17 @@ def test_close(worker, loop): worker.log = mock.Mock() worker.loop = loop app = worker.wsgi = mock.Mock() - app.finish.return_value = asyncio.Future(loop=loop) + app.finish.return_value = helpers.create_future(loop) app.finish.return_value.set_result(1) handler.connections = [object()] - handler.finish_connections.return_value = asyncio.Future( - loop=loop) + handler.finish_connections.return_value = helpers.create_future(loop) handler.finish_connections.return_value.set_result(1) + app.shutdown.return_value = helpers.create_future(loop) + app.shutdown.return_value.set_result(None) + loop.run_until_complete(worker.close()) + app.shutdown.assert_called_with() app.finish.assert_called_with() handler.finish_connections.assert_called_with(timeout=95.0) srv.close.assert_called_with() diff --git a/tests/test_wsgi.py b/tests/test_wsgi.py index 37dafdf..e754cd8 100644 --- a/tests/test_wsgi.py +++ b/tests/test_wsgi.py @@ -10,6 +10,7 @@ import aiohttp from aiohttp import multidict from aiohttp import wsgi from aiohttp import protocol +from aiohttp import helpers class TestHttpWsgiServerProtocol(unittest.TestCase): @@ -29,8 +30,10 @@ class TestHttpWsgiServerProtocol(unittest.TestCase): ('2.3.4.5', 80)] self.headers = multidict.MultiDict({"HOST": "python.org"}) + self.raw_headers = [(b"HOST", b"python.org")] self.message = protocol.RawRequestMessage( - 'GET', '/path', (1, 0), self.headers, True, 'deflate') + 'GET', '/path', (1, 0), self.headers, self.raw_headers, + True, 'deflate') self.payload = aiohttp.FlowControlDataQueue(self.reader) self.payload.feed_data(b'data', 4) self.payload.feed_data(b'data', 4) @@ -154,9 +157,9 @@ class TestHttpWsgiServerProtocol(unittest.TestCase): def wsgi_app(env, start): start('200 OK', [('Content-Type', 'text/plain')]) - f1 = asyncio.Future(loop=self.loop) + f1 = helpers.create_future(self.loop) f1.set_result(b'data') - fut = asyncio.Future(loop=self.loop) + fut = helpers.create_future(self.loop) fut.set_result([f1]) return fut @@ -180,7 +183,8 @@ class TestHttpWsgiServerProtocol(unittest.TestCase): stream.feed_eof() self.message = protocol.RawRequestMessage( - 'GET', '/path', (1, 1), self.headers, True, 'deflate') + 'GET', '/path', (1, 1), self.headers, self.raw_headers, + True, 'deflate') srv = self._make_srv(wsgi_app, readpayload=True) self.loop.run_until_complete( @@ -219,7 +223,8 @@ class TestHttpWsgiServerProtocol(unittest.TestCase): stream.feed_eof() self.message = protocol.RawRequestMessage( - 'GET', '/path', (1, 1), self.headers, False, 'deflate') + 'GET', '/path', (1, 1), self.headers, self.raw_headers, + False, 'deflate') srv = self._make_srv(wsgi_app, readpayload=True) @@ -251,7 +256,8 @@ class TestHttpWsgiServerProtocol(unittest.TestCase): def test_dont_unquote_environ_path_info(self): path = '/path/some%20text' self.message = protocol.RawRequestMessage( - 'GET', path, (1, 0), self.headers, True, 'deflate') + 'GET', path, (1, 0), self.headers, self.raw_headers, + True, 'deflate') environ = self._make_one() self.assertEqual(environ['PATH_INFO'], path) @@ -261,14 +267,15 @@ class TestHttpWsgiServerProtocol(unittest.TestCase): # not be removed self.headers.extend({'AUTHORIZATION': 'spam'}) self.message = protocol.RawRequestMessage( - 'GET', '/', (1, 1), self.headers, True, 'deflate') + 'GET', '/', (1, 1), self.headers, self.raw_headers, + True, 'deflate') environ = self._make_one() self.assertEqual('spam', environ['HTTP_AUTHORIZATION']) def test_http_1_0_no_host(self): headers = multidict.MultiDict({}) self.message = protocol.RawRequestMessage( - 'GET', '/', (1, 0), headers, True, 'deflate') + 'GET', '/', (1, 0), headers, [], True, 'deflate') environ = self._make_one() self.assertEqual(environ['SERVER_NAME'], '2.3.4.5') self.assertEqual(environ['SERVER_PORT'], '80') @@ -279,7 +286,8 @@ class TestHttpWsgiServerProtocol(unittest.TestCase): ("::", 1122, 0, 0), ('2.3.4.5', 80)] self.message = protocol.RawRequestMessage( - 'GET', '/', (1, 0), self.headers, True, 'deflate') + 'GET', '/', (1, 0), self.headers, self.raw_headers, + True, 'deflate') environ = self._make_one() self.assertEqual(environ['SERVER_NAME'], 'python.org') self.assertEqual(environ['SERVER_PORT'], '80') @@ -295,7 +303,7 @@ class TestHttpWsgiServerProtocol(unittest.TestCase): 'SERVER_NAME': '1.2.3.4', 'SERVER_PORT': '5678', 'REMOTE_ADDR': '4.3.2.1', 'REMOTE_PORT': '8765'}) self.message = protocol.RawRequestMessage( - 'GET', '/', (1, 0), headers, True, 'deflate') + 'GET', '/', (1, 0), headers, self.raw_headers, True, 'deflate') environ = self._make_one() self.assertEqual(environ['SERVER_NAME'], '1.2.3.4') self.assertEqual(environ['SERVER_PORT'], '5678') |
