microversion-parse 2.0.0__tar.gz → 2.2.0__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 (45) hide show
  1. microversion_parse-2.2.0/.pre-commit-config.yaml +20 -0
  2. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/.zuul.yaml +3 -0
  3. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/AUTHORS +1 -0
  4. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/ChangeLog +27 -0
  5. microversion_parse-2.2.0/PKG-INFO +147 -0
  6. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/doc/source/conf.py +10 -11
  7. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse/__init__.py +76 -51
  8. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse/middleware.py +36 -11
  9. microversion_parse-2.2.0/microversion_parse/tests/__init__.py +0 -0
  10. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse/tests/test_extract_version.py +49 -29
  11. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse/tests/test_get_version.py +57 -42
  12. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse/tests/test_headers_from_wsgi_environ.py +27 -22
  13. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse/tests/test_middleware.py +6 -4
  14. microversion_parse-2.2.0/microversion_parse/tests/test_webob.py +95 -0
  15. microversion_parse-2.2.0/microversion_parse.egg-info/PKG-INFO +147 -0
  16. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse.egg-info/SOURCES.txt +3 -2
  17. microversion_parse-2.2.0/microversion_parse.egg-info/pbr.json +1 -0
  18. microversion_parse-2.2.0/pyproject.toml +80 -0
  19. microversion_parse-2.2.0/setup.cfg +7 -0
  20. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/setup.py +2 -1
  21. microversion_parse-2.2.0/test-requirements.txt +3 -0
  22. microversion_parse-2.2.0/tox.ini +79 -0
  23. microversion_parse-2.0.0/.pre-commit-config.yaml +0 -39
  24. microversion_parse-2.0.0/PKG-INFO +0 -145
  25. microversion_parse-2.0.0/microversion_parse/tests/test_webob.py +0 -80
  26. microversion_parse-2.0.0/microversion_parse.egg-info/PKG-INFO +0 -145
  27. microversion_parse-2.0.0/microversion_parse.egg-info/pbr.json +0 -1
  28. microversion_parse-2.0.0/releasenotes/notes/drop-python27-support-5b9a4e0ce63b730e.yaml +0 -5
  29. microversion_parse-2.0.0/setup.cfg +0 -30
  30. microversion_parse-2.0.0/test-requirements.txt +0 -6
  31. microversion_parse-2.0.0/tox.ini +0 -48
  32. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/.stestr.conf +0 -0
  33. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/LICENSE +0 -0
  34. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/Makefile +0 -0
  35. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/README.rst +0 -0
  36. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/doc/requirements.txt +0 -0
  37. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/doc/source/index.rst +0 -0
  38. /microversion_parse-2.0.0/microversion_parse/tests/__init__.py → /microversion_parse-2.2.0/microversion_parse/py.typed +0 -0
  39. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse/tests/gabbits/middleware.yaml +0 -0
  40. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse/tests/gabbits/simple.yaml +0 -0
  41. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse.egg-info/dependency_links.txt +0 -0
  42. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse.egg-info/not-zip-safe +0 -0
  43. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse.egg-info/requires.txt +0 -0
  44. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/microversion_parse.egg-info/top_level.txt +0 -0
  45. {microversion_parse-2.0.0 → microversion_parse-2.2.0}/requirements.txt +0 -0
@@ -0,0 +1,20 @@
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v6.0.0
4
+ hooks:
5
+ - id: trailing-whitespace
6
+ - id: mixed-line-ending
7
+ args: ['--fix', 'lf']
8
+ exclude: '.*\.(svg)$'
9
+ - id: fix-byte-order-marker
10
+ - id: check-executables-have-shebangs
11
+ - id: check-merge-conflict
12
+ - id: debug-statements
13
+ - id: check-yaml
14
+ files: .*\.(yaml|yml)$
15
+ - repo: https://github.com/astral-sh/ruff-pre-commit
16
+ rev: v0.15.18
17
+ hooks:
18
+ - id: ruff-check
19
+ args: ['--fix', '--unsafe-fixes']
20
+ - id: ruff-format
@@ -1,4 +1,7 @@
1
+ ---
2
+
1
3
  - project:
