asgiref 3.10.0__py3-none-any.whl → 3.11.1__py3-none-any.whl

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.
asgiref/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "3.10.0"
1
+ __version__ = "3.11.1"
asgiref/sync.py CHANGED
@@ -424,6 +424,7 @@ class SyncToAsync(Generic[_P, _R]):
424
424
  func: Callable[_P, _R],
425
425
  thread_sensitive: bool = True,
426
426
  executor: Optional["ThreadPoolExecutor"] = None,
427
+ context: Optional[contextvars.Context] = None,
427
428
  ) -> None:
428
429
  if (
429
430
  not callable(func)
@@ -431,8 +432,11 @@ class SyncToAsync(Generic[_P, _R]):
431
432
  or iscoroutinefunction(getattr(func, "__call__", func))
432
433
  ):
433
434
  raise TypeError("sync_to_async can only be applied to sync functions.")
434
- self.func = func
435
+
435
436
  functools.update_wrapper(self, func)
437
+ self.func = func
438
+ self.context = context
439
+
436
440
  self._thread_sensitive = thread_sensitive
437
441
  markcoroutinefunction(self)
438
442
  if thread_sensitive and executor is not None:
@@ -480,7 +484,7 @@ class SyncToAsync(Generic[_P, _R]):
480
484
  # Use the passed in executor, or the loop's default if it is None
481
485
  executor = self._executor
482
486
 
483
- context = contextvars.copy_context()
487
+ context = contextvars.copy_context() if self.context is None else self.context
484
488
  child = functools.partial(self.func, *args, **kwargs)
485
489
  func = context.run
486
490
  task_context: List[asyncio.Task[Any]] = []
@@ -518,7 +522,8 @@ class SyncToAsync(Generic[_P, _R]):
518
522
  exec_coro.cancel()
519
523
  ret = await exec_coro
520
524
  finally:
521
- _restore_context(context)
525
+ if self.context is None:
526
+ _restore_context(context)
522
527
  self.deadlock_context.set(False)
523
528
 
524
529
  return ret
@@ -611,6 +616,7 @@ def sync_to_async(
611
616
  *,
612
617
  thread_sensitive: bool = True,
613
618
  executor: Optional["ThreadPoolExecutor"] = None,
619
+ context: Optional[contextvars.Context] = None,
614
620
  ) -> Callable[[Callable[_P, _R]], Callable[_P, Coroutine[Any, Any, _R]]]:
615
621
  ...
616
622
 
@@ -621,6 +627,7 @@ def sync_to_async(
621
627
  *,
622
628
  thread_sensitive: bool = True,
623
629
  executor: Optional["ThreadPoolExecutor"] = None,
630
+ context: Optional[contextvars.Context] = None,
624
631
  ) -> Callable[_P, Coroutine[Any, Any, _R]]:
625
632
  ...
626
633
 
