chore: 添加虚拟环境到仓库

- 添加 backend_service/venv 虚拟环境
- 包含所有Python依赖包
- 注意:虚拟环境约393MB,包含12655个文件
This commit is contained in:
2025-12-03 10:19:25 +08:00
parent a6c2027caa
commit c4f851d387
12655 changed files with 3009376 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
from ._api import EventSource, aconnect_sse, connect_sse
from ._exceptions import SSEError
from ._models import ServerSentEvent
__version__ = "0.4.3"
__all__ = [
"__version__",
"EventSource",
"connect_sse",
"aconnect_sse",
"ServerSentEvent",
"SSEError",
]

View File

@@ -0,0 +1,93 @@
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager, contextmanager
from typing import Any, AsyncIterator, Iterator, cast
import httpx
from ._decoders import SSEDecoder, SSELineDecoder
from ._exceptions import SSEError
from ._models import ServerSentEvent
class EventSource:
def __init__(self, response: httpx.Response) -> None:
self._response = response
def _check_content_type(self) -> None:
content_type = self._response.headers.get("content-type", "").partition(";")[0]
if "text/event-stream" not in content_type:
raise SSEError(
"Expected response header Content-Type to contain 'text/event-stream', "
f"got {content_type!r}"
)
@property
def response(self) -> httpx.Response:
return self._response
def iter_sse(self) -> Iterator[ServerSentEvent]:
self._check_content_type()
decoder = SSEDecoder()
for line in _iter_sse_lines(self._response):
line = line.rstrip("\n")
sse = decoder.decode(line)
if sse is not None:
yield sse
async def aiter_sse(self) -> AsyncGenerator[ServerSentEvent, None]:
self._check_content_type()
decoder = SSEDecoder()
lines = cast(AsyncGenerator[str, None], _aiter_sse_lines(self._response))
try:
async for line in lines:
line = line.rstrip("\n")
sse = decoder.decode(line)
if sse is not None:
yield sse
finally:
await lines.aclose()
@contextmanager
def connect_sse(
client: httpx.Client, method: str, url: str, **kwargs: Any
) -> Iterator[EventSource]:
headers = kwargs.pop("headers", {})
headers["Accept"] = "text/event-stream"
headers["Cache-Control"] = "no-store"
with client.stream(method, url, headers=headers, **kwargs) as response:
yield EventSource(response)
@asynccontextmanager
async def aconnect_sse(
client: httpx.AsyncClient,
method: str,
url: str,
**kwargs: Any,
) -> AsyncIterator[EventSource]:
headers = kwargs.pop("headers", {})
headers["Accept"] = "text/event-stream"
headers["Cache-Control"] = "no-store"
async with client.stream(method, url, headers=headers, **kwargs) as response:
yield EventSource(response)
async def _aiter_sse_lines(response: httpx.Response) -> AsyncIterator[str]:
decoder = SSELineDecoder()
async for text in response.aiter_text():
for line in decoder.decode(text):
yield line
for line in decoder.flush():
yield line
def _iter_sse_lines(response: httpx.Response) -> Iterator[str]:
decoder = SSELineDecoder()
for text in response.iter_text():
for line in decoder.decode(text):
yield line
for line in decoder.flush():
yield line

View File

@@ -0,0 +1,139 @@
from typing import List, Optional
from ._models import ServerSentEvent
def _splitlines_sse(text: str) -> List[str]:
"""Split text on \r\n, \r, or \n only."""
if not text:
return []
if "\r" not in text:
lines = text.split("\n")
else:
normalized = text.replace("\r\n", "\n").replace("\r", "\n")
lines = normalized.split("\n")
if text[-1] in "\r\n":
lines.pop()
return lines
class SSELineDecoder:
"""
Handles incrementally reading lines from text.
Mostly a copy of httpx._decoders.LineDecoder, but as per SSE spec, only \r\n, \r,
and \n are treated as newlines, which differs from the behavior of splitlines()
used by httpx._decoders.LineDecoder.
"""
def __init__(self) -> None:
self.buffer: list[str] = []
self.trailing_cr: bool = False
def decode(self, text: str) -> list[str]:
# We always push a trailing `\r` into the next decode iteration.
if self.trailing_cr:
text = "\r" + text
self.trailing_cr = False
if text.endswith("\r"):
self.trailing_cr = True
text = text[:-1]
if not text:
# NOTE: the edge case input of empty text doesn't occur in practice,
# because other httpx internals filter out this value
return [] # pragma: no cover
trailing_newline = text[-1] in "\n\r"
lines = _splitlines_sse(text)
if len(lines) == 1 and not trailing_newline:
# No new lines, buffer the input and continue.
self.buffer.append(lines[0])
return []
if self.buffer:
# Include any existing buffer in the first portion of the
# splitlines result.
lines = ["".join(self.buffer) + lines[0]] + lines[1:]
self.buffer = []
if not trailing_newline:
# If the last segment of splitlines is not newline terminated,
# then drop it from our output and start a new buffer.
self.buffer = [lines.pop()]
return lines
def flush(self) -> list[str]:
if not self.buffer and not self.trailing_cr:
return []
lines = ["".join(self.buffer)]
self.buffer = []
self.trailing_cr = False
return lines
class SSEDecoder:
def __init__(self) -> None:
self._event = ""
self._data: List[str] = []
self._last_event_id = ""
self._retry: Optional[int] = None
def decode(self, line: str) -> Optional[ServerSentEvent]:
# See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501
if not line:
if (
not self._event
and not self._data
and not self._last_event_id
and self._retry is None
):
return None
sse = ServerSentEvent(
event=self._event,
data="\n".join(self._data),
id=self._last_event_id,
retry=self._retry,
)
# NOTE: as per the SSE spec, do not reset last_event_id.
self._event = ""
self._data = []
self._retry = None
return sse
if line.startswith(":"):
return None
fieldname, _, value = line.partition(":")
if value.startswith(" "):
value = value[1:]
if fieldname == "event":
self._event = value
elif fieldname == "data":
self._data.append(value)
elif fieldname == "id":
if "\0" in value:
pass
else:
self._last_event_id = value
elif fieldname == "retry":
try:
self._retry = int(value)
except (TypeError, ValueError):
pass
else:
pass # Field is ignored.
return None

View File

@@ -0,0 +1,5 @@
import httpx
class SSEError(httpx.TransportError):
pass

View File

@@ -0,0 +1,54 @@
import json
from typing import Any, Optional
class ServerSentEvent:
def __init__(
self,
event: Optional[str] = None,
data: Optional[str] = None,
id: Optional[str] = None,
retry: Optional[int] = None,
) -> None:
if not event:
event = "message"
if data is None:
data = ""
if id is None:
id = ""
self._event = event
self._data = data
self._id = id
self._retry = retry
@property
def event(self) -> str:
return self._event
@property
def data(self) -> str:
return self._data
@property
def id(self) -> str:
return self._id
@property
def retry(self) -> Optional[int]:
return self._retry
def json(self) -> Any:
return json.loads(self.data)
def __repr__(self) -> str:
pieces = [f"event={self.event!r}"]
if self.data != "":
pieces.append(f"data={self.data!r}")
if self.id != "":
pieces.append(f"id={self.id!r}")
if self.retry is not None:
pieces.append(f"retry={self.retry!r}")
return f"ServerSentEvent({', '.join(pieces)})"