2
4
  templates:
3
5
  - openstack-python3-jobs
6
+ - openstack-python3-next-jobs
4
7
  - check-requirements
@@ -7,6 +7,7 @@ Hervé Beraud <hberaud@redhat.com>
7
7
  Louis Taylor <louis@kragniz.eu>
8
8
  Moisés Guimarães de Medeiros <moguimar@redhat.com>
9
9
  PollyZ <Polly.Zhou@rackspace.com>
10
+ Stephen Finucane <stephenfin@redhat.com>
10
11
  Takashi Kajinami <kajinamit@oss.nttdata.com>
11
12
  Takashi Kajinami <tkajinam@redhat.com>
12
13
  Vieri <15050873171@163.com>
@@ -1,6 +1,33 @@
1
1
  CHANGES
2
2
  =======
3
3
 
4
+ 2.2.0
5
+ -----
6
+
7
+ * Declare Python 3.15 support
8
+ * Use pyproject.toml to maintain coverage options
9
+ * tox: Use constraints option
10
+ * Resolve deprecation warnings from setuptools
11
+ * Drop Python 3.10 support
12
+ * zuul: Use openstack-python3-next-jobs template
13
+ * pre-commit: Bump versions
14
+ * Replace deprecated openstackdocstheme options
15
+ * Drop release note files
16
+ * Run mypy from tox
17
+ * Add typing classifier
18
+
19
+ 2.1.0
20
+ -----
21
+
22
+ * gitignore: Ignore pbr-generated artifacts
23
+ * Add typing
24
+ * pre-commit: Bump versions
25
+ * ruff: Use more specific name to enable pyupgrade rule
26
+ * Add ruff
27
+ * pre-commit: Bump dependencies
28
+ * Migrate setup configuration to pyproject.toml
29
+ * Drop Python 3.9 support
30
+
4
31
  2.0.0
5
32
  -----
