httoop 0.2.1__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. {httoop-0.2.1 → httoop-0.2.2}/PKG-INFO +31 -16
  2. {httoop-0.2.1 → httoop-0.2.2}/README.md +28 -8
  3. {httoop-0.2.1 → httoop-0.2.2}/httoop/__init__.py +7 -9
  4. {httoop-0.2.1 → httoop-0.2.2}/httoop/__main__.py +20 -13
  5. {httoop-0.2.1 → httoop-0.2.2}/httoop/authentication/__init__.py +9 -9
  6. {httoop-0.2.1 → httoop-0.2.2}/httoop/authentication/basic.py +5 -5
  7. {httoop-0.2.1 → httoop-0.2.2}/httoop/authentication/digest.py +7 -6
  8. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/__init__.py +1 -1
  9. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/application/hal_json.py +5 -5
  10. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/application/json.py +2 -4
  11. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/application/x_www_form_urlencoded.py +1 -2
  12. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/application/xml.py +1 -1
  13. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/message/http.py +1 -1
  14. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/multipart/multipart.py +2 -3
  15. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/text/plain.py +4 -4
  16. {httoop-0.2.1 → httoop-0.2.2}/httoop/date.py +12 -11
  17. {httoop-0.2.1 → httoop-0.2.2}/httoop/exceptions.py +1 -1
  18. {httoop-0.2.1 → httoop-0.2.2}/httoop/gateway/wsgi.py +10 -6
  19. {httoop-0.2.1 → httoop-0.2.2}/httoop/header/__init__.py +2 -2
  20. {httoop-0.2.1 → httoop-0.2.2}/httoop/header/cache.py +1 -1
  21. {httoop-0.2.1 → httoop-0.2.2}/httoop/header/conditional.py +5 -3
  22. {httoop-0.2.1 → httoop-0.2.2}/httoop/header/element.py +67 -38
  23. {httoop-0.2.1 → httoop-0.2.2}/httoop/header/headers.py +27 -31
  24. {httoop-0.2.1 → httoop-0.2.2}/httoop/header/messaging.py +16 -12
  25. {httoop-0.2.1 → httoop-0.2.2}/httoop/header/ranges.py +11 -9
  26. {httoop-0.2.1 → httoop-0.2.2}/httoop/header/security.py +4 -4
  27. {httoop-0.2.1 → httoop-0.2.2}/httoop/messages/body.py +4 -3
  28. {httoop-0.2.1 → httoop-0.2.2}/httoop/messages/protocol.py +2 -2
  29. {httoop-0.2.1 → httoop-0.2.2}/httoop/messages/request.py +1 -1
  30. {httoop-0.2.1 → httoop-0.2.2}/httoop/messages/response.py +1 -1
  31. {httoop-0.2.1 → httoop-0.2.2}/httoop/meta.py +1 -1
  32. {httoop-0.2.1 → httoop-0.2.2}/httoop/parser.py +22 -12
  33. {httoop-0.2.1 → httoop-0.2.2}/httoop/semantic/message.py +16 -1
  34. {httoop-0.2.1 → httoop-0.2.2}/httoop/semantic/request.py +1 -0
  35. {httoop-0.2.1 → httoop-0.2.2}/httoop/semantic/response.py +3 -1
  36. {httoop-0.2.1 → httoop-0.2.2}/httoop/server/__init__.py +8 -0
  37. {httoop-0.2.1 → httoop-0.2.2}/httoop/status/__init__.py +1 -1
  38. {httoop-0.2.1 → httoop-0.2.2}/httoop/status/status.py +2 -1
  39. {httoop-0.2.1 → httoop-0.2.2}/httoop/status/types.py +2 -2
  40. {httoop-0.2.1 → httoop-0.2.2}/httoop/uri/percent_encoding.py +12 -11
  41. {httoop-0.2.1 → httoop-0.2.2}/httoop/uri/uri.py +21 -19
  42. {httoop-0.2.1 → httoop-0.2.2}/httoop/util.py +11 -11
  43. {httoop-0.2.1 → httoop-0.2.2}/httoop/version.py +1 -1
  44. {httoop-0.2.1 → httoop-0.2.2}/httoop.egg-info/PKG-INFO +31 -16
  45. httoop-0.2.2/httoop.egg-info/requires.txt +7 -0
  46. {httoop-0.2.1 → httoop-0.2.2}/pyproject.toml +27 -48
  47. httoop-0.2.1/httoop.egg-info/requires.txt +0 -12
  48. {httoop-0.2.1 → httoop-0.2.2}/LICENSE +0 -0
  49. {httoop-0.2.1 → httoop-0.2.2}/httoop/cache/__init__.py +0 -0
  50. {httoop-0.2.1 → httoop-0.2.2}/httoop/client/__init__.py +0 -0
  51. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/application/__init__.py +0 -0
  52. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/application/gzip.py +0 -0
  53. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/application/zlib.py +0 -0
  54. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/audio/__init__.py +0 -0
  55. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/codec.py +0 -0
  56. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/example/__init__.py +0 -0
  57. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/image/__init__.py +0 -0
  58. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/message/__init__.py +0 -0
  59. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/model/__init__.py +0 -0
  60. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/multipart/__init__.py +0 -0
  61. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/text/__init__.py +0 -0
  62. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/text/html.py +0 -0
  63. {httoop-0.2.1 → httoop-0.2.2}/httoop/codecs/video/__init__.py +0 -0
  64. {httoop-0.2.1 → httoop-0.2.2}/httoop/gateway/__init__.py +0 -0
  65. {httoop-0.2.1 → httoop-0.2.2}/httoop/header/auth.py +0 -0
  66. {httoop-0.2.1 → httoop-0.2.2}/httoop/messages/__init__.py +0 -0
  67. {httoop-0.2.1 → httoop-0.2.2}/httoop/messages/message.py +0 -0
  68. {httoop-0.2.1 → httoop-0.2.2}/httoop/messages/method.py +0 -0
  69. {httoop-0.2.1 → httoop-0.2.2}/httoop/proxy/__init__.py +0 -0
  70. {httoop-0.2.1 → httoop-0.2.2}/httoop/semantic/__init__.py +0 -0
  71. {httoop-0.2.1 → httoop-0.2.2}/httoop/status/client_error.py +0 -0
  72. {httoop-0.2.1 → httoop-0.2.2}/httoop/status/informational.py +0 -0
  73. {httoop-0.2.1 → httoop-0.2.2}/httoop/status/redirect.py +0 -0
  74. {httoop-0.2.1 → httoop-0.2.2}/httoop/status/server_error.py +0 -0
  75. {httoop-0.2.1 → httoop-0.2.2}/httoop/status/success.py +0 -0
  76. {httoop-0.2.1 → httoop-0.2.2}/httoop/uri/__init__.py +0 -0
  77. {httoop-0.2.1 → httoop-0.2.2}/httoop/uri/http.py +0 -0
  78. {httoop-0.2.1 → httoop-0.2.2}/httoop/uri/query_string.py +0 -0
  79. {httoop-0.2.1 → httoop-0.2.2}/httoop/uri/schemes.py +0 -0
  80. {httoop-0.2.1 → httoop-0.2.2}/httoop.egg-info/SOURCES.txt +0 -0
  81. {httoop-0.2.1 → httoop-0.2.2}/httoop.egg-info/dependency_links.txt +0 -0
  82. {httoop-0.2.1 → httoop-0.2.2}/httoop.egg-info/top_level.txt +0 -0
  83. {httoop-0.2.1 → httoop-0.2.2}/httoop.egg-info/zip-safe +0 -0
  84. {httoop-0.2.1 → httoop-0.2.2}/setup.cfg +0 -0
  85. {httoop-0.2.1 → httoop-0.2.2}/tests/test_cli.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: httoop
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: object oriented HTTP protocol library
5
5
  Author-email: SpaceOne <space@wechall.net>