@@ -630,6 +637,7 @@ def sync_to_async(
630
637
  *,
631
638
  thread_sensitive: bool = True,
632
639
  executor: Optional["ThreadPoolExecutor"] = None,
640
+ context: Optional[contextvars.Context] = None,
633
641
  ) -> Union[
634
642
  Callable[[Callable[_P, _R]], Callable[_P, Coroutine[Any, Any, _R]]],
635
643
  Callable[_P, Coroutine[Any, Any, _R]],
@@ -639,9 +647,11 @@ def sync_to_async(
639
647
  f,
640
648
  thread_sensitive=thread_sensitive,
641
649
  executor=executor,
650
+ context=context,
642
651
  )
643
652
  return SyncToAsync(
644
653
  func,
645
654
  thread_sensitive=thread_sensitive,
646
655
  executor=executor,
656
+ context=context,
647
657
  )
asgiref/wsgi.py CHANGED
@@ -1,4 +1,5 @@
1
1
  import sys
2
+ from collections import defaultdict
2
3
  from tempfile import SpooledTemporaryFile
3
4
 
4
5
  from asgiref.sync import AsyncToSync, sync_to_async
@@ -9,8 +10,9 @@ class WsgiToAsgi:
9
10
  Wraps a WSGI application to make it into an ASGI application.
10
11
  """
11
12
 
12
- def __init__(self, wsgi_application):
13
+ def __init__(self, wsgi_application, duplicate_header_limit=100):
13
14
  self.wsgi_application = wsgi_application
15
+ self.duplicate_header_limit = duplicate_header_limit
14
16
 
15
17
  async def __call__(self, scope, receive, send):
16
18
  """
@@ -18,7 +20,9 @@ class WsgiToAsgi:
18
20
  We return a new WsgiToAsgiInstance here with the WSGI app
19
21
  and the scope, ready to respond when it is __call__ed.
20
22
  """
21
- await WsgiToAsgiInstance(self.wsgi_application)(scope, receive, send)
23
+ await WsgiToAsgiInstance(self.wsgi_application, self.duplicate_header_limit)(
24
+ scope, receive, send
25
+ )
22
26
 
23
27
 
24
28
  class WsgiToAsgiInstance:
@@ -26,8 +30,9 @@ class WsgiToAsgiInstance:
26
30
  Per-socket instance of a wrapped WSGI application
27
31
  """
28
32
 
29
- def __init__(self, wsgi_application):
33
+ def __init__(self, wsgi_application, duplicate_header_limit=100):
30
34
  self.wsgi_application = wsgi_application
35
+ self.duplicate_header_limit = duplicate_header_limit
31
36
  self.response_started = False
32
37
  self.response_content_length = None
33
38
 
@@ -84,6 +89,7 @@ class WsgiToAsgiInstance:
84
89
  environ["REMOTE_ADDR"] = scope["client"][0]
85
90
 
86
91
  # Go through headers and make them into environ entries
92
+ _headers = defaultdict(list)
87
93
  for name, value in self.scope.get("headers", []):
88
94
  name = name.decode("latin1")
89
95
  if name == "content-length":
@@ -94,9 +100,17 @@ class WsgiToAsgiInstance:
94
100
  corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
95
101
  # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
96
102
  value = value.decode("latin1")
97
- if corrected_name in environ:
98
- value = environ[corrected_name] + "," + value
99
- environ[corrected_name] = value
103
+ if (
104
+ self.duplicate_header_limit
105
+ and len(_headers[corrected_name]) >= self.duplicate_header_limit
106
+ ):
107
+ raise ValueError(
108
+ f"Too many duplicate headers: {corrected_name} exceeds limit of"
109
+ f"{self.duplicate_header_limit}"
110
+ )
111
+ _headers[corrected_name].append(value)
112
+ for name, values in _headers.items():
113
+ environ[name] = ",".join(values)
100
114
  return environ
101
115
 
102
116
  def start_response(self, status, response_headers, exc_info=None):
@@ -138,7 +152,24 @@ class WsgiToAsgiInstance:
138
152
  this so that the start_response callable is called in the same thread.
139
153
  """
140
154
  # Translate the scope and incoming request body into a WSGI environ
141
- environ = self.build_environ(self.scope, body)
155
+ try:
156
+ environ = self.build_environ(self.scope, body)
157
+ except ValueError:
158
+ # Return 400 Bad Request if header limit exceeded
159
+ self.sync_send(
160
+ {
161
+ "type": "http.response.start",
162
+ "status": 400,
163
+ "headers": [(b"content-type", b"text/plain")],
164
+ }
165
+ )
166
+ self.sync_send(
167
+ {
168
+ "type": "http.response.body",
169
+ "body": b"Bad Request: Too many duplicate headers",
170
+ }
171
+ )
172
+ return
142
173
  # Run the WSGI app
143
174
  bytes_sent = 0
144
175
  for output in self.wsgi_application(environ, self.start_response):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: asgiref
3
- Version: 3.10.0
3
+ Version: 3.11.1
4
4
  Summary: ASGI specs, helper code, and adapters
5
5
  Home-page: https://github.com/django/asgiref/
6
6
  Author: Django Software Foundation
@@ -1,16 +1,16 @@
1
- asgiref/__init__.py,sha256=iKJAvc5i0UTDDSSefTGL0Tq-kWQ4S3OJJgvyaQfQNF8,23
1
+ asgiref/__init__.py,sha256=UuKR3QjWk9sJtn2huDFsPdSgtx1CgiEl2B4BUtVRd58,23
2
2
  asgiref/compatibility.py,sha256=DhY1SOpOvOw0Y1lSEjCqg-znRUQKecG3LTaV48MZi68,1606
3
3
  asgiref/current_thread_executor.py,sha256=42CU1VODLTk-_PYise-cP1XgyAvI5Djc8f97owFzdrs,4157
4
4
  asgiref/local.py,sha256=ZZeWWIXptVU4GbNApMMWQ-skuglvodcQA5WpzJDMxh4,4912
5
5
  asgiref/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
6
  asgiref/server.py,sha256=3A68169Nuh2sTY_2O5JzRd_opKObWvvrEFcrXssq3kA,6311
7
- asgiref/sync.py,sha256=CEKxFyePiksUoA7MronOKaF6mmNQxUYZjXlfJZXEQCM,22551
7
+ asgiref/sync.py,sha256=KHjSkYRZKIJ1cmBvxcloGrcnhvAuEfXCWCZAoxN8grg,22929
8
8
  asgiref/testing.py,sha256=U5wcs_-ZYTO5SIGfl80EqRAGv_T8BHrAhvAKRuuztT4,4421
9
9
  asgiref/timeout.py,sha256=LtGL-xQpG8JHprdsEUCMErJ0kNWj4qwWZhEHJ3iKu4s,3627
10
10
  asgiref/typing.py,sha256=Zi72AZlOyF1C7N14LLZnpAdfUH4ljoBqFdQo_bBKMq0,6290
11
- asgiref/wsgi.py,sha256=J8OAgirfsYHZmxxqIGfFiZ43uq1qKKv2xGMkRISNIo4,6742
12
- asgiref-3.10.0.dist-info/licenses/LICENSE,sha256=uEZBXRtRTpwd_xSiLeuQbXlLxUbKYSn5UKGM0JHipmk,1552
13
- asgiref-3.10.0.dist-info/METADATA,sha256=TlcKOCn3FwSCGD62jZkbckPRh-RjAhkCLLDnfmDZTyA,9287
14
- asgiref-3.10.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
15
- asgiref-3.10.0.dist-info/top_level.txt,sha256=bokQjCzwwERhdBiPdvYEZa4cHxT4NCeAffQNUqJ8ssg,8
16
- asgiref-3.10.0.dist-info/RECORD,,
11
+ asgiref/wsgi.py,sha256=OSxanm5Qf-VfrOkAx62mYW0mOnh8pwaTz1099HbJzM0,7941
12
+ asgiref-3.11.1.dist-info/licenses/LICENSE,sha256=uEZBXRtRTpwd_xSiLeuQbXlLxUbKYSn5UKGM0JHipmk,1552
13
+ asgiref-3.11.1.dist-info/METADATA,sha256=aLePcJP6N7HpneCbacTmO_4Gc4b0PRSo2fWPwsWLeYQ,9287
14
+ asgiref-3.11.1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
15
+ asgiref-3.11.1.dist-info/top_level.txt,sha256=bokQjCzwwERhdBiPdvYEZa4cHxT4NCeAffQNUqJ8ssg,8
16
+ asgiref-3.11.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.9.0)
2
+ Generator: setuptools (80.10.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5