6
33
 
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: microversion_parse
3
+ Version: 2.2.0
4
+ Summary: OpenStack microversion header parser
5
+ Author-email: OpenStack <openstack-discuss@lists.openstack.org>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://opendev.org/openstack/microversion-parse
8
+ Classifier: Environment :: OpenStack
9
+ Classifier: Intended Audience :: Information Technology
10
+ Classifier: Intended Audience :: System Administrators
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/x-rst
22
+ License-File: LICENSE
23
+ Requires-Dist: WebOb>=1.2.3
24
+ Dynamic: license-file
25
+ Dynamic: requires-dist
26
+
27
+ microversion_parse
28
+ ==================
29
+
30
+ A small set of functions to manage OpenStack `microversion`_ headers that can
31
+ be used in middleware, application handlers and decorators to effectively
32
+ manage microversions.
33
+
34
+ Also included, in the ``middleware`` module, is a ``MicroversionMiddleware``
35
+ that will process incoming microversion headers.
36
+
37
+ get_version
38
+ -----------
39
+
40
+ A simple parser for OpenStack microversion headers::
41
+
42
+ import microversion_parse
43
+
44
+ # headers is a dict of headers with folded (comma-separated
45
+ # values) or a list of header, value tuples
46
+ version = microversion_parse.get_version(
47
+ headers, service_type='compute',
48
+ legacy_headers=['x-openstack-nova-api-version'])
49
+
50
+ # If headers are not already available, a dict of headers
51
+ # can be extracted from the WSGI environ
52
+ headers = microversion_parse.headers_from_wsgi_environ(environ)
53
+ version = microversion_parse.get_version(
54
+ headers, service_type='placement')
55
+
56
+ It processes microversion headers with the standard form::
57
+
58
+ OpenStack-API-Version: compute 2.1
59
+
60
+ In that case, the response will be '2.1'.
61
+
62
+ If provided with a ``legacy_headers`` argument, this is treated as
63
+ a list of additional headers to check for microversions. Some examples of
64
+ headers include::
65
+
66
+ OpenStack-telemetry-api-version: 2.1
67
+ OpenStack-nova-api-version: 2.1
68
+ X-OpenStack-nova-api-version: 2.1
69
+
70
+ If a version string cannot be found, ``None`` will be returned. If
71
+ the input is incorrect usual Python exceptions (ValueError,
72
+ TypeError) are allowed to raise to the caller.
73
+
74
+ parse_version_string
75
+ --------------------
76
+
77
+ A function to turn a version string into a ``Version``, a comparable
78
+ ``namedtuple``::
79
+
80
+ version_tuple = microversion_parse.parse_version_string('2.1')
81
+
82
+ If the provided string is not a valid microversion string, ``TypeError``
83
+ is raised.
84
+
85
+ extract_version
86
+ ---------------
87
+
88
+ Combines ``get_version`` and ``parse_version_string`` to find and validate
89
+ a microversion for a given service type in a collection of headers::
90
+
91
+ version_tuple = microversion_parse.extract_version(
92
+ headers, # a representation of headers, as accepted by get_version
93
+ service_type, # service type identify to match in headers
94
+ versions_list, # an ordered list of strings of version numbers that
95
+ # are the valid versions presented by this service
96
+ )
97
+
98
+ ``latest`` will be translated to whatever the max version is in versions_list.
99
+
100
+ If the found version is not in versions_list a ``ValueError`` is raised.
101
+
102
+ Note that ``extract_version`` does not support ``legacy_headers``.
103
+
104
+ MicroversionMiddleware
105
+ ----------------------
106
+
107
+ A WSGI middleware that can wrap an application that needs to be microversion
108
+ aware. The application will get a WSGI environ with a
109
+ 'SERVICE_TYPE.microversion' key that has a value of the microversion found at
110
+ an 'openstack-api-version' header that matches SERVICE_TYPE. If no header is
111
+ found, the minimum microversion will be set. If the special keyword 'latest' is
112
+ used, the maximum microversion will be set.
113
+
114
+ If the requested microversion is not available a 406 response is returned.
115
+
116
+ If there is an error parsing a provided header, a 400 response is returned.
117
+
118
+ Otherwise the application is called.
119
+
120
+ The middleware is configured when it is created. Three parameters are required:
121
+
122
+ app
123
+ The next WSGI middleware or application in the stack.
124
+
125
+ service_type
126
+ The service type of the application, used to identify microversion headers.
127
+
128
+ versions_list
129
+ An ordered list of legitimate microversions (as strings) for the application.
130
+ It's assumed that any application that is using microversions will have such
131
+ a list for its own housekeeping and documentation.
132
+
133
+ One named parameter is optional:
134
+
135
+ json_error_formatter
136
+ A Webob error formatter that can be used to structure the response when JSON
137
+ is expected.
138
+
139
+ For example::
140
+
141
+ def app():
142
+ app = middleware.MicroversionMiddleware(
143
+ MyWSGIApp(), 'cats', ['1.0', '1.1', '1.2'])
144
+ return app
145
+
146
+
147
+ .. _microversion: http://specs.openstack.org/openstack/api-wg/guidelines/microversion_specification.html
@@ -1,4 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
1
  # Copyright (C) 2020 Red Hat, Inc.
3
2
  #
4
3
  # Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -33,7 +32,7 @@
33
32
  extensions = [
34
33
  'sphinx.ext.autodoc',
35
34
  'sphinx.ext.intersphinx',
36
- 'openstackdocstheme'
35
+ 'openstackdocstheme',
37
36
  ]
38
37
 
39
38
  # Add any paths that contain templates here, relative to this directory.
@@ -50,12 +49,12 @@ master_doc = 'index'
50
49
  # General information about the project.
51
50
  project = 'microversion-parse'
52
51
  copyright = '2016, OpenStack'
53
- author = u'OpenStack'
52
+ author = 'OpenStack'
54
53
 
55
54
  # openstackdocstheme options
56
- repository_name = 'openstack/microversion-parse'
57
- bug_project = 'microversion-parse'
58
- bug_tag = ''
55
+ openstackdocs_repo_name = 'openstack/microversion-parse'
56
+ openstackdocs_bug_project = 'microversion-parse'
57
+ openstackdocs_bug_tag = ''
59
58
  html_theme = 'openstackdocs'
60
59
 
61
60
  # The language for content autogenerated by Sphinx. Refer to documentation
@@ -92,7 +91,7 @@ latex_documents = [
92
91
  'microversion-parse.tex',
93
92
  'microversion-parse Documentation',
94
93
  'OpenStack',
95
- 'manual'
94
+ 'manual',
96
95
  ),
97
96
  ]
98
97
 
@@ -104,9 +103,9 @@ man_pages = [
104
103
  (
105
104
  master_doc,
106
105
  'microversion-parse',
107
- u'microversion-parse Documentation',
106
+ 'microversion-parse Documentation',
108
107
  [author],
109
- 1
108
+ 1,
110
109
  )
111
110
  ]
112
111
 
@@ -120,11 +119,11 @@ texinfo_documents = [
120
119
  (
121
120
  master_doc,
122
121
  'microversion-parse',
123
- u'microversion-parse Documentation',
122
+ 'microversion-parse Documentation',
124
123
  author,
125
124
  'microversion-parse',
126
125
  'One line description of project.',
127
- 'Miscellaneous'
126
+ 'Miscellaneous',
128
127
  ),
129
128
  ]
130
129
 
@@ -12,7 +12,8 @@
12
12
  # limitations under the License.
13
13
 
14
14
  import collections
15
-
15
+ from collections.abc import Iterable, MutableMapping, Sequence
16
+ from typing import Any, Self
16
17
 
17
18
  ENVIRON_HTTP_HEADER_FMT = 'http_{}'
18
19
  STANDARD_HEADER = 'openstack-api-version'
@@ -24,19 +25,25 @@ class Version(collections.namedtuple('Version', 'major minor')):
24
25
  Since it is a tuple, it is automatically comparable.
25
26
  """
26
27
 
27
- def __new__(cls, major, minor):
28
+ max_version: tuple[int, int]
29
+ min_version: tuple[int, int]
30
+
31
+ def __new__(cls, major: int, minor: int) -> 'Self':
28
32
  """Add min and max version attributes to the tuple."""
29
- self = super(Version, cls).__new__(cls, major, minor)
33
+ self = super().__new__(cls, major, minor)
30
34
  self.max_version = (-1, 0)
31
35
  self.min_version = (-1, 0)
32
36
  return self
33
37
 
34
- def __str__(self):
35
- return '%s.%s' % (self.major, self.minor)
38
+ def __str__(self) -> str:
39
+ return f'{self.major}.{self.minor}'
36
40
 
37
- def matches(self, min_version=None, max_version=None):
38
- """Is this version within min_version and max_version.
39
- """
41
+ def matches(
42
+ self,
43
+ min_version: tuple[int, int] | None = None,
44
+ max_version: tuple[int, int] | None = None,
45
+ ) -> bool:
46
+ """Is this version within min_version and max_version."""
40
47
  # NOTE(cdent): min_version and max_version are expected
41
48
  # to be set by the code that is creating the Version, if
42
49
  # they are known.
@@ -47,31 +54,34 @@ class Version(collections.namedtuple('Version', 'major minor')):
47
54
  return min_version <= self <= max_version
48
55
 
49
56
 
50
- def get_version(headers, service_type, legacy_headers=None):
57
+ def get_version(
58
+ headers: Iterable[tuple[str, str]] | MutableMapping[str, str],
59
+ service_type: str,
60
+ legacy_headers: Iterable[str] | None = None,
61
+ ) -> str | None:
51
62
  """Parse a microversion out of headers
52
63
 
53
- :param headers: The headers of a request, dict or list
54
- :param service_type: The service type being looked for in the headers
55
- :param legacy_headers: Other headers to look at for a version
56
- :returns: a version string or "latest"
57
- :raises: ValueError
64
+ If headers is not a dict we assume is an iterator of tuple-like headers,
65
+ which we will fold into a dict.
58
66
 
59
- If headers is not a dict we assume is an iterator of
60
- tuple-like headers, which we will fold into a dict.
67
+ The flow is that we first look for the new standard singular header:
61
68
 
62
- The flow is that we first look for the new standard singular
63
- header:
64
-
65
- * openstack-api-version: <service> <version>
69
+ * ``openstack-api-version: <service> <version>``
66
70
 
67
71
  If that's not present we fall back to the headers listed in
68
- legacy_headers. These often look like this:
72
+ ``legacy_headers``. These often look like this:
73
+
74
+ * ``openstack-<service>-api-version: <version>``
75
+ * ``openstack-<legacy>-api-version: <version>``
76
+ * ``x-openstack-<legacy>-api-version: <version>``
69
77
 
70
- * openstack-<service>-api-version: <version>
71
- * openstack-<legacy>-api-version: <version>
72
- * x-openstack-<legacy>-api-version: <version>
78
+ Folded headers are joined by ``,``.
73
79
 
74
- Folded headers are joined by ','.
80
+ :param headers: The headers of a request, dict or list
81
+ :param service_type: The service type being looked for in the headers
82
+ :param legacy_headers: Other headers to look at for a version
83
+ :returns: a version string or "latest"
84
+ :raises: ValueError
75
85
  """
76
86
 
77
87
  folded_headers = fold_headers(headers)
@@ -87,7 +97,9 @@ def get_version(headers, service_type, legacy_headers=None):
87
97
  return None
88
98
 
89
99
 
90
- def check_legacy_headers(headers, legacy_headers):
100
+ def check_legacy_headers(
101
+ headers: MutableMapping[str, str], legacy_headers: Iterable[str]
102
+ ) -> str | None:
91
103
  """Gather values from old headers."""
92
104
  for legacy_header in legacy_headers:
93
105
  try:
@@ -98,7 +110,9 @@ def check_legacy_headers(headers, legacy_headers):
98
110
  return None
99
111
 
100
112
 
101
- def check_standard_header(headers, service_type):
113
+ def check_standard_header(
114
+ headers: MutableMapping[str, str], service_type: str
115
+ ) -> str | None:
102
116
  """Parse the standard header to get value for service."""
103
117
  try:
104
118
  header = _extract_header_value(headers, STANDARD_HEADER)
@@ -112,8 +126,12 @@ def check_standard_header(headers, service_type):
112
126
  except (KeyError, ValueError):
113
127
  return None
114
128
 
129
+ return None
130
+
115
131
 
116
- def fold_headers(headers):
132
+ # we accept Any even though we know this will be a list of 2-item tuples or a
133
+ # dict, in order to avoid reworking logic
134
+ def fold_headers(headers: Any) -> MutableMapping[str, str]:
117
135
  """Turn a list of headers into a folded dict."""
118
136
  # If it behaves like a dict, return it. Webob uses objects which
119
137
  # are not dicts, but behave like them.
@@ -121,6 +139,7 @@ def fold_headers(headers):
121
139
  return dict((k.lower(), v) for k, v in headers.items())
122
140
  except AttributeError:
123
141
  pass
142
+
124
143
  header_dict = collections.defaultdict(list)
125
144
  for header, value in headers:
126
145
  header_dict[header.lower()].append(value.strip())
@@ -132,35 +151,40 @@ def fold_headers(headers):
132
151
  return folded_headers
133
152
 
134
153
 
135
- def headers_from_wsgi_environ(environ):
154
+ def headers_from_wsgi_environ(
155
+ environ: MutableMapping[str, str],
156
+ ) -> dict[str, str]:
136
157
  """Extract all the HTTP_ keys and values from environ to a new dict.
137
158
 
138
- Note that this does not change the keys in any way in the returned
139
- dict. Nor is the incoming environ modified.
159
+ Note that this does not change the keys in any way in the returned dict.
160
+ Nor is the incoming environ modified.
140
161
 
141
162
  :param environ: A PEP 3333 compliant WSGI environ dict.
142
163
  """
143
164
  return {key: environ[key] for key in environ if key.startswith('HTTP_')}
144
165
 
145
166
 
146
- def _extract_header_value(headers, header_name):
167
+ def _extract_header_value(
168
+ headers: MutableMapping[str, str], header_name: str
169
+ ) -> str:
147
170
  """Get the value of a header.
148
171
 
149
- The provided headers is a dict. If a key doesn't exist for
150
- header_name, try using the WSGI environ form of the name.
172
+ The provided headers is a dict. If a key doesn't exist for ``header_name``,
173
+ try using the WSGI environ form of the name.
151
174
 
152
- Raises KeyError if neither key is found.
175
+ :raises: KeyError if neither key is found.
153
176
  """
154
177
  try:
155
178
  value = headers[header_name]
156
179
  except KeyError:
157
180
  wsgi_header_name = ENVIRON_HTTP_HEADER_FMT.format(
158
- header_name.replace('-', '_'))
181
+ header_name.replace('-', '_')
182
+ )
159
183
  value = headers[wsgi_header_name]
160
184
  return value
161
185
 
162
186
 
163
- def parse_version_string(version_string):
187
+ def parse_version_string(version_string: str) -> Version:
164
188
  """Turn a version string into a Version
165
189
 
166
190
  :param version_string: A string of two numerals, X.Y.
@@ -173,28 +197,29 @@ def parse_version_string(version_string):
173
197
  # ValueError, TypeError or AttributeError when the incoming
174
198
  # data is poorly formed but will, however, naturally adapt to
175
199
  # extraneous whitespace.
176
- return Version(*(int(value) for value
177
- in version_string.split('.', 1)))
200
+ return Version(*(int(value) for value in version_string.split('.', 1)))
178
201
  except (ValueError, TypeError, AttributeError) as exc:
179
- raise TypeError('invalid version string: %s; %s' % (
180
- version_string, exc))
202
+ raise TypeError(f'invalid version string: {version_string}; {exc}')
181
203
 
182
204
 
183
- def extract_version(headers, service_type, versions_list):
205
+ def extract_version(
206
+ headers: Iterable[tuple[str, str]] | MutableMapping[str, str],
207
+ service_type: str,
208
+ versions_list: Sequence[str],
209
+ ) -> Version:
184
210
  """Extract the microversion from the headers.
185
211
 
186
- There may be multiple headers and some which don't match our
187
- service.
212
+ There may be multiple headers and some which don't match our service.
188
213
 
189
- If no version is found then the extracted version is the minimum
190
- available version.
214
+ If no version is found then the extracted version is the minimum available
215
+ version.
191
216
 
192
217
  :param headers: Request headers as dict list or WSGI environ
193
- :param service_type: The service_type as a string
218
+ :param service_type: The service type as a string
194
219
  :param versions_list: List of all possible microversions as strings,
195
- sorted from earliest to latest version.
196
- :returns: a Version with the optional min_version and max_version
197
- attributes set.
220
+ sorted from earliest to latest version.
221
+ :returns: a :class:`~Version` with the optional ``min_version`` and
222
+ ``max_version`` attributes set.
198
223
  :raises: ValueError
199
224
  """
200
225
  found_version = get_version(headers, service_type=service_type)
@@ -213,4 +238,4 @@ def extract_version(headers, service_type, versions_list):
213
238
  # to administratively disable a version if we really need to.
214
239
  if str(request_version) in versions_list:
215
240
  return request_version
216
- raise ValueError('Unacceptable version header: %s' % version_string)
241
+ raise ValueError(f'Unacceptable version header: {version_string}')
@@ -10,15 +10,29 @@
10
10
  # implied.
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
+
13
14
  """WSGI middleware for getting microversion info."""
14
15
 
16
+ from collections.abc import Sequence
17
+ from typing import Any, Protocol, TYPE_CHECKING
18
+
15
19
  import webob
16
20
  import webob.dec
21
+ import webob.exc
17
22
 
18
23
  import microversion_parse
19
24
 
25
+ if TYPE_CHECKING:
26
+ from _typeshed.wsgi import WSGIApplication
27
+
28
+
29
+ class _JSONFormatter(Protocol):
30
+ def __call__(
31
+ self, *, body: str, status: str, title: str, environ: dict[str, Any]
32
+ ) -> Any: ...
33
+
20
34
 
21
- class MicroversionMiddleware(object):
35
+ class MicroversionMiddleware:
22
36
  """WSGI middleware for getting microversion info.
23
37
 
24
38
  The application will get a WSGI environ with a
@@ -37,8 +51,13 @@ class MicroversionMiddleware(object):
37
51
  Otherwise the application is called.
38
52
  """
39
53
 
40
- def __init__(self, application, service_type, versions,
41
- json_error_formatter=None):
54
+ def __init__(
55
+ self,
56
+ application: 'WSGIApplication | None',
57
+ service_type: str,
58
+ versions: Sequence[str],
59
+ json_error_formatter: _JSONFormatter | None = None,
60
+ ) -> None:
42
61
  """Create the WSGI middleware.
43
62
 
44
63
  :param application: The application hosting the service.
@@ -51,29 +70,35 @@ class MicroversionMiddleware(object):
51
70
  """
52
71
  self.application = application
53
72
  self.service_type = service_type
54
- self.microversion_environ = '%s.microversion' % service_type
73
+ self.microversion_environ = f'{service_type}.microversion'
55
74
  self.versions = versions
56
75
  self.json_error_formatter = json_error_formatter
57
76
 
58
77
  @webob.dec.wsgify
59
- def __call__(self, req):
78
+ def __call__(
79
+ self,
80
+ req: webob.request.Request,
81
+ ) -> webob.response.Response | None:
60
82
  try:
61
83
  microversion = microversion_parse.extract_version(
62
- req.headers, self.service_type, self.versions)
84
+ req.headers, self.service_type, self.versions
85
+ )
63
86
  # TODO(cdent): These error response are not formatted according to
64
87
  # api-sig guidelines, unless a json_error_formatter is provided
65
88
  # that can do it. For an example, see the placement service.
66
89
  except ValueError as exc:
67
90
  raise webob.exc.HTTPNotAcceptable(
68
- ('Invalid microversion: %(error)s') % {'error': exc},
69
- json_formatter=self.json_error_formatter)
91
+ (f'Invalid microversion: {exc}'),
92
+ json_formatter=self.json_error_formatter,
93
+ )
70
94
  except TypeError as exc:
71
95
  raise webob.exc.HTTPBadRequest(
72
- ('Invalid microversion: %(error)s') % {'error': exc},
73
- json_formatter=self.json_error_formatter)
96
+ (f'Invalid microversion: {exc}'),
97
+ json_formatter=self.json_error_formatter,
98
+ )
74
99
 
75
100
  req.environ[self.microversion_environ] = microversion
76
- microversion_header = '%s %s' % (self.service_type, microversion)
101
+ microversion_header = f'{self.service_type} {microversion}'
77
102
  standard_header = microversion_parse.STANDARD_HEADER
78
103
 
79
104
  try: