uvicorn 0.33.0__tar.gz → 0.34.1__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 (76) hide show
  1. {uvicorn-0.33.0 → uvicorn-0.34.1}/.gitignore +1 -0
  2. {uvicorn-0.33.0 → uvicorn-0.34.1}/PKG-INFO +6 -6
  3. {uvicorn-0.33.0 → uvicorn-0.34.1}/pyproject.toml +6 -7
  4. {uvicorn-0.33.0 → uvicorn-0.34.1}/requirements.txt +12 -12
  5. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/middleware/test_wsgi.py +2 -1
  6. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/protocols/test_http.py +2 -2
  7. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/protocols/test_websocket.py +10 -14
  8. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/supervisors/test_reload.py +25 -20
  9. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/test_auto_detection.py +1 -1
  10. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/test_cli.py +2 -2
  11. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/test_config.py +1 -1
  12. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/test_main.py +12 -1
  13. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/test_server.py +7 -3
  14. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/__init__.py +1 -1
  15. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/_types.py +5 -17
  16. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/config.py +5 -4
  17. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/main.py +19 -6
  18. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/middleware/wsgi.py +2 -3
  19. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/websockets/websockets_impl.py +6 -5
  20. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/websockets/wsproto_impl.py +3 -2
  21. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/server.py +4 -6
  22. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/supervisors/basereload.py +2 -1
  23. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/supervisors/statreload.py +3 -2
  24. {uvicorn-0.33.0 → uvicorn-0.34.1}/LICENSE.md +0 -0
  25. {uvicorn-0.33.0 → uvicorn-0.34.1}/README.md +0 -0
  26. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/__init__.py +0 -0
  27. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/conftest.py +0 -0
  28. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/importer/__init__.py +0 -0
  29. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/importer/circular_import_a.py +0 -0
  30. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/importer/circular_import_b.py +0 -0
  31. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/importer/raise_import_error.py +0 -0
  32. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/importer/test_importer.py +0 -0
  33. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/middleware/__init__.py +0 -0
  34. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/middleware/test_logging.py +0 -0
  35. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/middleware/test_message_logger.py +0 -0
  36. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/middleware/test_proxy_headers.py +0 -0
  37. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/protocols/__init__.py +0 -0
  38. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/protocols/test_utils.py +0 -0
  39. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/response.py +0 -0
  40. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/supervisors/__init__.py +0 -0
  41. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/supervisors/test_multiprocess.py +0 -0
  42. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/supervisors/test_signal.py +0 -0
  43. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/test_default_headers.py +0 -0
  44. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/test_lifespan.py +0 -0
  45. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/test_ssl.py +0 -0
  46. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/test_subprocess.py +0 -0
  47. {uvicorn-0.33.0 → uvicorn-0.34.1}/tests/utils.py +0 -0
  48. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/__main__.py +0 -0
  49. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/_subprocess.py +0 -0
  50. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/importer.py +0 -0
  51. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/lifespan/__init__.py +0 -0
  52. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/lifespan/off.py +0 -0
  53. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/lifespan/on.py +0 -0
  54. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/logging.py +0 -0
  55. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/loops/__init__.py +0 -0
  56. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/loops/asyncio.py +0 -0
  57. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/loops/auto.py +0 -0
  58. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/loops/uvloop.py +0 -0
  59. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/middleware/__init__.py +0 -0
  60. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/middleware/asgi2.py +0 -0
  61. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/middleware/message_logger.py +0 -0
  62. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/middleware/proxy_headers.py +0 -0
  63. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/__init__.py +0 -0
  64. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/http/__init__.py +0 -0
  65. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/http/auto.py +0 -0
  66. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/http/flow_control.py +0 -0
  67. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/http/h11_impl.py +0 -0
  68. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/http/httptools_impl.py +0 -0
  69. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/utils.py +0 -0
  70. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/websockets/__init__.py +0 -0
  71. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/protocols/websockets/auto.py +0 -0
  72. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/py.typed +0 -0
  73. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/supervisors/__init__.py +0 -0
  74. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/supervisors/multiprocess.py +0 -0
  75. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/supervisors/watchfilesreload.py +0 -0
  76. {uvicorn-0.33.0 → uvicorn-0.34.1}/uvicorn/workers.py +0 -0
@@ -1,5 +1,6 @@
1
1
  .cache
2
2
  .coverage
3
+ .coverage.*
3
4
  .mypy_cache/
4
5
  __pycache__/
5
6
  uvicorn.egg-info/
@@ -1,20 +1,20 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: uvicorn
3
- Version: 0.33.0
3
+ Version: 0.34.1
4
4
  Summary: The lightning-fast ASGI server.
5
- Project-URL: Changelog, https://github.com/encode/uvicorn/blob/master/CHANGELOG.md
5
+ Project-URL: Changelog, https://www.uvicorn.org/release-notes
6
6
  Project-URL: Funding, https://github.com/sponsors/encode
7
7
  Project-URL: Homepage, https://www.uvicorn.org/
8
8
  Project-URL: Source, https://github.com/encode/uvicorn
9
9
  Author-email: Tom Christie <tom@tomchristie.com>, Marcelo Trylesinski <marcelotryle@gmail.com>
10
- License: BSD-3-Clause
10
+ License-Expression: BSD-3-Clause
11
+ License-File: LICENSE.md
11
12
  Classifier: Development Status :: 4 - Beta
12
13
  Classifier: Environment :: Web Environment