6
6
  License: MIT
@@ -14,7 +14,6 @@ Classifier: Operating System :: POSIX :: BSD
14
14
  Classifier: Operating System :: POSIX :: Linux
15
15
  Classifier: Operating System :: MacOS :: MacOS X
16
16
  Classifier: Operating System :: Microsoft :: Windows
17
- Classifier: Programming Language :: Python :: 3.8
18
17
  Classifier: Programming Language :: Python :: 3.9
19
18
  Classifier: Programming Language :: Python :: 3.10
20
19
  Classifier: Programming Language :: Python :: 3.11
@@ -27,18 +26,14 @@ Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
27
26
  Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Server
28
27
  Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
29
28
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
30
- Requires-Python: >=3.8
29
+ Requires-Python: >=3.9
31
30
  Description-Content-Type: text/markdown
32
31
  License-File: LICENSE
32
+ Requires-Dist: typing_extensions>=4.4
33
33
  Provides-Extra: xml
34
34
  Requires-Dist: defusedxml; extra == "xml"
35
35
  Provides-Extra: hal
36
36
  Requires-Dist: uritemplate; extra == "hal"
37
- Provides-Extra: test
38
- Requires-Dist: pytest; extra == "test"
39
- Requires-Dist: pytest-cov; extra == "test"
40
- Requires-Dist: coveralls; extra == "test"
41
- Requires-Dist: defusedxml; extra == "test"
42
37
  Dynamic: license-file
43
38
 
44
39
  [![Build Status](https://github.com/spaceone/httoop/actions/workflows/ci.yml/badge.svg)](https://github.com/spaceone/httoop/actions/workflows/ci.yml)
@@ -49,19 +44,39 @@ Dynamic: license-file
49
44
  httoop
50
45
  ======
51
46
 
52
- An object oriented HTTP/1.1 library. (HTTP/2 will probably follow in the future).
47
+ An object-oriented HTTP/1.x protocol library for Python.
53
48
 
54
- Httoop can be used to parse, compose and work with HTTP-Request- and Response-Messages.
49
+ Httoop is for applications that need to understand HTTP, not merely send a request.
50
+ It parses and composes requests and responses, and gives every important part of a message a useful object: methods, URIs, protocols, headers, statuses, and bodies.
51
+ The same model can be used to build protocol-aware clients, servers, gateways, middleware, caches, and proxies.
55
52
 
56
- It is an generic library for implementing HTTP servers, clients, caches and proxies.
53
+ ## Why httoop?
57
54
 
58
- Httoop provides an powerful interface using the vocabularity used in RFC 7230 - 7235 and focuses on implementing HTTP "compliant" as defined in [RFC 7230 Section 2.5](https://datatracker.ietf.org/doc/html/rfc7230#section-2.5).
55
+ Most HTTP libraries make the network convenient by hiding the protocol.
56
+ Httoop takes a different approach: it makes the protocol convenient to work with.
57
+ You can inspect, validate, transform, and re-compose a message without dropping down to ad-hoc string manipulation or abandoning the HTTP wire format.
59
58
 
60
- "An implementation is not compliant if it fails to satisfy one or more of the MUST or REQUIRED level requirements for the protocols it implements."
61
- [RFC 2616 Section 1.2](https://datatracker.ietf.org/doc/html/rfc2616#section-1.2)
59
+ * **One coherent object model.** HTTP values share a small semantic interface: they can be parsed, composed, converted to bytes, compared, and represented consistently.
60
+ * **Incremental by design.** The state-machine parser accepts fragmented input, supports pipelined messages, handles fixed-length and chunked bodies, and preserves trailers.
61
+ * **Structured instead of stringly typed.** Headers and URIs expose parsed components, parameters, normalization, joining, and validation. Cookies, ranges, content types, dates, authentication fields, and security headers do not need to be hand-parsed.
62
+ * **Streaming without special cases.** A body can be bytes, text, a file, a file-like object, or an iterable. The same body abstraction handles content encoding, transfer encoding, chunking, and limits.
63
+ * **Protocol-aware composition.** Request and response preparation takes care of HTTP details such as `Host`, `Content-Length`, `Date`, connection semantics, bodyless statuses, `HEAD`, and byte ranges.
64
+ * **Safe boundaries for untrusted input.** Header counts and sizes, URI lengths, body sizes, and decompressed body sizes can be bounded explicitly, while malformed framing and invalid fields are rejected.
65
+ * **Designed to be extended.** New header elements, URI schemes, statuses, and media codecs can be registered and used through the same interfaces as the built-ins.
66
+ * **Integration where it matters.** WSGI support provides a bridge to existing Python web applications without requiring a second message representation.
62
67
 
63
- On top of the object oriented abstraction of HTTP httoop provides an easy way to support WSGI.
68
+ ## The Zen of httoop
64
69
 
70
+ Httoop follows a few simple principles:
71
+
72
+ 1. **Model HTTP as meaning, not as text.** Wire bytes are an input and output format; inside the application, HTTP should be represented by objects with explicit semantics.
73
+ 2. **Separate syntax, semantics, and transport.** Parsing answers "is this a valid message?", composition answers "what should this message mean on the wire?", and adapters answer "where does it run?". Each layer can evolve independently.
74
+ 3. **Make the wire visible when it matters.** Httoop does not hide framing, headers, status codes, encodings, or protocol versions. This makes unusual HTTP behavior possible to inspect and reason about.
75
+ 4. **Treat partial input and large bodies as normal.** Streaming, buffering, pipelining, and resource limits are part of the model rather than afterthoughts.
76
+ 5. **Prefer composition over special-purpose APIs.** The same `Request`, `Response`, `Headers`, `URI`, and `Body` objects work across clients, servers, gateways, and middleware.
77
+ 6. **Extend by adding knowledge, not by rewriting the core.** Protocol extensions plug into registries and semantic types instead of requiring changes throughout the parser.
78
+
79
+ ## HTTP standards
65
80
 
66
81
  HTTP and extensions are defined in the following RFC's:
67
82
 
@@ -143,7 +158,7 @@ Extended information about hypermedia, WWW and how HTTP is meant to be used:
143
158
 
144
159
  * [Economies of scale](https://roy.gbiv.com/untangled/2008/economies-of-scale)
145
160
 
146
- * Clarifications of misconceptions people have about REST:
161
+ Clarifications of misconceptions people have about REST:
147
162
 
148
163
  * [Do You Really Understand the REST?](https://t-code.pl/blog/2016/02/rest-misconceptions-0/)
149
164
 
@@ -6,19 +6,39 @@
6
6
  httoop
7
7
  ======
8
8
 
9
- An object oriented HTTP/1.1 library. (HTTP/2 will probably follow in the future).
9
+ An object-oriented HTTP/1.x protocol library for Python.
10
10
 
11
- Httoop can be used to parse, compose and work with HTTP-Request- and Response-Messages.
11
+ Httoop is for applications that need to understand HTTP, not merely send a request.
12
+ It parses and composes requests and responses, and gives every important part of a message a useful object: methods, URIs, protocols, headers, statuses, and bodies.
13
+ The same model can be used to build protocol-aware clients, servers, gateways, middleware, caches, and proxies.
12
14
 
13
- It is an generic library for implementing HTTP servers, clients, caches and proxies.
15
+ ## Why httoop?
14
16
 
15
- Httoop provides an powerful interface using the vocabularity used in RFC 7230 - 7235 and focuses on implementing HTTP "compliant" as defined in [RFC 7230 Section 2.5](https://datatracker.ietf.org/doc/html/rfc7230#section-2.5).
17
+ Most HTTP libraries make the network convenient by hiding the protocol.
18
+ Httoop takes a different approach: it makes the protocol convenient to work with.
19
+ You can inspect, validate, transform, and re-compose a message without dropping down to ad-hoc string manipulation or abandoning the HTTP wire format.
16
20
 
17
- "An implementation is not compliant if it fails to satisfy one or more of the MUST or REQUIRED level requirements for the protocols it implements."
18
- [RFC 2616 Section 1.2](https://datatracker.ietf.org/doc/html/rfc2616#section-1.2)
21
+ * **One coherent object model.** HTTP values share a small semantic interface: they can be parsed, composed, converted to bytes, compared, and represented consistently.
22
+ * **Incremental by design.** The state-machine parser accepts fragmented input, supports pipelined messages, handles fixed-length and chunked bodies, and preserves trailers.
23
+ * **Structured instead of stringly typed.** Headers and URIs expose parsed components, parameters, normalization, joining, and validation. Cookies, ranges, content types, dates, authentication fields, and security headers do not need to be hand-parsed.
24
+ * **Streaming without special cases.** A body can be bytes, text, a file, a file-like object, or an iterable. The same body abstraction handles content encoding, transfer encoding, chunking, and limits.
25
+ * **Protocol-aware composition.** Request and response preparation takes care of HTTP details such as `Host`, `Content-Length`, `Date`, connection semantics, bodyless statuses, `HEAD`, and byte ranges.
26
+ * **Safe boundaries for untrusted input.** Header counts and sizes, URI lengths, body sizes, and decompressed body sizes can be bounded explicitly, while malformed framing and invalid fields are rejected.
27
+ * **Designed to be extended.** New header elements, URI schemes, statuses, and media codecs can be registered and used through the same interfaces as the built-ins.
28
+ * **Integration where it matters.** WSGI support provides a bridge to existing Python web applications without requiring a second message representation.
19
29
 
20
- On top of the object oriented abstraction of HTTP httoop provides an easy way to support WSGI.
30
+ ## The Zen of httoop
21
31
 
32
+ Httoop follows a few simple principles:
33
+
34
+ 1. **Model HTTP as meaning, not as text.** Wire bytes are an input and output format; inside the application, HTTP should be represented by objects with explicit semantics.
35
+ 2. **Separate syntax, semantics, and transport.** Parsing answers "is this a valid message?", composition answers "what should this message mean on the wire?", and adapters answer "where does it run?". Each layer can evolve independently.
36
+ 3. **Make the wire visible when it matters.** Httoop does not hide framing, headers, status codes, encodings, or protocol versions. This makes unusual HTTP behavior possible to inspect and reason about.
37
+ 4. **Treat partial input and large bodies as normal.** Streaming, buffering, pipelining, and resource limits are part of the model rather than afterthoughts.
38
+ 5. **Prefer composition over special-purpose APIs.** The same `Request`, `Response`, `Headers`, `URI`, and `Body` objects work across clients, servers, gateways, and middleware.
39
+ 6. **Extend by adding knowledge, not by rewriting the core.** Protocol extensions plug into registries and semantic types instead of requiring changes throughout the parser.
40
+
41
+ ## HTTP standards
22
42
 
23
43
  HTTP and extensions are defined in the following RFC's:
24
44
 
@@ -100,7 +120,7 @@ Extended information about hypermedia, WWW and how HTTP is meant to be used:
100
120
 
101
121
  * [Economies of scale](https://roy.gbiv.com/untangled/2008/economies-of-scale)
102
122
 
103
- * Clarifications of misconceptions people have about REST:
123
+ Clarifications of misconceptions people have about REST:
104
124
 
105
125
  * [Do You Really Understand the REST?](https://t-code.pl/blog/2016/02/rest-misconceptions-0/)
106
126
 
@@ -64,14 +64,12 @@ from httoop.version import ServerHeader, ServerProtocol, UserAgentHeader, __vers
64
64
 
65
65
 
66
66
  __all__ = [
67
- 'ACCEPTED', 'BAD_GATEWAY', 'BAD_REQUEST', 'CONFLICT', 'CONTINUE', 'CREATED', 'EXPECTATION_FAILED', 'FORBIDDEN', 'FOUND', 'GATEWAY_TIMEOUT',
68
- 'GONE', 'HTTP_VERSION_NOT_SUPPORTED', 'INTERNAL_SERVER_ERROR', 'I_AM_A_TEAPOT', 'LENGTH_REQUIRED', 'METHOD_NOT_ALLOWED', 'MOVED_PERMANENTLY',
69
- 'MULTIPLE_CHOICES', 'NON_AUTHORITATIVE_INFORMATION', 'NOT_ACCEPTABLE', 'NOT_FOUND', 'NOT_IMPLEMENTED', 'NOT_MODIFIED', 'NO_CONTENT', 'OK',
70
- 'PARTIAL_CONTENT', 'CONTENT_TOO_LARGE', 'PAYMENT_REQUIRED', 'PRECONDITION_FAILED', 'PROXY_AUTHENTICATION_REQUIRED', 'RANGE_NOT_SATISFIABLE',
71
- 'REQUEST_TIMEOUT', 'RESET_CONTENT', 'SEE_OTHER', 'SERVICE_UNAVAILABLE', 'SWITCHING_PROTOCOLS', 'TEMPORARY_REDIRECT', 'UNAUTHORIZED',
72
- 'UNPROCESSABLE_ENTITY', 'UNSUPPORTED_MEDIA_TYPE', 'URI', 'URI_TOO_LONG', 'USE_PROXY',
73
- 'Body', 'ClientStateMachine', 'ComposedRequest', 'ComposedResponse', 'Date', 'DecodeError', 'EncodeError', 'Headers',
74
- 'InvalidBody', 'InvalidDate', 'InvalidHeader', 'InvalidLine', 'InvalidURI',
75
- 'Method', 'Protocol', 'ProxyStateMachine', 'Request', 'Response', 'ServerHeader', 'ServerProtocol', 'ServerStateMachine', 'Status',
67
+ 'ACCEPTED', 'BAD_GATEWAY', 'BAD_REQUEST', 'CONFLICT', 'CONTENT_TOO_LARGE', 'CONTINUE', 'CREATED', 'EXPECTATION_FAILED', 'FORBIDDEN', 'FOUND', 'GATEWAY_TIMEOUT',
68
+ 'GONE', 'HTTP_VERSION_NOT_SUPPORTED', 'INTERNAL_SERVER_ERROR', 'I_AM_A_TEAPOT', 'LENGTH_REQUIRED', 'METHOD_NOT_ALLOWED', 'MOVED_PERMANENTLY', 'MULTIPLE_CHOICES',
69
+ 'NON_AUTHORITATIVE_INFORMATION', 'NOT_ACCEPTABLE', 'NOT_FOUND', 'NOT_IMPLEMENTED', 'NOT_MODIFIED', 'NO_CONTENT', 'OK', 'PARTIAL_CONTENT', 'PAYMENT_REQUIRED',
70
+ 'PRECONDITION_FAILED', 'PROXY_AUTHENTICATION_REQUIRED', 'RANGE_NOT_SATISFIABLE', 'REQUEST_TIMEOUT', 'RESET_CONTENT', 'SEE_OTHER', 'SERVICE_UNAVAILABLE',
71
+ 'SWITCHING_PROTOCOLS', 'TEMPORARY_REDIRECT', 'UNAUTHORIZED', 'UNPROCESSABLE_ENTITY', 'UNSUPPORTED_MEDIA_TYPE', 'URI', 'URI_TOO_LONG', 'USE_PROXY', 'Body',
72
+ 'ClientStateMachine', 'ComposedRequest', 'ComposedResponse', 'Date', 'DecodeError', 'EncodeError', 'Headers', 'InvalidBody', 'InvalidDate', 'InvalidHeader',
73
+ 'InvalidLine', 'InvalidURI', 'Method', 'Protocol', 'ProxyStateMachine', 'Request', 'Response', 'ServerHeader', 'ServerProtocol', 'ServerStateMachine', 'Status',
76
74
  'StatusException', 'UserAgentHeader', '__version__', 'cache',
77
75
  ]
@@ -9,7 +9,8 @@ python3 -m httoop compose response | python3 -m httoop parse response
9
9
 
10
10
  import pathlib
11
11
  import sys
12
- from argparse import ArgumentParser, FileType
12
+ from argparse import ArgumentParser
13
+ from typing import IO
13
14
 
14
15
  from httoop import Request, Response, __name__ as name, __version__ as version
15
16
  from httoop.client import ClientStateMachine
@@ -51,7 +52,7 @@ class CLI:
51
52
  request = parse_message_subparsers.add_parser('request', parents=[self.parent_parser])
52
53
  request.set_defaults(func=self.parse_request)
53
54
  add = request.add_argument
54
- add('--file', default='-', type=FileType('rb'))
55
+ add('--file', default='-')
55
56
  add('--scheme', default='http')
56
57
  add('--host', default='www.example.net')
57
58
  add('--port', default=80, type=int)
@@ -59,24 +60,27 @@ class CLI:
59
60
  response = parse_message_subparsers.add_parser('response', parents=[self.parent_parser])
60
61
  add = response.add_argument
61
62
  response.set_defaults(func=self.parse_response)
62
- add('--file', default='-', type=FileType('rb'))
63
+ add('--file', default='-')
63
64
 
64
65
  def parse_arguments(self) -> None:
65
66
  self.arguments = self.parser.parse_args()
66
-
67
- if self.arguments.action == 'parse' and hasattr(self.arguments.file, 'buffer'):
68
- # https://bugs.python.org/issue14156
69
- self.arguments.file = self.arguments.file.buffer
70
67
  self.arguments.func()
71
68
 
72
- def add_common_arguments(self, add) -> None:
69
+ @classmethod
70
+ def add_common_arguments(cls, add) -> None:
73
71
  add('--protocol')
74
72
  add('-H', '--header', action='append', default=[])
75
73
  add('-b', '--body', default='')
76
74
 
75
+ @classmethod
76
+ def get_file(cls, file: str) -> IO:
77
+ if file == '-':
78
+ return sys.stdin.buffer
79
+ return pathlib.Path(file).open('rb')
80
+
77
81
  def parse_request(self) -> None:
78
82
  server = ServerStateMachine(self.arguments.scheme, self.arguments.host, self.arguments.port)
79
- for _request, response in server.parse(self.arguments.file.read()):
83
+ for _request, response in server.parse(self.get_file(self.arguments.file).read()):
80
84
  print(repr(response))
81
85
  print(repr(response.headers))
82
86
  print(repr(response.body))
@@ -84,12 +88,13 @@ class CLI:
84
88
  def parse_response(self) -> None:
85
89
  client = ClientStateMachine()
86
90
  client.request = Request()
87
- for response in client.parse(self.arguments.file.read()):
91
+ for response in client.parse(self.get_file(self.arguments.file).read()):
88
92
  print(repr(response))
89
93
  print(repr(response.headers))
90
94
  print(repr(response.body))
91
95
  print(repr(bytes(response.body)))
92
96
  if client.buffer:
97
+ assert client.message # noqa: S101
93
98
  print('WARNING: response not yet complete!:')
94
99
  print(repr(client.message))
95
100
  print(repr(client.message.headers))
@@ -115,10 +120,11 @@ class CLI:
115
120
  self.common()
116
121
 
117
122
  def common(self) -> None:
123
+ assert self.message is not None # noqa: S101
118
124
  if self.arguments.protocol:
119
125
  protocol = self.arguments.protocol
120
126
  try:
121
- protocol = [int(x) for x in protocol.split('.', 1)]
127
+ protocol = tuple(int(x) for x in protocol.split('.', 1))
122
128
  except ValueError:
123
129
  pass
124
130
  else:
@@ -133,14 +139,15 @@ class CLI:
133
139
  if body == '-':
134
140
  body = sys.stdin.read()
135
141
  elif body.startswith('@'):
136
- body = pathlib.Path(body[1:]).open('rb')
142
+ body = pathlib.Path(body[1:]).open('rb') # noqa: SIM115
137
143
  self.message.body = body
138
144
 
139
145
  sys.stdout.write(self.decode(bytes(self.message)))
140
146
  sys.stdout.write(self.decode(bytes(self.message.headers)))
141
147
  sys.stdout.write(self.decode(bytes(self.message.body)))
142
148
 
143
- def decode(self, data):
149
+ @classmethod
150
+ def decode(cls, data):
144
151
  if str is not bytes:
145
152
  data = data.decode('ISO8859-1')
146
153
  return data
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import re
4
- from typing import TYPE_CHECKING, Any
4
+ from typing import TYPE_CHECKING, Any, ClassVar
5
5
 
6
6
  from httoop.authentication.basic import BasicAuthRequestScheme, BasicAuthResponseScheme
7
7
  from httoop.authentication.digest import DigestAuthRequestScheme, DigestAuthResponseScheme, SecureDigestAuthRequestScheme
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
16
16
 
17
17
  class AuthElement(HeaderElement):
18
18
 
19
- schemes = {}
19
+ schemes: ClassVar = {}
20
20
  RE_SPACE_SPLIT = re.compile(rb'\s+(?=(?:[^"]*"[^"]*")*[^"]*$)')
21
21
 
22
22
  def sanitize(self) -> None:
@@ -31,16 +31,16 @@ class AuthElement(HeaderElement):
31
31
  try:
32
32
  scheme, authinfo = elementstr.split(b' ', 1)
33
33
  except ValueError:
34
- raise InvalidHeader(_('Authorization headers must contain authentication scheme'))
34
+ raise InvalidHeader(_('Authorization headers must contain authentication scheme')) from None
35
35
  try:
36
36
  parser = cls.schemes[scheme.decode('ISO8859-1').lower()]
37
37
  except KeyError:
38
- raise InvalidHeader(_('Unsupported authentication scheme: %r'), scheme)
38
+ raise InvalidHeader(_('Unsupported authentication scheme: %r'), scheme) from None
39
39
 
40
40
  try:
41
41
  authinfo = parser.parse(authinfo)
42
42
  except KeyError as key:
43
- raise InvalidHeader(_('Missing parameter %r for authentication scheme %r'), str(key), scheme)
43
+ raise InvalidHeader(_('Missing parameter %r for authentication scheme %r'), str(key), scheme) from None
44
44
 
45
45
  return scheme.title(), authinfo
46
46
 
@@ -48,12 +48,12 @@ class AuthElement(HeaderElement):
48
48
  try:
49
49
  scheme = self.schemes[self.value.lower()]
50
50
  except KeyError:
51
- raise InvalidHeader(_('Unsupported authentication scheme: %r'), self.value)
51
+ raise InvalidHeader(_('Unsupported authentication scheme: %r'), self.value) from None
52
52
 
53
53
  try:
54
54
  authinfo = scheme.compose(self.params)
55
55
  except KeyError as key:
56
- raise InvalidHeader(_('Missing parameter %r for authentication scheme %r'), str(key), self.value)
56
+ raise InvalidHeader(_('Missing parameter %r for authentication scheme %r'), str(key), self.value) from None
57
57
 
58
58
  return b'%s %s' % (self.value.encode('ASCII').title(), authinfo)
59
59
 
@@ -68,7 +68,7 @@ class AuthRequestElement(AuthElement):
68
68
 
69
69
  encoding = 'ASCII'
70
70
 
71
- schemes = {
71
+ schemes: ClassVar = {
72
72
  'basic': BasicAuthRequestScheme,
73
73
  'digest': SecureDigestAuthRequestScheme,
74
74
  }
@@ -103,7 +103,7 @@ class AuthRequestElement(AuthElement):
103
103
 
104
104
  class AuthResponseElement(AuthElement):
105
105
 
106
- schemes = {
106
+ schemes: ClassVar = {
107
107
  'basic': BasicAuthResponseScheme,
108
108
  'digest': DigestAuthResponseScheme,
109
109
  }
@@ -19,9 +19,9 @@ class BasicAuthRequestScheme:
19
19
  if not username:
20
20
  raise ValueError()
21
21
  except Base64Error:
22
- raise InvalidHeader(_('Basic authentication contains invalid base64'))
22
+ raise InvalidHeader(_('Basic authentication contains invalid base64')) from None
23
23
  except ValueError:
24
- raise InvalidHeader(_('No username:password provided'))
24
+ raise InvalidHeader(_('No username:password provided')) from None
25
25
 
26
26
  return {
27
27
  # 'username': username.decode('ISO8859-1'),
@@ -42,11 +42,11 @@ class BasicAuthRequestScheme:
42
42
  class BasicAuthResponseScheme:
43
43
 
44
44
  @staticmethod
45
- def parse(authinfo: bytes) -> dict[bytes, str | bytes]:
45
+ def parse(authinfo: bytes) -> dict[bytes, str]:
46
46
  params = HeaderElement.parseparams(b'X;%s' % authinfo)[1]
47
- params.setdefault(b'realm', b'')
47
+ params.setdefault(b'realm', '')
48
48
  return params
49
49
 
50
50
  @staticmethod
51
51
  def compose(authinfo: ByteUnicodeDict) -> bytes:
52
- return HeaderElement.formatparam(b'realm', authinfo['realm'], True)
52
+ return HeaderElement.formatparam(b'realm', authinfo['realm'], quote=True)
@@ -1,9 +1,10 @@
1
+ # ruff: file-ignore[N806,N802]
1
2
  from __future__ import annotations
2
3
 
3
4
  from hashlib import md5, new, sha256
4
5
  from hmac import compare_digest
5
6
  from secrets import token_bytes
6
- from typing import Callable
7
+ from typing import Callable, ClassVar
7
8
 
8
9
  from httoop.exceptions import InvalidHeader
9
10
  from httoop.header.element import HeaderElement
@@ -11,11 +12,11 @@ from httoop.util import ByteUnicodeDict, _
11
12
 
12
13
 
13
14
  class DigestAuthScheme:
14
- algorithms = {
15
- 'MD5': lambda: md5(), # noqa: S324
16
- 'MD5-sess': lambda: md5(), # noqa: S324
17
- 'SHA-256': lambda: sha256(),
18
- 'SHA-256-sess': lambda: sha256(),
15
+ algorithms: ClassVar = {
16
+ 'MD5': md5,
17
+ 'MD5-sess': md5,
18
+ 'SHA-256': sha256,
19
+ 'SHA-256-sess': sha256,
19
20
  'SHA-512-256': lambda: new('sha512_256'),
20
21
  'SHA-512-256-sess': lambda: new('sha512_256'),
21
22
  } # not case insensitive per RFC
@@ -18,7 +18,7 @@ types = (application, audio, example, image, message, model, multipart, text, vi
18
18
  __all__ = ['CODECS', 'Codec', 'application', 'audio', 'example', 'image', 'message', 'model', 'multipart', 'text', 'video']
19
19
 
20
20
 
21
- def lookup(encoding: str, raise_errors: bool = True) -> Any:
21
+ def lookup(encoding: str, *, raise_errors: bool = True) -> Any:
22
22
  type_ = '%s/*' % (encoding.split('/', 1)[0],)
23
23
  return CODECS.get(encoding) or CODECS.get(type_) or (raise_errors and CODECS[encoding]) or None
24
24
 
@@ -95,7 +95,7 @@ class Resource(dict):
95
95
  except StopIteration:
96
96
  pass
97
97
 
98
- def expand(___self, ___href, **templates):
98
+ def expand(___self, ___href, **templates): # noqa: N805
99
99
  return expand(___href, templates)
100
100
 
101
101
  def get_curie(self, relation: str) -> str:
@@ -125,10 +125,10 @@ class HAL(JSON):
125
125
 
126
126
  @classmethod
127
127
  def decode(cls, data: bytes, charset: str | None = None, mimetype: ContentType | None = None) -> Resource:
128
- data = super().decode(data)
129
- if not isinstance(data, dict):
128
+ doc = super().decode(data)
129
+ if not isinstance(doc, dict):
130
130
  raise DecodeError('HAL documents must be JSON objects.')
131
- return Resource(data)
131
+ return Resource(doc)
132
132
 
133
133
  @classmethod
134
134
  def encode(cls, data: dict[str, None] | Resource, charset: str | None = None, mimetype: ContentType | None = None) -> bytes:
@@ -138,6 +138,6 @@ class HAL(JSON):
138
138
  try:
139
139
  Resource(data.copy())
140
140
  except DecodeError as exc:
141
- raise EncodeError(str(exc))
141
+ raise EncodeError(str(exc)) from exc
142
142
 
143
143
  return super().encode(data)
@@ -15,10 +15,8 @@ class JSON(Codec):
15
15
 
16
16
  @classmethod
17
17
  def encode(cls, data: dict[str, str], charset: str | None = None, mimetype: ContentType | None = None) -> bytes:
18
- data = json_encode(data)
19
- if not isinstance(data, bytes): # python3
20
- data = data.encode(charset or 'UTF-8')
21
- return data
18
+ doc = json_encode(data)
19
+ return doc.encode(charset or 'UTF-8')
22
20
 
23
21
  @classmethod
24
22
  def decode(cls, data: bytes, charset: str | None = None, mimetype: ContentType | None = None) -> dict[str, Any]:
@@ -39,5 +39,4 @@ class FormURLEncoded(Codec):
39
39
 
40
40
  @classmethod
41
41
  def quote(cls, data: str | list[int], charset: str | None = None) -> bytes:
42
- data = data.encode(charset or 'ISO8859-1')
43
- return Percent.quote(data, cls.UNQUOTED)
42
+ return Percent.quote(data.encode(charset or 'ISO8859-1'), cls.UNQUOTED)
@@ -33,7 +33,7 @@ class XML(Codec):
33
33
  try:
34
34
  return fromstring(data)
35
35
  except ParseError as exc:
36
- raise DecodeError(f'Could not decode as {mimetype}: {exc}')
36
+ raise DecodeError(f'Could not decode as {mimetype}: {exc}') from exc
37
37
 
38
38
  @classmethod
39
39
  def encode(cls, root: Element, charset: str | None = None, mimetype: ContentType | None = None) -> bytes:
@@ -21,7 +21,7 @@ class HTTP(Codec):
21
21
 
22
22
  @classmethod
23
23
  def decode(cls, data: bytes, charset: str | None = None, mimetype: ContentType | None = None) -> Request | Response:
24
- from httoop.messages import Request, Response
24
+ from httoop.messages import Request, Response # noqa: PLC0415
25
25
 
26
26
  line, data = data.split(b'\r\n', 1)
27
27
  message = Request()
@@ -37,14 +37,13 @@ class Multipart(Codec):
37
37
  if part not in {b'--', b'--\r\n'}:
38
38
  raise DecodeError(_('Invalid multipart end: %r'), part.decode('ISO8859-1'))
39
39
 
40
- from httoop.messages.body import Body
40
+ from httoop.messages.body import Body # noqa: PLC0415
41
41
 
42
42
  multiparts = []
43
43
  for part in parts:
44
44
  if not part.startswith(b'\r\n'):
45
45
  raise DecodeError(_('Invalid boundary end: %r'), part[:2].decode('ISO8859-1'))
46
- part = part[2:]
47
- headers, separator, content = part.partition(b'\r\n\r\n')
46
+ headers, separator, content = part[2:].partition(b'\r\n\r\n')
48
47
  if not separator:
49
48
  raise DecodeError(_('Multipart does not contain CRLF header separator'))
50
49
  if not content.endswith(b'\r\n'):
@@ -17,15 +17,15 @@ class PlainText(Codec):
17
17
  @classmethod
18
18
  def decode(cls, data: bytes, charset: str | None = None, mimetype: ContentType | None = None) -> str:
19
19
  try:
20
- assert isinstance(data, bytes)
20
+ assert isinstance(data, bytes) # noqa: S101
21
21
  return data.decode(charset or 'UTF-8')
22
22
  except UnicodeDecodeError:
23
- raise DecodeError('Wrong encoding.')
23
+ raise DecodeError('Wrong encoding.') from None
24
24
 
25
25
  @classmethod
26
26
  def encode(cls, data: str, charset: str | None = None, mimetype: ContentType | None = None) -> bytes:
27
27
  try:
28
- assert not isinstance(data, bytes)
28
+ assert not isinstance(data, bytes) # noqa: S101
29
29
  return data.encode(charset or 'UTF-8')
30
30
  except UnicodeEncodeError:
31
- raise EncodeError('Wrong encoding.')
31
+ raise EncodeError('Wrong encoding.') from None
@@ -9,7 +9,7 @@ from __future__ import annotations
9
9
  import time
10
10
 
11
11
  # import calendar
12
- from datetime import datetime
12
+ from datetime import datetime as datetime_type, timezone
13
13
  from email.utils import parsedate_tz
14
14
  from typing import Any
15
15
 
@@ -21,7 +21,7 @@ from httoop.util import _
21
21
  __all__ = ['Date']
22
22
 
23
23
 
24
- class Date(Semantic):
24
+ class Date(Semantic): # noqa: PLW1641
25
25
  """
26
26
  A HTTP Date string.
27
27
 
@@ -50,7 +50,7 @@ class Date(Semantic):
50
50
  or a timetuple
51
51
  """
52
52
  self.__composed = None
53
- self.__timestamp = None
53
+ self.__timestamp: float = 0.0
54
54
  self.__datetime = None
55
55
  self.__time_struct = None
56
56
 
@@ -61,7 +61,7 @@ class Date(Semantic):
61
61
  elif isinstance(timeval, (tuple, time.struct_time)):
62
62
  # self.__timestamp = calendar.timegm(timeval)
63
63
  self.__timestamp = time.mktime(timeval) - time.timezone
64
- elif isinstance(timeval, datetime):
64
+ elif isinstance(timeval, datetime_type):
65
65
  self.__datetime = timeval
66
66
  # self.__timestamp = calendar.timegm(self.datetime.utctimetuple())
67
67
  self.__timestamp = time.mktime(self.datetime.utctimetuple()) - time.timezone
@@ -75,9 +75,9 @@ class Date(Semantic):
75
75
  raise TypeError('Date(): got invalid argument')
76
76
 
77
77
  @property
78
- def datetime(self) -> datetime:
78
+ def datetime(self) -> datetime_type:
79
79
  if self.__datetime is None:
80
- self.__datetime = datetime.utcfromtimestamp(int(self))
80
+ self.__datetime = datetime_type.fromtimestamp(int(self), tz=timezone.utc)
81
81
  return self.__datetime
82
82
 
83
83
  @property
@@ -104,7 +104,7 @@ class Date(Semantic):
104
104
  )
105
105
 
106
106
  @classmethod
107
- def parse(cls, timestr: bytes) -> Date:
107
+ def parse(cls, data: bytes) -> Date:
108
108
  """
109
109
  Parses a HTTP date string and returns a :class:`Date` object.
110
110
 
@@ -115,7 +115,7 @@ class Date(Semantic):
115
115
  :rtype : :class:`Date`
116
116
 
117
117
  """
118
- timestr = timestr.decode('ISO8859-1')
118
+ timestr = data.decode('ISO8859-1')
119
119
 
120
120
  # parse the most common HTTP Date formats (RFC 2822, RFC 1036, C's asctime)
121
121
  date = parsedate_tz(timestr)
@@ -148,17 +148,18 @@ class Date(Semantic):
148
148
  except NotImplementedError: # pragma: no cover
149
149
  return NotImplemented
150
150
 
151
- def __other(self, other):
151
+ @staticmethod
152
+ def __other(other) -> Date:
152
153
  if other is None:
153
154
  return Date(0)
154
- raise NotImplementedError() # pragma: no cover
155
+ # raise NotImplementedError()
155
156
  if isinstance(other, Date):
156
157
  return other
157
158
  try:
158
159
  return Date(other)
159
160
  except (InvalidDate, TypeError):
160
161
  return Date(0)
161
- raise NotImplementedError() # pragma: no cover
162
+ # raise NotImplementedError()
162
163
 
163
164
  def __repr__(self) -> str:
164
165
  return '<HTTP Date(%d)>' % (int(self),)
@@ -3,7 +3,7 @@
3
3
  from httoop.util import _Translateable
4
4
 
5
5
 
6
- class Invalid(_Translateable, ValueError):
6
+ class Invalid(_Translateable, ValueError): # noqa: N818
7
7
  """base class for invalid values."""
8
8
 
9
9