13
14
  Classifier: Intended Audience :: Developers
14
15
  Classifier: License :: OSI Approved :: BSD License
15
16
  Classifier: Operating System :: OS Independent
16
17
  Classifier: Programming Language :: Python :: 3
17
- Classifier: Programming Language :: Python :: 3.8
18
18
  Classifier: Programming Language :: Python :: 3.9
19
19
  Classifier: Programming Language :: Python :: 3.10
20
20
  Classifier: Programming Language :: Python :: 3.11
@@ -23,7 +23,7 @@ Classifier: Programming Language :: Python :: 3.13
23
23
  Classifier: Programming Language :: Python :: Implementation :: CPython
24
24
  Classifier: Programming Language :: Python :: Implementation :: PyPy
25
25
  Classifier: Topic :: Internet :: WWW/HTTP
26
- Requires-Python: >=3.8
26
+ Requires-Python: >=3.9
27
27
  Requires-Dist: click>=7.0
28
28
  Requires-Dist: h11>=0.8
29
29
  Requires-Dist: typing-extensions>=4.0; python_version < '3.11'
@@ -8,7 +8,7 @@ dynamic = ["version"]
8
8
  description = "The lightning-fast ASGI server."
9
9
  readme = "README.md"
10
10
  license = "BSD-3-Clause"
11
- requires-python = ">=3.8"
11
+ requires-python = ">=3.9"
12
12
  authors = [
13
13
  { name = "Tom Christie", email = "tom@tomchristie.com" },
14
14
  { name = "Marcelo Trylesinski", email = "marcelotryle@gmail.com" },
@@ -20,7 +20,6 @@ classifiers = [
20
20
  "License :: OSI Approved :: BSD License",
21
21
  "Operating System :: OS Independent",
22
22
  "Programming Language :: Python :: 3",
23
- "Programming Language :: Python :: 3.8",
24
23
  "Programming Language :: Python :: 3.9",
25
24
  "Programming Language :: Python :: 3.10",
26
25
  "Programming Language :: Python :: 3.11",
@@ -38,7 +37,7 @@ dependencies = [
38
37
 
39
38
  [project.optional-dependencies]
40
39
  standard = [
41
- "colorama>=0.4;sys_platform == 'win32'",
40
+ "colorama>=0.4; sys_platform == 'win32'",
42
41
  "httptools>=0.6.3",
43
42
  "python-dotenv>=0.13",
44
43
  "PyYAML>=5.1",
@@ -51,7 +50,7 @@ standard = [
51
50
  uvicorn = "uvicorn.main:main"
52
51
 
53
52
  [project.urls]
54
- Changelog = "https://github.com/encode/uvicorn/blob/master/CHANGELOG.md"
53
+ Changelog = "https://www.uvicorn.org/release-notes"
55
54
  Funding = "https://github.com/sponsors/encode"
56
55
  Homepage = "https://www.uvicorn.org/"
57
56
  Source = "https://github.com/encode/uvicorn"
@@ -86,7 +85,7 @@ disallow_untyped_defs = false
86
85
  check_untyped_defs = true
87
86
 
88
87
  [tool.pytest.ini_options]
89
- addopts = "-rxXs --strict-config --strict-markers"
88
+ addopts = "-rxXs --strict-config --strict-markers -n 8"
90
89
  xfail_strict = true
91
90
  filterwarnings = [
92
91
  "error",
@@ -96,6 +95,7 @@ filterwarnings = [
96
95
  ]
97
96
 
98
97
  [tool.coverage.run]
98
+ parallel = true
99
99
  source_pkgs = ["uvicorn", "tests"]
100
100
  plugins = ["coverage_conditional_plugin"]
101
101
  omit = ["uvicorn/workers.py", "uvicorn/__main__.py"]
@@ -126,9 +126,8 @@ exclude_lines = [
126
126
  py-win32 = "sys_platform == 'win32'"
127
127
  py-not-win32 = "sys_platform != 'win32'"
128
128
  py-linux = "sys_platform == 'linux'"
129
+ py-not-linux = "sys_platform != 'linux'"
129
130
  py-darwin = "sys_platform == 'darwin'"
130
- py-gte-38 = "sys_version_info >= (3, 8)"
131
- py-lt-38 = "sys_version_info < (3, 8)"
132
131
  py-gte-39 = "sys_version_info >= (3, 9)"
133
132
  py-lt-39 = "sys_version_info < (3, 9)"
134
133
  py-gte-310 = "sys_version_info >= (3, 10)"
@@ -5,29 +5,29 @@
5
5
  h11 @ git+https://github.com/python-hyper/h11.git@master
6
6
 
7
7
  # Explicit optionals
8
- a2wsgi==1.10.7
8
+ a2wsgi==1.10.8
9
9
  wsproto==1.2.0
10
10
  websockets==13.1
11
11
 
12
12
  # Packaging
13
13
  build==1.2.2.post1
14
- twine==6.0.1
14
+ twine==6.1.0
15
15
 
16
16
  # Testing
17
- ruff==0.8.3
18
- pytest==8.3.4
17
+ ruff==0.11.2
18
+ pytest==8.3.5
19
19
  pytest-mock==3.14.0
20
- mypy==1.13.0
20
+ pytest-xdist[psutil]==3.6.1
21
+ mypy==1.15.0
21
22
  types-click==7.1.8
22
- types-pyyaml==6.0.12.20240917
23
- trustme==1.1.0; python_version < '3.9'
24
- trustme==1.2.0; python_version >= '3.9'
25
- cryptography==44.0.0
26
- coverage==7.6.1; python_version < '3.9'
27
- coverage==7.6.9; python_version >= '3.9'
23
+ types-pyyaml==6.0.12.20250326
24
+ trustme==1.2.1
25
+ cryptography==44.0.2
26
+ coverage==7.8.0
28
27
  coverage-conditional-plugin==0.9.0
28
+ coverage-enable-subprocess==1.0
29
29
  httpx==0.28.1
30
30
 
31
31
  # Documentation
32
32
  mkdocs==1.6.1
33
- mkdocs-material==9.5.48
33
+ mkdocs-material==9.6.10
@@ -2,7 +2,8 @@ from __future__ import annotations
2
2
 
3
3
  import io
4
4
  import sys
5
- from typing import AsyncGenerator, Callable
5
+ from collections.abc import AsyncGenerator
6
+ from typing import Callable
6
7
 
7
8
  import a2wsgi
8
9
  import httpx
@@ -14,8 +14,8 @@ from uvicorn._types import ASGIApplication, ASGIReceiveCallable, ASGISendCallabl
14
14
  from uvicorn.config import WS_PROTOCOLS, Config
15
15
  from uvicorn.lifespan.off import LifespanOff
16
16
  from uvicorn.lifespan.on import LifespanOn
17
- from uvicorn.main import ServerState
18
17
  from uvicorn.protocols.http.h11_impl import H11Protocol
18
+ from uvicorn.server import ServerState
19
19
 
20
20
  try:
21
21
  from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol
@@ -914,7 +914,7 @@ def test_fragmentation(unused_tcp_port: int):
914
914
  def send_fragmented_req(path: str):
915
915
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
916
916
  sock.connect(("127.0.0.1", unused_tcp_port))
917
- d = (f"GET {path} HTTP/1.1\r\n" "Host: localhost\r\n" "Connection: close\r\n\r\n").encode()
917
+ d = (f"GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").encode()
918
918
  split = len(path) // 2
919
919
  sock.sendall(d[:split])
920
920
  time.sleep(0.01)
@@ -9,7 +9,6 @@ import pytest
9
9
  import websockets
10
10
  import websockets.client
11
11
  import websockets.exceptions
12
- from typing_extensions import TypedDict
13
12
  from websockets.extensions.permessage_deflate import ClientPerMessageDeflateFactory
14
13
  from websockets.typing import Subprotocol
15
14
 
@@ -109,17 +108,14 @@ async def test_invalid_upgrade(ws_protocol_cls: WSProtocol, http_protocol_cls: H
109
108
  pass # ok, wsproto 0.13
110
109
  else:
111
110
  assert response.status_code == 400
112
- assert (
113
- response.text.lower().strip().rstrip(".")
114
- in [
115
- "missing sec-websocket-key header",
116
- "missing sec-websocket-version header", # websockets
117
- "missing or empty sec-websocket-key header", # wsproto
118
- "failed to open a websocket connection: missing " "sec-websocket-key header",
119
- "failed to open a websocket connection: missing or empty " "sec-websocket-key header",
120
- "failed to open a websocket connection: missing sec-websocket-key header; 'sec-websocket-key'",
121
- ]
122
- )
111
+ assert response.text.lower().strip().rstrip(".") in [
112
+ "missing sec-websocket-key header",
113
+ "missing sec-websocket-version header", # websockets
114
+ "missing or empty sec-websocket-key header", # wsproto
115
+ "failed to open a websocket connection: missing sec-websocket-key header",
116
+ "failed to open a websocket connection: missing or empty sec-websocket-key header",
117
+ "failed to open a websocket connection: missing sec-websocket-key header; 'sec-websocket-key'",
118
+ ]
123
119
 
124
120
 
125
121
  async def test_accept_connection(ws_protocol_cls: WSProtocol, http_protocol_cls: HTTPProtocol, unused_tcp_port: int):
@@ -780,7 +776,7 @@ async def test_server_reject_connection(
780
776
  assert disconnected_message == {"type": "websocket.disconnect", "code": 1006}
781
777
 
782
778
 
783
- class EmptyDict(TypedDict): ...
779
+ class EmptyDict(typing.TypedDict): ...
784
780
 
785
781
 
786
782
  async def test_server_reject_connection_with_response(
@@ -1020,7 +1016,7 @@ async def test_server_multiple_websocket_http_response_start_events(
1020
1016
  await websocket_session(f"ws://127.0.0.1:{unused_tcp_port}")
1021
1017
 
1022
1018
  assert exception_message == (
1023
- "Expected ASGI message 'websocket.http.response.body' but got " "'websocket.http.response.start'."
1019
+ "Expected ASGI message 'websocket.http.response.body' but got 'websocket.http.response.start'."
1024
1020
  )
1025
1021
 
1026
1022
 
@@ -1,13 +1,13 @@
1
1
  from __future__ import annotations
2
2
 
3
- import platform
4
3
  import signal
5
4
  import socket
6
5
  import sys
6
+ from collections.abc import Generator
7
7
  from pathlib import Path
8
8
  from threading import Thread
9
9
  from time import sleep
10
- from typing import Callable, Generator
10
+ from typing import Callable
11
11
 
12
12
  import pytest
13
13
  from pytest_mock import MockerFixture
@@ -23,11 +23,8 @@ except ImportError: # pragma: no cover
23
23
  WatchFilesReload = None # type: ignore[misc,assignment]
24
24
 
25
25
 
26
- # TODO: Investigate why this is flaky on MacOS M1.
27
- skip_if_m1 = pytest.mark.skipif(
28
- sys.platform == "darwin" and platform.processor() == "arm",
29
- reason="Flaky on MacOS M1",
30
- )
26
+ # TODO: Investigate why this is flaky on MacOS, and Windows.
27
+ skip_non_linux = pytest.mark.skipif(sys.platform in ("darwin", "win32"), reason="Flaky on Windows and MacOS")
31
28
 
32
29
 
33
30
  def run(sockets: list[socket.socket] | None) -> None:
@@ -98,7 +95,7 @@ class TestBaseReload:
98
95
  reloader = self._setup_reloader(config)
99
96
  reloader.shutdown()
100
97
 
101
- @pytest.mark.parametrize("reloader_class", [StatReload, WatchFilesReload])
98
+ @pytest.mark.parametrize("reloader_class", [StatReload, pytest.param(WatchFilesReload, marks=skip_non_linux)])
102
99
  def test_reload_when_python_file_is_changed(self, touch_soon: Callable[[Path], None]):
103
100
  file = self.reload_path / "main.py"
104
101
 
@@ -140,8 +137,12 @@ class TestBaseReload:
140
137
 
141
138
  reloader.shutdown()
142
139
 
143
- @pytest.mark.parametrize("reloader_class, result", [(StatReload, False), (WatchFilesReload, True)])
144
- def test_reload_when_pattern_matched_file_is_changed(self, result: bool, touch_soon: Callable[[Path], None]):
140
+ @pytest.mark.parametrize(
141
+ "reloader_class, result", [(StatReload, False), pytest.param(WatchFilesReload, True, marks=skip_non_linux)]
142
+ )
143
+ def test_reload_when_pattern_matched_file_is_changed(
144
+ self, result: bool, touch_soon: Callable[[Path], None]
145
+ ): # pragma: py-not-linux
145
146
  file = self.reload_path / "app" / "js" / "main.js"
146
147
 
147
148
  with as_cwd(self.reload_path):
@@ -152,10 +153,10 @@ class TestBaseReload:
152
153
 
153
154
  reloader.shutdown()
154
155
 
155
- @pytest.mark.parametrize("reloader_class", [pytest.param(WatchFilesReload, marks=skip_if_m1)])
156
+ @pytest.mark.parametrize("reloader_class", [pytest.param(WatchFilesReload, marks=skip_non_linux)])
156
157
  def test_should_not_reload_when_exclude_pattern_match_file_is_changed(
157
158
  self, touch_soon: Callable[[Path], None]
158
- ): # pragma: py-darwin
159
+ ): # pragma: py-not-linux
159
160
  python_file = self.reload_path / "app" / "src" / "main.py"
160
161
  css_file = self.reload_path / "app" / "css" / "main.css"
161
162
  js_file = self.reload_path / "app" / "js" / "main.js"
@@ -187,8 +188,10 @@ class TestBaseReload:
187
188
 
188
189
  reloader.shutdown()
189
190
 
190
- @pytest.mark.parametrize("reloader_class", [StatReload, WatchFilesReload])
191
- def test_should_reload_when_directories_have_same_prefix(self, touch_soon: Callable[[Path], None]):
191
+ @pytest.mark.parametrize("reloader_class", [StatReload, pytest.param(WatchFilesReload, marks=skip_non_linux)])
192
+ def test_should_reload_when_directories_have_same_prefix(
193
+ self, touch_soon: Callable[[Path], None]
194
+ ): # pragma: py-not-linux
192
195
  app_dir = self.reload_path / "app"
193
196
  app_file = app_dir / "src" / "main.py"
194
197
  app_first_dir = self.reload_path / "app_first"
@@ -209,9 +212,11 @@ class TestBaseReload:
209
212
 
210
213
  @pytest.mark.parametrize(
211
214
  "reloader_class",
212
- [StatReload, pytest.param(WatchFilesReload, marks=skip_if_m1)],
215
+ [StatReload, pytest.param(WatchFilesReload, marks=skip_non_linux)],
213
216
  )
214
- def test_should_not_reload_when_only_subdirectory_is_watched(self, touch_soon: Callable[[Path], None]):
217
+ def test_should_not_reload_when_only_subdirectory_is_watched(
218
+ self, touch_soon: Callable[[Path], None]
219
+ ): # pragma: py-not-linux
215
220
  app_dir = self.reload_path / "app"
216
221
  app_dir_file = self.reload_path / "app" / "src" / "main.py"
217
222
  root_file = self.reload_path / "main.py"
@@ -228,8 +233,8 @@ class TestBaseReload:
228
233
 
229
234
  reloader.shutdown()
230
235
 
231
- @pytest.mark.parametrize("reloader_class", [pytest.param(WatchFilesReload, marks=skip_if_m1)])
232
- def test_override_defaults(self, touch_soon: Callable[[Path], None]) -> None: # pragma: py-darwin
236
+ @pytest.mark.parametrize("reloader_class", [pytest.param(WatchFilesReload, marks=skip_non_linux)])
237
+ def test_override_defaults(self, touch_soon: Callable[[Path], None]) -> None: # pragma: py-not-linux
233
238
  dotted_file = self.reload_path / ".dotted"
234
239
  dotted_dir_file = self.reload_path / ".dotted_dir" / "file.txt"
235
240
  python_file = self.reload_path / "main.py"
@@ -250,8 +255,8 @@ class TestBaseReload:
250
255
 
251
256
  reloader.shutdown()
252
257
 
253
- @pytest.mark.parametrize("reloader_class", [pytest.param(WatchFilesReload, marks=skip_if_m1)])
254
- def test_explicit_paths(self, touch_soon: Callable[[Path], None]) -> None: # pragma: py-darwin
258
+ @pytest.mark.parametrize("reloader_class", [pytest.param(WatchFilesReload, marks=skip_non_linux)])
259
+ def test_explicit_paths(self, touch_soon: Callable[[Path], None]) -> None: # pragma: py-not-linux
255
260
  dotted_file = self.reload_path / ".dotted"
256
261
  non_dotted_file = self.reload_path / "ext" / "ext.jpg"
257
262
  python_file = self.reload_path / "main.py"
@@ -5,9 +5,9 @@ import pytest
5
5
 
6
6
  from uvicorn.config import Config
7
7
  from uvicorn.loops.auto import auto_loop_setup
8
- from uvicorn.main import ServerState
9
8
  from uvicorn.protocols.http.auto import AutoHTTPProtocol
10
9
  from uvicorn.protocols.websockets.auto import AutoWebSocketsProtocol
10
+ from uvicorn.server import ServerState
11
11
 
12
12
  try:
13
13
  importlib.import_module("uvloop")
@@ -3,9 +3,9 @@ import importlib
3
3
  import os
4
4
  import platform
5
5
  import sys
6
+ from collections.abc import Iterator
6
7
  from pathlib import Path
7
8
  from textwrap import dedent
8
- from typing import Iterator
9
9
  from unittest import mock
10
10
 
11
11
  import pytest
@@ -131,7 +131,7 @@ def test_cli_incomplete_app_parameter() -> None:
131
131
  result = runner.invoke(cli, ["tests.test_cli"])
132
132
 
133
133
  assert (
134
- 'Error loading ASGI app. Import string "tests.test_cli" ' 'must be in format "<module>:<attribute>".'
134
+ 'Error loading ASGI app. Import string "tests.test_cli" must be in format "<module>:<attribute>".'
135
135
  ) in result.output
136
136
  assert result.exit_code == 1
137
137
 
@@ -409,7 +409,7 @@ def test_env_file(
409
409
  Test that one can load environment variables using an env file.
410
410
  """
411
411
  fp = tmp_path / ".env"
412
- content = f"WEB_CONCURRENCY={web_concurrency}\n" f"FORWARDED_ALLOW_IPS={forwarded_allow_ips}\n"
412
+ content = f"WEB_CONCURRENCY={web_concurrency}\nFORWARDED_ALLOW_IPS={forwarded_allow_ips}\n"
413
413
  fp.write_text(content)
414
414
  with caplog.at_level(logging.INFO):
415
415
  config = Config(app=asgi_app, env_file=fp)
@@ -1,3 +1,4 @@
1
+ import importlib
1
2
  import inspect
2
3
  import socket
3
4
  from logging import WARNING
@@ -5,6 +6,7 @@ from logging import WARNING
5
6
  import httpx
6
7
  import pytest
7
8
 
9
+ import uvicorn.server
8
10
  from tests.utils import run_server
9
11
  from uvicorn import Server
10
12
  from uvicorn._types import ASGIReceiveCallable, ASGISendCallable, Scope
@@ -79,7 +81,7 @@ def test_run_invalid_app_config_combination(caplog: pytest.LogCaptureFixture) ->
79
81
  assert caplog.records[-1].name == "uvicorn.error"
80
82
  assert caplog.records[-1].levelno == WARNING
81
83
  assert caplog.records[-1].message == (
82
- "You must pass the application as an import string to enable " "'reload' or 'workers'."
84
+ "You must pass the application as an import string to enable 'reload' or 'workers'."
83
85
  )
84
86
 
85
87
 
@@ -113,3 +115,12 @@ async def test_exit_on_create_server_with_invalid_host() -> None:
113
115
  server = Server(config=config)
114
116
  await server.serve()
115
117
  assert exc_info.value.code == 1
118
+
119
+
120
+ def test_deprecated_server_state_from_main() -> None:
121
+ with pytest.deprecated_call(
122
+ match="uvicorn.main.ServerState is deprecated, use uvicorn.server.ServerState instead."
123
+ ):
124
+ main = importlib.import_module("uvicorn.main")
125
+ server_state_cls = getattr(main, "ServerState")
126
+ assert server_state_cls is uvicorn.server.ServerState
@@ -5,7 +5,9 @@ import contextlib
5
5
  import logging
6
6
  import signal
7
7
  import sys
8
- from typing import Callable, ContextManager, Generator
8
+ from collections.abc import Generator
9
+ from contextlib import AbstractContextManager
10
+ from typing import Callable
9
11
 
10
12
  import httpx
11
13
  import pytest
@@ -62,7 +64,9 @@ else: # pragma: py-win32
62
64
  @pytest.mark.parametrize("exception_signal", signals)
63
65
  @pytest.mark.parametrize("capture_signal", signal_captures)
64
66
  async def test_server_interrupt(
65
- exception_signal: signal.Signals, capture_signal: Callable[[signal.Signals], ContextManager[None]]
67
+ exception_signal: signal.Signals,
68
+ capture_signal: Callable[[signal.Signals], AbstractContextManager[None]],
69
+ unused_tcp_port: int,
66
70
  ): # pragma: py-win32
67
71
  """Test interrupting a Server that is run explicitly inside asyncio"""
68
72
 
@@ -71,7 +75,7 @@ async def test_server_interrupt(
71
75
  await asyncio.sleep(0.01)
72
76
  signal.raise_signal(exception_signal)
73
77
 
74
- server = Server(Config(app=dummy_app, loop="asyncio"))
78
+ server = Server(Config(app=dummy_app, loop="asyncio", port=unused_tcp_port))
75
79
  asyncio.create_task(interrupt_running(server))
76
80
  with capture_signal(exception_signal) as witness:
77
81
  await server.serve()
@@ -1,5 +1,5 @@
1
1
  from uvicorn.config import Config
2
2
  from uvicorn.main import Server, main, run
3
3
 
4
- __version__ = "0.33.0"
4
+ __version__ = "0.34.1"
5
5
  __all__ = ["main", "run", "Config", "Server"]
@@ -32,20 +32,8 @@ from __future__ import annotations
32
32
 
33
33
  import sys
34
34
  import types
35
- from typing import (
36
- Any,
37
- Awaitable,
38
- Callable,
39
- Iterable,
40
- Literal,
41
- MutableMapping,
42
- Optional,
43
- Protocol,
44
- Tuple,
45
- Type,
46
- TypedDict,
47
- Union,
48
- )
35
+ from collections.abc import Awaitable, Iterable, MutableMapping
36
+ from typing import Any, Callable, Literal, Optional, Protocol, TypedDict, Union
49
37
 
50
38
  if sys.version_info >= (3, 11): # pragma: py-lt-311
51
39
  from typing import NotRequired
@@ -54,8 +42,8 @@ else: # pragma: py-gte-311
54
42
 
55
43
  # WSGI
56
44
  Environ = MutableMapping[str, Any]
57
- ExcInfo = Tuple[Type[BaseException], BaseException, Optional[types.TracebackType]]
58
- StartResponse = Callable[[str, Iterable[Tuple[str, str]], Optional[ExcInfo]], None]
45
+ ExcInfo = tuple[type[BaseException], BaseException, Optional[types.TracebackType]]
46
+ StartResponse = Callable[[str, Iterable[tuple[str, str]], Optional[ExcInfo]], None]
59
47
  WSGIApp = Callable[[Environ, StartResponse], Union[Iterable[bytes], BaseException]]
60
48
 
61
49
 
@@ -281,7 +269,7 @@ class ASGI2Protocol(Protocol):
281
269
  async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... # pragma: no cover
282
270
 
283
271
 
284
- ASGI2Application = Type[ASGI2Protocol]
272
+ ASGI2Application = type[ASGI2Protocol]
285
273
  ASGI3Application = Callable[
286
274
  [
287
275
  Scope,
@@ -9,9 +9,10 @@ import os
9
9
  import socket
10
10
  import ssl
11
11
  import sys
12
+ from collections.abc import Awaitable
12
13
  from configparser import RawConfigParser
13
14
  from pathlib import Path
14
- from typing import IO, Any, Awaitable, Callable, Literal
15
+ from typing import IO, Any, Callable, Literal
15
16
 
16
17
  import click
17
18
 
@@ -137,7 +138,7 @@ def resolve_reload_patterns(patterns_list: list[str], directories_list: list[str
137
138
  # Special case for the .* pattern, otherwise this would only match
138
139
  # hidden directories which is probably undesired
139
140
  if pattern == ".*":
140
- continue # pragma: py-darwin
141
+ continue # pragma: py-not-linux
141
142
  patterns.append(pattern)
142
143
  if is_dir(Path(pattern)):
143
144
  directories.append(Path(pattern))
@@ -279,7 +280,7 @@ class Config:
279
280
 
280
281
  if (reload_dirs or reload_includes or reload_excludes) and not self.should_reload:
281
282
  logger.warning(
282
- "Current configuration will not reload as not all conditions are met, " "please refer to documentation."
283
+ "Current configuration will not reload as not all conditions are met, please refer to documentation."
283
284
  )
284
285
 
285
286
  if self.should_reload:
@@ -445,7 +446,7 @@ class Config:
445
446
  else:
446
447
  if not self.factory:
447
448
  logger.warning(
448
- "ASGI app factory detected. Using it, " "but please consider setting the --factory flag explicitly."
449
+ "ASGI app factory detected. Using it, but please consider setting the --factory flag explicitly."
449
450
  )
450
451
 
451
452
  if self.interface == "auto":
@@ -6,6 +6,7 @@ import os
6
6
  import platform
7
7
  import ssl
8
8
  import sys
9
+ import warnings
9
10
  from configparser import RawConfigParser
10
11
  from typing import IO, Any, Callable
11
12
 
@@ -29,7 +30,7 @@ from uvicorn.config import (
29
30
  LoopSetupType,
30
31
  WSProtocolType,
31
32
  )
32
- from uvicorn.server import Server, ServerState # noqa: F401 # Used to be defined here.
33
+ from uvicorn.server import Server
33
34
  from uvicorn.supervisors import ChangeReload, Multiprocess
34
35
 
35
36
  LEVEL_CHOICES = click.Choice(list(LOG_LEVELS.keys()))
@@ -81,7 +82,7 @@ def print_version(ctx: click.Context, param: click.Parameter, value: bool) -> No
81
82
  "--reload-dir",
82
83
  "reload_dirs",
83
84
  multiple=True,
84
- help="Set reload directories explicitly, instead of using the current working" " directory.",
85
+ help="Set reload directories explicitly, instead of using the current working directory.",
85
86
  type=click.Path(exists=True),
86
87
  )
87
88
  @click.option(
@@ -106,7 +107,7 @@ def print_version(ctx: click.Context, param: click.Parameter, value: bool) -> No
106
107
  type=float,
107
108
  default=0.25,
108
109
  show_default=True,
109
- help="Delay between previous and next check if application needs to be." " Defaults to 0.25s.",
110
+ help="Delay between previous and next check if application needs to be. Defaults to 0.25s.",
110
111
  )
111
112
  @click.option(
112
113
  "--workers",
@@ -222,7 +223,7 @@ def print_version(ctx: click.Context, param: click.Parameter, value: bool) -> No
222
223
  "--proxy-headers/--no-proxy-headers",
223
224
  is_flag=True,
224
225
  default=True,
225
- help="Enable/Disable X-Forwarded-Proto, X-Forwarded-For, X-Forwarded-Port to " "populate remote address info.",
226
+ help="Enable/Disable X-Forwarded-Proto, X-Forwarded-For, X-Forwarded-Port to populate remote address info.",
226
227
  )
227
228
  @click.option(
228
229
  "--server-header/--no-server-header",
@@ -255,7 +256,7 @@ def print_version(ctx: click.Context, param: click.Parameter, value: bool) -> No
255
256
  "--limit-concurrency",
256
257
  type=int,
257
258
  default=None,
258
- help="Maximum number of concurrent connections or tasks to allow, before issuing" " HTTP 503 responses.",
259
+ help="Maximum number of concurrent connections or tasks to allow, before issuing HTTP 503 responses.",
259
260
  )
260
261
  @click.option(
261
262
  "--backlog",
@@ -565,7 +566,7 @@ def run(
565
566
 
566
567
  if (config.reload or config.workers > 1) and not isinstance(app, str):
567
568
  logger = logging.getLogger("uvicorn.error")
568
- logger.warning("You must pass the application as an import string to enable 'reload' or " "'workers'.")
569
+ logger.warning("You must pass the application as an import string to enable 'reload' or 'workers'.")
569
570
  sys.exit(1)
570
571
 
571
572
  try:
@@ -587,5 +588,17 @@ def run(
587
588
  sys.exit(STARTUP_FAILURE)
588
589
 
589
590
 
591
+ def __getattr__(name: str) -> Any:
592
+ if name == "ServerState":
593
+ warnings.warn(
594
+ "uvicorn.main.ServerState is deprecated, use uvicorn.server.ServerState instead.",
595
+ DeprecationWarning,
596
+ )
597
+ from uvicorn.server import ServerState
598
+
599
+ return ServerState
600
+ raise AttributeError(f"module {__name__} has no attribute {name}")
601
+
602
+
590
603
  if __name__ == "__main__":
591
604
  main() # pragma: no cover
@@ -6,7 +6,7 @@ import io
6
6
  import sys
7
7
  import warnings
8
8
  from collections import deque
9
- from typing import Iterable
9
+ from collections.abc import Iterable
10
10
 
11
11
  from uvicorn._types import (
12
12
  ASGIReceiveCallable,
@@ -82,8 +82,7 @@ def build_environ(scope: HTTPScope, message: ASGIReceiveEvent, body: io.BytesIO)
82
82
  class _WSGIMiddleware:
83
83
  def __init__(self, app: WSGIApp, workers: int = 10):
84
84
  warnings.warn(
85
- "Uvicorn's native WSGI implementation is deprecated, you "
86
- "should switch to a2wsgi (`pip install a2wsgi`).",
85
+ "Uvicorn's native WSGI implementation is deprecated, you should switch to a2wsgi (`pip install a2wsgi`).",
87
86
  DeprecationWarning,
88
87
  )
89
88
  self.app = app
@@ -3,7 +3,8 @@ from __future__ import annotations
3
3
  import asyncio
4
4
  import http
5
5
  import logging
6
- from typing import Any, Literal, Optional, Sequence, cast
6
+ from collections.abc import Sequence
7
+ from typing import Any, Literal, Optional, cast
7
8
  from urllib.parse import unquote
8
9
 
9
10
  import websockets
@@ -213,7 +214,7 @@ class WebSocketProtocol(WebSocketServerProtocol):
213
214
  def send_500_response(self) -> None:
214
215
  msg = b"Internal Server Error"
215
216
  content = [
216
- b"HTTP/1.1 500 Internal Server Error\r\n" b"content-type: text/plain; charset=utf-8\r\n",
217
+ b"HTTP/1.1 500 Internal Server Error\r\ncontent-type: text/plain; charset=utf-8\r\n",
217
218
  b"content-length: " + str(len(msg)).encode("ascii") + b"\r\n",
218
219
  b"connection: close\r\n",
219
220
  b"\r\n",
@@ -337,7 +338,7 @@ class WebSocketProtocol(WebSocketServerProtocol):
337
338
  self.closed_event.set()
338
339
 
339
340
  else:
340
- msg = "Expected ASGI message 'websocket.send' or 'websocket.close'," " but got '%s'."
341
+ msg = "Expected ASGI message 'websocket.send' or 'websocket.close', but got '%s'."
341
342
  raise RuntimeError(msg % message_type)
342
343
  except ConnectionClosed as exc:
343
344
  raise ClientDisconnected from exc
@@ -350,11 +351,11 @@ class WebSocketProtocol(WebSocketServerProtocol):
350
351
  if not message.get("more_body", False):
351
352
  self.closed_event.set()
352
353
  else:
353
- msg = "Expected ASGI message 'websocket.http.response.body' " "but got '%s'."
354
+ msg = "Expected ASGI message 'websocket.http.response.body' but got '%s'."
354
355
  raise RuntimeError(msg % message_type)
355
356
 
356
357
  else:
357
- msg = "Unexpected ASGI message '%s', after sending 'websocket.close' " "or response already completed."
358
+ msg = "Unexpected ASGI message '%s', after sending 'websocket.close' or response already completed."
358
359
  raise RuntimeError(msg % message_type)
359
360
 
360
361
  async def asgi_receive(self) -> WebSocketDisconnectEvent | WebSocketConnectEvent | WebSocketReceiveEvent:
@@ -224,6 +224,7 @@ class WSProtocol(asyncio.Protocol):
224
224
  headers: list[tuple[bytes, bytes]] = [
225
225
  (b"content-type", b"text/plain; charset=utf-8"),
226
226
  (b"connection", b"close"),
227
+ (b"content-length", b"21"),
227
228
  ]
228
229
  output = self.conn.send(wsproto.events.RejectConnection(status_code=500, headers=headers, has_body=True))
229
230
  output += self.conn.send(wsproto.events.RejectData(data=b"Internal Server Error"))
@@ -343,7 +344,7 @@ class WSProtocol(asyncio.Protocol):
343
344
  self.transport.close()
344
345
 
345
346
  else:
346
- msg = "Expected ASGI message 'websocket.send' or 'websocket.close'," " but got '%s'."
347
+ msg = "Expected ASGI message 'websocket.send' or 'websocket.close', but got '%s'."
347
348
  raise RuntimeError(msg % message_type)
348
349
  except LocalProtocolError as exc:
349
350
  raise ClientDisconnected from exc
@@ -361,7 +362,7 @@ class WSProtocol(asyncio.Protocol):
361
362
  self.transport.close()
362
363
 
363
364
  else:
364
- msg = "Expected ASGI message 'websocket.http.response.body' " "but got '%s'."
365
+ msg = "Expected ASGI message 'websocket.http.response.body' but got '%s'."
365
366
  raise RuntimeError(msg % message_type)
366
367
 
367
368
  else:
@@ -10,9 +10,10 @@ import socket
10
10
  import sys
11
11
  import threading
12
12
  import time
13
+ from collections.abc import Generator, Sequence
13
14
  from email.utils import formatdate
14
15
  from types import FrameType
15
- from typing import TYPE_CHECKING, Generator, Sequence, Union
16
+ from typing import TYPE_CHECKING, Union
16
17
 
17
18
  import click
18
19
 
@@ -118,7 +119,7 @@ class Server:
118
119
 
119
120
  def _share_socket(
120
121
  sock: socket.SocketType,
121
- ) -> socket.SocketType: # pragma py-linux pragma: py-darwin
122
+ ) -> socket.SocketType: # pragma py-not-win32
122
123
  # Windows requires the socket be explicitly shared across
123
124
  # multiple workers (processes).
124
125
  from socket import fromshare # type: ignore[attr-defined]
@@ -284,10 +285,7 @@ class Server:
284
285
  len(self.server_state.tasks),
285
286
  )
286
287
  for t in self.server_state.tasks:
287
- if sys.version_info < (3, 9): # pragma: py-gte-39
288
- t.cancel()
289
- else: # pragma: py-lt-39
290
- t.cancel(msg="Task cancelled, timeout graceful shutdown exceeded")
288
+ t.cancel(msg="Task cancelled, timeout graceful shutdown exceeded")
291
289
 
292
290
  # Send the lifespan shutdown event, and wait for application shutdown.
293
291
  if not self.force_exit:
@@ -5,10 +5,11 @@ import os
5
5
  import signal
6
6
  import sys
7
7
  import threading
8
+ from collections.abc import Iterator
8
9
  from pathlib import Path
9
10
  from socket import socket
10
11
  from types import FrameType
11
- from typing import Callable, Iterator
12
+ from typing import Callable
12
13
 
13
14
  import click
14
15
 
@@ -1,9 +1,10 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import logging
4
+ from collections.abc import Iterator
4
5
  from pathlib import Path
5
6
  from socket import socket
6
- from typing import Callable, Iterator
7
+ from typing import Callable
7
8
 
8
9
  from uvicorn.config import Config
9
10
  from uvicorn.supervisors.basereload import BaseReload
@@ -23,7 +24,7 @@ class StatReload(BaseReload):
23
24
  self.mtimes: dict[Path, float] = {}
24
25
 
25
26
  if config.reload_excludes or config.reload_includes:
26
- logger.warning("--reload-include and --reload-exclude have no effect unless " "watchfiles is installed.")
27
+ logger.warning("--reload-include and --reload-exclude have no effect unless watchfiles is installed.")
27
28
 
28
29
  def should_restart(self) -> list[Path] | None:
29
30
  self.pause()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes