index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,646 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/datastructures.py | 551,552 | 508,595 | getlist | Headers | 552,559 | 552,559 | class Headers(typing.Mapping[str, str]):
"""
An immutable, case-insensitive multidict.
"""
def __init__(
self,
headers: typing.Optional[typing.Mapping[str, str]] = None,
raw: typing.Optional[typing.List[typing.Tuple[bytes, bytes]]] = None,
scope: typing.Optional[typing.M... | class Headers(typing.Mapping[str, str]):
"""
An immutable, case-insensitive multidict.
"""
def __init__(
self,
headers: typing.Optional[typing.Mapping[str, str]] = None,
raw: typing.Optional[typing.List[typing.Tuple[bytes, bytes]]] = None,
scope: typing.Optional[typing.M... | get_header_key = key.lower().encode("latin-1")
return [
item_value.decode("latin-1")
for item_key, item_value in self._list
if item_key == get_header_key
]
| get_header_key = key.lower().encode("latin-1")
return [
item_value.decode("latin-1")
for item_key, item_value in self._list
if item_key == get_header_key
]
| 16 | 942 | 73 | 1,015 | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... |
5,647 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/datastructures.py | 296,297 | 253,331 | keys | ImmutableMultiDict | 297,299 | 297,299 | class ImmutableMultiDict(typing.Mapping[_KeyType, _CovariantValueType]):
_dict: typing.Dict[_KeyType, _CovariantValueType]
def __init__(
self,
*args: typing.Union[
"ImmutableMultiDict[_KeyType, _CovariantValueType]",
typing.Mapping[_KeyType, _CovariantValueType],
... | class ImmutableMultiDict(typing.Mapping[_KeyType, _CovariantValueType]):
_dict: typing.Dict[_KeyType, _CovariantValueType]
def __init__(
self,
*args: typing.Union[
"ImmutableMultiDict[_KeyType, _CovariantValueType]",
typing.Mapping[_KeyType, _CovariantValueType],
... | return self._dict.keys()
| return self._dict.keys()
| 2 | 850 | 12 | 862 | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... |
5,648 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/datastructures.py | 364,365 | 331,391 | setlist | MultiDict | 365,372 | 365,372 | class MultiDict(ImmutableMultiDict[typing.Any, typing.Any]):
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
self.setlist(key, [value])
def __delitem__(self, key: typing.Any) -> None:
self._list = [(k, v) for k, v in self._list if k != key]
del self._dict[key]
de... | class MultiDict(ImmutableMultiDict[typing.Any, typing.Any]):
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
self.setlist(key, [value])
def __delitem__(self, key: typing.Any) -> None:
self._list = [(k, v) for k, v in self._list if k != key]
del self._dict[key]
de... | if not values:
self.pop(key, None)
else:
existing_items = [(k, v) for (k, v) in self._list if k != key]
self._list = existing_items + [(key, value) for value in values]
self._dict[key] = values[-1]
| if not values:
self.pop(key, None)
else:
existing_items = [(k, v) for (k, v) in self._list if k != key]
self._list = existing_items + [(key, value) for value in values]
self._dict[key] = values[-1]
| 32 | 643 | 90 | 733 | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... |
5,649 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/datastructures.py | 667,668 | 595,682 | append | MutableHeaders | 671,675 | 668,675 | class MutableHeaders(Headers):
def __setitem__(self, key: str, value: str) -> None:
"""
Set the header `key` to `value`, removing any duplicate entries.
Retains insertion order.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
f... | class MutableHeaders(Headers):
def __setitem__(self, key: str, value: str) -> None:
"""
Set the header `key` to `value`, removing any duplicate entries.
Retains insertion order.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
f... | append_key = key.lower().encode("latin-1")
append_value = value.encode("latin-1")
self._list.append((append_key, append_value))
| """
Append a header, preserving any duplicate entries.
"""
append_key = key.lower().encode("latin-1")
append_value = value.encode("latin-1")
self._list.append((append_key, append_value))
| 8 | 872 | 53 | 925 | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... |
5,650 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/datastructures.py | 147,148 | 21,175 | replace_query_params | URL | 148,151 | 148,151 | class URL:
def __init__(
self,
url: str = "",
scope: typing.Optional[Scope] = None,
**components: typing.Any,
) -> None:
if scope is not None:
assert not url, 'Cannot set both "url" and "scope".'
assert not components, 'Cannot set both "scope" and ... | class URL:
def __init__(
self,
url: str = "",
scope: typing.Optional[Scope] = None,
**components: typing.Any,
) -> None:
if scope is not None:
assert not url, 'Cannot set both "url" and "scope".'
assert not components, 'Cannot set both "scope" and ... | query = urlencode([(str(key), str(value)) for key, value in kwargs.items()])
return self.replace(query=query)
| query = urlencode([(str(key), str(value)) for key, value in kwargs.items()])
return self.replace(query=query)
| 11 | 1,415 | 43 | 1,458 | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... |
5,651 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/datastructures.py | 189,190 | 175,205 | make_absolute_url | URLPath | 190,205 | 190,205 | class URLPath(str):
"""
A URL path string that may also hold an associated protocol and/or host.
Used by the routing to return `url_path_for` matches.
"""
def __new__(cls, path: str, protocol: str = "", host: str = "") -> "URLPath":
assert protocol in ("http", "websocket", "")
retur... | class URLPath(str):
"""
A URL path string that may also hold an associated protocol and/or host.
Used by the routing to return `url_path_for` matches.
"""
def __new__(cls, path: str, protocol: str = "", host: str = "") -> "URLPath":
assert protocol in ("http", "websocket", "")
retur... | if isinstance(base_url, str):
base_url = URL(base_url)
if self.protocol:
scheme = {
"http": {True: "https", False: "http"},
"websocket": {True: "wss", False: "ws"},
}[self.protocol][base_url.is_secure]
else:
scheme =... | if isinstance(base_url, str):
base_url = URL(base_url)
if self.protocol:
scheme = {
"http": {True: "https", False: "http"},
"websocket": {True: "wss", False: "ws"},
}[self.protocol][base_url.is_secure]
else:
scheme =... | 40 | 186 | 171 | 357 | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... |
5,652 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/datastructures.py | 473,474 | 431,486 | seek | UploadFile | 474,479 | 474,479 | class UploadFile:
"""
An uploaded file included as part of the request data.
"""
def __init__(
self,
file: typing.BinaryIO,
*,
size: typing.Optional[int] = None,
filename: typing.Optional[str] = None,
headers: "typing.Optional[Headers]" = None,
) -> N... | class UploadFile:
"""
An uploaded file included as part of the request data.
"""
def __init__(
self,
file: typing.BinaryIO,
*,
size: typing.Optional[int] = None,
filename: typing.Optional[str] = None,
headers: "typing.Optional[Headers]" = None,
) -> N... | if self._in_memory:
self.file.seek(offset)
else:
await run_in_threadpool(self.file.seek, offset)
| if self._in_memory:
self.file.seek(offset)
else:
await run_in_threadpool(self.file.seek, offset)
| 7 | 443 | 47 | 490 | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... |
5,653 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/endpoints.py | 29,30 | 14,57 | dispatch | HTTPEndpoint | 30,47 | 30,47 | class HTTPEndpoint:
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
self.scope = scope
self.receive = receive
self.send = send
self._allowed_methods = [
method
for method in ("GET", "HEAD", "POST",... | class HTTPEndpoint:
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
self.scope = scope
self.receive = receive
self.send = send
self._allowed_methods = [
method
for method in ("GET", "HEAD", "POST",... | request = Request(self.scope, receive=self.receive)
handler_name = (
"get"
if request.method == "HEAD" and not hasattr(self, "head")
else request.method.lower()
)
handler: typing.Callable[[Request], typing.Any] = getattr(
self, handler_nam... | request = Request(self.scope, receive=self.receive)
handler_name = (
"get"
if request.method == "HEAD" and not hasattr(self, "head")
else request.method.lower()
)
handler: typing.Callable[[Request], typing.Any] = getattr(
self, handler_nam... | 47 | 331 | 186 | 517 | import json
import typing
from prefect._vendor.starlette import status
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.exceptions import HTTPException
from prefect._vendor.starlette.requests import Request... | import json
import typing
from prefect._vendor.starlette import status
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.exceptions import HTTPException
from prefect._vendor.starlette.requests import Request... |
5,654 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/endpoints.py | 92,93 | 57,131 | decode | WebSocketEndpoint | 93,122 | 93,122 | class WebSocketEndpoint:
encoding: typing.Optional[str] = None # May be "text", "bytes", or "json".
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "websocket"
self.scope = scope
self.receive = receive
self.send = send
def __... | class WebSocketEndpoint:
encoding: typing.Optional[str] = None # May be "text", "bytes", or "json".
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "websocket"
self.scope = scope
self.receive = receive
self.send = send
def __... | if self.encoding == "text":
if "text" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected text websocket messages, but got bytes")
return message["text"]
elif self.encoding == "bytes":
... | if self.encoding == "text":
if "text" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected text websocket messages, but got bytes")
return message["text"]
elif self.encoding == "bytes":
... | 86 | 537 | 332 | 869 | import json
import typing
from prefect._vendor.starlette import status
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.exceptions import HTTPException
from prefect._vendor.starlette.requests import Request... | import json
import typing
from prefect._vendor.starlette import status
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.exceptions import HTTPException
from prefect._vendor.starlette.requests import Request... |
5,656 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/formparsers.py | 77,78 | 46,118 | parse | FormParser | 78,118 | 78,118 | class FormParser:
def __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
... | class FormParser:
def __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
... | # Callbacks dictionary.
callbacks = {
"on_field_start": self.on_field_start,
"on_field_name": self.on_field_name,
"on_field_data": self.on_field_data,
"on_field_end": self.on_field_end,
"on_end": self.on_end,
}
# Create the par... | # Callbacks dictionary.
callbacks = {
"on_field_start": self.on_field_start,
"on_field_name": self.on_field_name,
"on_field_data": self.on_field_data,
"on_field_end": self.on_field_end,
"on_end": self.on_end,
}
# Create the par... | 102 | 362 | 438 | 800 | import typing
from dataclasses import dataclass, field
from enum import Enum
from tempfile import SpooledTemporaryFile
from urllib.parse import unquote_plus
from prefect._vendor.starlette.datastructures import FormData, Headers, UploadFile
try:
import multipart
from multipart.multipart import parse_options_he... | import typing
from dataclasses import dataclass, field
from enum import Enum
from tempfile import SpooledTemporaryFile
from urllib.parse import unquote_plus
from prefect._vendor.starlette.datastructures import FormData, Headers, UploadFile
try:
import multipart
from multipart.multipart import parse_options_he... |
5,657 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/formparsers.py | 226,227 | 118,277 | parse | MultiPartParser | 227,277 | 227,277 | class MultiPartParser:
max_file_size = 1024 * 1024
def __init__(
self,
headers: Headers,
stream: typing.AsyncGenerator[bytes, None],
*,
max_files: typing.Union[int, float] = 1000,
max_fields: typing.Union[int, float] = 1000,
) -> None:
assert (
... | class MultiPartParser:
max_file_size = 1024 * 1024
def __init__(
self,
headers: Headers,
stream: typing.AsyncGenerator[bytes, None],
*,
max_files: typing.Union[int, float] = 1000,
max_fields: typing.Union[int, float] = 1000,
) -> None:
assert (
... | # Parse the Content-Type header to get the multipart boundary.
_, params = parse_options_header(self.headers["Content-Type"])
charset = params.get(b"charset", "utf-8")
if isinstance(charset, bytes):
charset = charset.decode("latin-1")
self._charset = charset
t... | # Parse the Content-Type header to get the multipart boundary.
_, params = parse_options_header(self.headers["Content-Type"])
charset = params.get(b"charset", "utf-8")
if isinstance(charset, bytes):
charset = charset.decode("latin-1")
self._charset = charset
t... | 186 | 1,309 | 628 | 1,937 | import typing
from dataclasses import dataclass, field
from enum import Enum
from tempfile import SpooledTemporaryFile
from urllib.parse import unquote_plus
from prefect._vendor.starlette.datastructures import FormData, Headers, UploadFile
try:
import multipart
from multipart.multipart import parse_options_he... | import typing
from dataclasses import dataclass, field
from enum import Enum
from tempfile import SpooledTemporaryFile
from urllib.parse import unquote_plus
from prefect._vendor.starlette.datastructures import FormData, Headers, UploadFile
try:
import multipart
from multipart.multipart import parse_options_he... |
5,658 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/authentication.py | 50,52 | 14,53 | default_on_error | AuthenticationMiddleware | 52,53 | 52,53 | class AuthenticationMiddleware:
def __init__(
self,
app: ASGIApp,
backend: AuthenticationBackend,
on_error: typing.Optional[
typing.Callable[[HTTPConnection, AuthenticationError], Response]
] = None,
) -> None:
self.app = app
self.backend = bac... | class AuthenticationMiddleware:
def __init__(
self,
app: ASGIApp,
backend: AuthenticationBackend,
on_error: typing.Optional[
typing.Callable[[HTTPConnection, AuthenticationError], Response]
] = None,
) -> None:
self.app = app
self.backend = bac... | return PlainTextResponse(str(exc), status_code=400)
| return PlainTextResponse(str(exc), status_code=400)
| 3 | 399 | 21 | 420 | import typing
from prefect._vendor.starlette.authentication import (
AuthCredentials,
AuthenticationBackend,
AuthenticationError,
UnauthenticatedUser,
)
from prefect._vendor.starlette.requests import HTTPConnection
from prefect._vendor.starlette.responses import PlainTextResponse, Response
from prefect... | import typing
from prefect._vendor.starlette.authentication import (
AuthCredentials,
AuthenticationBackend,
AuthenticationError,
UnauthenticatedUser,
)
from prefect._vendor.starlette.requests import HTTPConnection
from prefect._vendor.starlette.responses import PlainTextResponse, Response
from prefect... |
5,659 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/base.py | 113,114 | 97,204 | call_next | BaseHTTPMiddleware | 114,192 | 114,192 | class BaseHTTPMiddleware:
def __init__(
self, app: ASGIApp, dispatch: typing.Optional[DispatchFunction] = None
) -> None:
self.app = app
self.dispatch_func = self.dispatch if dispatch is None else dispatch
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:... | class BaseHTTPMiddleware:
def __init__(
self, app: ASGIApp, dispatch: typing.Optional[DispatchFunction] = None
) -> None:
self.app = app
self.dispatch_func = self.dispatch if dispatch is None else dispatch
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:... | app_exc: typing.Optional[Exception] = None
send_stream: ObjectSendStream[typing.MutableMapping[str, typing.Any]]
recv_stream: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]]
send_stream, recv_stream = anyio.create_memory_object_stream()
async def ... | app_exc: typing.Optional[Exception] = None
send_stream: ObjectSendStream[typing.MutableMapping[str, typing.Any]]
recv_stream: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]]
send_stream, recv_stream = anyio.create_memory_object_stream()
async def ... | 199 | 302 | 823 | 1,125 | import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette._utils import collapse_excgroups
from prefect._vendor.starlette.background import BackgroundTask
from prefect._vendor.starlette.requests import ClientDisconnect, Request
from prefect._vendor.starlette.... | import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette._utils import collapse_excgroups
from prefect._vendor.starlette.background import BackgroundTask
from prefect._vendor.starlette.requests import ClientDisconnect, Request
from prefect._vendor.starlette.... |
5,660 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/base.py | 36,37 | 22,97 | wrapped_receive | _CachedRequest | 37,97 | 37,97 | class _CachedRequest(Request):
"""
If the user calls Request.body() from their dispatch function
we cache the entire request body in memory and pass that to downstream middlewares,
but if they call Request.stream() then all we do is send an
empty body so that downstream things don't hang forever.
... | class _CachedRequest(Request):
"""
If the user calls Request.body() from their dispatch function
we cache the entire request body in memory and pass that to downstream middlewares,
but if they call Request.stream() then all we do is send an
empty body so that downstream things don't hang forever.
... | # wrapped_rcv state 1: disconnected
if self._wrapped_rcv_disconnected:
# we've already sent a disconnect to the downstream app
# we don't need to wait to get another one
# (although most ASGI servers will just keep sending it)
return {"type": "http.disconn... | # wrapped_rcv state 1: disconnected
if self._wrapped_rcv_disconnected:
# we've already sent a disconnect to the downstream app
# we don't need to wait to get another one
# (although most ASGI servers will just keep sending it)
return {"type": "http.disconn... | 278 | 180 | 700 | 880 | import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette._utils import collapse_excgroups
from prefect._vendor.starlette.background import BackgroundTask
from prefect._vendor.starlette.requests import ClientDisconnect, Request
from prefect._vendor.starlette.... | import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette._utils import collapse_excgroups
from prefect._vendor.starlette.background import BackgroundTask
from prefect._vendor.starlette.requests import ClientDisconnect, Request
from prefect._vendor.starlette.... |
5,661 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/base.py | 217,218 | 204,221 | stream_response | _StreamingResponse | 218,221 | 218,221 | class _StreamingResponse(StreamingResponse):
def __init__(
self,
content: ContentStream,
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optional[BackgroundTask] = None,
... | class _StreamingResponse(StreamingResponse):
def __init__(
self,
content: ContentStream,
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optional[BackgroundTask] = None,
... | if self._info:
await send({"type": "http.response.debug", "info": self._info})
return await super().stream_response(send)
| if self._info:
await send({"type": "http.response.debug", "info": self._info})
return await super().stream_response(send)
| 10 | 175 | 44 | 219 | import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette._utils import collapse_excgroups
from prefect._vendor.starlette.background import BackgroundTask
from prefect._vendor.starlette.requests import ClientDisconnect, Request
from prefect._vendor.starlette.... | import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette._utils import collapse_excgroups
from prefect._vendor.starlette.background import BackgroundTask
from prefect._vendor.starlette.requests import ClientDisconnect, Request
from prefect._vendor.starlette.... |
5,662 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/cors.py | 93,94 | 13,177 | is_allowed_origin | CORSMiddleware | 94,104 | 94,104 | class CORSMiddleware:
def __init__(
self,
app: ASGIApp,
allow_origins: typing.Sequence[str] = (),
allow_methods: typing.Sequence[str] = ("GET",),
allow_headers: typing.Sequence[str] = (),
allow_credentials: bool = False,
allow_origin_regex: typing.Optional[str... | class CORSMiddleware:
def __init__(
self,
app: ASGIApp,
allow_origins: typing.Sequence[str] = (),
allow_methods: typing.Sequence[str] = ("GET",),
allow_headers: typing.Sequence[str] = (),
allow_credentials: bool = False,
allow_origin_regex: typing.Optional[str... | if self.allow_all_origins:
return True
if self.allow_origin_regex is not None and self.allow_origin_regex.fullmatch(
origin
):
return True
return origin in self.allow_origins
| if self.allow_all_origins:
return True
if self.allow_origin_regex is not None and self.allow_origin_regex.fullmatch(
origin
):
return True
return origin in self.allow_origins
| 19 | 1,777 | 76 | 1,853 | import functools
import re
import typing
from prefect._vendor.starlette.datastructures import Headers, MutableHeaders
from prefect._vendor.starlette.responses import PlainTextResponse, Response
from prefect._vendor.starlette.types import ASGIApp, Message, Receive, Scope, Send
ALL_METHODS = ("DELETE", "GET", "HEAD", "... | import functools
import re
import typing
from prefect._vendor.starlette.datastructures import Headers, MutableHeaders
from prefect._vendor.starlette.responses import PlainTextResponse, Response
from prefect._vendor.starlette.types import ASGIApp, Message, Receive, Scope, Send
ALL_METHODS = ("DELETE", "GET", "HEAD", "... |
5,663 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/errors.py | 255,256 | 129,266 | debug_response | ServerErrorMiddleware | 256,264 | 256,264 | class ServerErrorMiddleware:
"""
Handles returning 500 responses when a server error occurs.
If 'debug' is set, then traceback responses will be returned,
otherwise the designated 'handler' will be called.
This middleware class should generally be used to wrap *everything*
else up, so that unh... | class ServerErrorMiddleware:
"""
Handles returning 500 responses when a server error occurs.
If 'debug' is set, then traceback responses will be returned,
otherwise the designated 'handler' will be called.
This middleware class should generally be used to wrap *everything*
else up, so that unh... | accept = request.headers.get("accept", "")
if "text/html" in accept:
content = self.generate_html(exc)
return HTMLResponse(content, status_code=500)
content = self.generate_plain_text(exc)
return PlainTextResponse(content, status_code=500)
| accept = request.headers.get("accept", "")
if "text/html" in accept:
content = self.generate_html(exc)
return HTMLResponse(content, status_code=500)
content = self.generate_plain_text(exc)
return PlainTextResponse(content, status_code=500)
| 20 | 1,323 | 95 | 1,418 | import html
import inspect
import traceback
import typing
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.responses import (
HTMLResponse,
Pla... | import html
import inspect
import traceback
import typing
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.responses import (
HTMLResponse,
Pla... |
5,664 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/exceptions.py | 64,65 | 15,75 | http_exception | ExceptionMiddleware | 65,72 | 65,72 | class ExceptionMiddleware:
def __init__(
self,
app: ASGIApp,
handlers: typing.Optional[
typing.Mapping[typing.Any, typing.Callable[[Request, Exception], Response]]
] = None,
debug: bool = False,
) -> None:
self.app = app
self.debug = debug # T... | class ExceptionMiddleware:
def __init__(
self,
app: ASGIApp,
handlers: typing.Optional[
typing.Mapping[typing.Any, typing.Callable[[Request, Exception], Response]]
] = None,
debug: bool = False,
) -> None:
self.app = app
self.debug = debug # T... | assert isinstance(exc, HTTPException)
if exc.status_code in {204, 304}:
return Response(status_code=exc.status_code, headers=exc.headers)
return PlainTextResponse(
exc.detail, status_code=exc.status_code, headers=exc.headers
)
| assert isinstance(exc, HTTPException)
if exc.status_code in {204, 304}:
return Response(status_code=exc.status_code, headers=exc.headers)
return PlainTextResponse(
exc.detail, status_code=exc.status_code, headers=exc.headers
)
| 17 | 621 | 91 | 712 | import typing
from prefect._vendor.starlette._exception_handler import (
ExceptionHandlers,
StatusHandlers,
wrap_app_handling_exceptions,
)
from prefect._vendor.starlette.exceptions import HTTPException, WebSocketException
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlett... | import typing
from prefect._vendor.starlette._exception_handler import (
ExceptionHandlers,
StatusHandlers,
wrap_app_handling_exceptions,
)
from prefect._vendor.starlette.exceptions import HTTPException, WebSocketException
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlett... |
5,665 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/gzip.py | 112,113 | 1,114 | unattached_send | 113,114 | 113,114 | import gzip
import io
import typing
from prefect._vendor.starlette.datastructures import Headers, MutableHeaders
from prefect._vendor.starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
)... | import gzip
import io
import typing
from prefect._vendor.starlette.datastructures import Headers, MutableHeaders
from prefect._vendor.starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
)... | raise RuntimeError("send awaitable not set") # pragma: no cover
| raise RuntimeError("send awaitable not set") # pragma: no cover
| 9 | 1,256 | 20 | 1,276 | import gzip
import io
import typing
from prefect._vendor.starlette.datastructures import Headers, MutableHeaders
from prefect._vendor.starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
)... | import gzip
import io
import typing
from prefect._vendor.starlette.datastructures import Headers, MutableHeaders
from prefect._vendor.starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
)... | |
5,666 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/gzip.py | 46,47 | 29,112 | send_with_gzip | GZipResponder | 47,112 | 47,112 | class GZipResponder:
def __init__(self, app: ASGIApp, minimum_size: int, compresslevel: int = 9) -> None:
self.app = app
self.minimum_size = minimum_size
self.send: Send = unattached_send
self.initial_message: Message = {}
self.started = False
self.content_encoding_se... | class GZipResponder:
def __init__(self, app: ASGIApp, minimum_size: int, compresslevel: int = 9) -> None:
self.app = app
self.minimum_size = minimum_size
self.send: Send = unattached_send
self.initial_message: Message = {}
self.started = False
self.content_encoding_se... | message_type = message["type"]
if message_type == "http.response.start":
# Don't send the initial message until we've determined how to
# modify the outgoing headers correctly.
self.initial_message = message
headers = Headers(raw=self.initial_message["head... | message_type = message["type"]
if message_type == "http.response.start":
# Don't send the initial message until we've determined how to
# modify the outgoing headers correctly.
self.initial_message = message
headers = Headers(raw=self.initial_message["head... | 175 | 246 | 784 | 1,030 | import gzip
import io
import typing
from prefect._vendor.starlette.datastructures import Headers, MutableHeaders
from prefect._vendor.starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
)... | import gzip
import io
import typing
from prefect._vendor.starlette.datastructures import Headers, MutableHeaders
from prefect._vendor.starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
)... |
5,667 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/sessions.py | 54,55 | 12,83 | send_wrapper | SessionMiddleware | 55,82 | 55,82 | class SessionMiddleware:
def __init__(
self,
app: ASGIApp,
secret_key: typing.Union[str, Secret],
session_cookie: str = "session",
max_age: typing.Optional[int] = 14 * 24 * 60 * 60, # 14 days, in seconds
path: str = "/",
same_site: typing.Literal["lax", "stri... | class SessionMiddleware:
def __init__(
self,
app: ASGIApp,
secret_key: typing.Union[str, Secret],
session_cookie: str = "session",
max_age: typing.Optional[int] = 14 * 24 * 60 * 60, # 14 days, in seconds
path: str = "/",
same_site: typing.Literal["lax", "stri... | if message["type"] == "http.response.start":
if scope["session"]:
# We have session data to persist.
data = b64encode(json.dumps(scope["session"]).encode("utf-8"))
data = self.signer.sign(data)
headers = MutableH... | if message["type"] == "http.response.start":
if scope["session"]:
# We have session data to persist.
data = b64encode(json.dumps(scope["session"]).encode("utf-8"))
data = self.signer.sign(data)
headers = MutableH... | 79 | 541 | 422 | 963 | import json
import typing
from base64 import b64decode, b64encode
import itsdangerous
from itsdangerous.exc import BadSignature
from prefect._vendor.starlette.datastructures import MutableHeaders, Secret
from prefect._vendor.starlette.requests import HTTPConnection
from prefect._vendor.starlette.types import ASGIApp, ... | import json
import typing
from base64 import b64decode, b64encode
import itsdangerous
from itsdangerous.exc import BadSignature
from prefect._vendor.starlette.datastructures import MutableHeaders, Secret
from prefect._vendor.starlette.requests import HTTPConnection
from prefect._vendor.starlette.types import ASGIApp, ... |
5,668 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/wsgi.py | 18,19 | 1,148 | build_environ | 22,64 | 19,64 | import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future release. "
"Please re... | import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future release. "
"Please re... | environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"),
"PATH_INFO": scope["path"].encode("utf8").decode("latin1"),
"QUERY_STRING": scope["query_string"].decode("ascii"),
"SERVER_PROTOCOL": f"HTTP/{scope['http_... | """
Builds a scope and request body into a WSGI environ object.
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"),
"PATH_INFO": scope["path"].encode("utf8").decode("latin1"),
"QUERY_STRING": scope[... | 140 | 1,120 | 561 | 1,681 | import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future release. "
"Please re... | import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future release. "
"Please re... | |
5,669 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/middleware/wsgi.py | 110,116 | 74,148 | start_response | WSGIResponder | 116,134 | 116,134 | class WSGIResponder:
stream_send: ObjectSendStream[typing.MutableMapping[str, typing.Any]]
stream_receive: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]]
def __init__(self, app: typing.Callable[..., typing.Any], scope: Scope) -> None:
self.app = app
self.scope = scope
s... | class WSGIResponder:
stream_send: ObjectSendStream[typing.MutableMapping[str, typing.Any]]
stream_receive: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]]
def __init__(self, app: typing.Callable[..., typing.Any], scope: Scope) -> None:
self.app = app
self.scope = scope
s... | self.exc_info = exc_info
if not self.response_started:
self.response_started = True
status_code_string, _ = status.split(" ", 1)
status_code = int(status_code_string)
headers = [
(name.strip().encode("ascii").lower(), value.strip().encode("... | self.exc_info = exc_info
if not self.response_started:
self.response_started = True
status_code_string, _ = status.split(" ", 1)
status_code = int(status_code_string)
headers = [
(name.strip().encode("ascii").lower(), value.strip().encode("... | 40 | 662 | 184 | 846 | import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future release. "
"Please re... | import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from prefect._vendor.starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future release. "
"Please re... |
5,670 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/responses.py | 303,304 | 264,348 | set_stat_headers | FileResponse | 304,313 | 304,313 | class FileResponse(Response):
chunk_size = 64 * 1024
def __init__(
self,
path: typing.Union[str, "os.PathLike[str]"],
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Op... | class FileResponse(Response):
chunk_size = 64 * 1024
def __init__(
self,
path: typing.Union[str, "os.PathLike[str]"],
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Op... | content_length = str(stat_result.st_size)
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
etag = md5_hexdigest(etag_base.encode(), usedforsecurity=False)
self.headers.setdefault("content-length"... | content_length = str(stat_result.st_size)
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
etag = md5_hexdigest(etag_base.encode(), usedforsecurity=False)
self.headers.setdefault("content-length"... | 24 | 875 | 160 | 1,035 | import http.cookies
import json
import os
import stat
import typing
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
from prefect._vendor.starlette._compat import md5_hexdigest
fr... | import http.cookies
import json
import os
import stat
import typing
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
from prefect._vendor.starlette._compat import md5_hexdigest
fr... |
5,671 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/responses.py | 179,180 | 166,189 | render | JSONResponse | 180,189 | 180,189 | class JSONResponse(Response):
media_type = "application/json"
def __init__(
self,
content: typing.Any,
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optional[Backgrou... | class JSONResponse(Response):
media_type = "application/json"
def __init__(
self,
content: typing.Any,
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optional[Backgrou... | return json.dumps(
content,
ensure_ascii=False,
allow_nan=False,
indent=None,
separators=(",", ":"),
).encode("utf-8")
| return json.dumps(
content,
ensure_ascii=False,
allow_nan=False,
indent=None,
separators=(",", ":"),
).encode("utf-8")
| 9 | 154 | 68 | 222 | import http.cookies
import json
import os
import stat
import typing
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
from prefect._vendor.starlette._compat import md5_hexdigest
fr... | import http.cookies
import json
import os
import stat
import typing
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
from prefect._vendor.starlette._compat import md5_hexdigest
fr... |
5,672 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/responses.py | 85,97 | 20,158 | set_cookie | Response | 97,124 | 97,124 | class Response:
media_type = None
charset = "utf-8"
def __init__(
self,
content: typing.Any = None,
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optional[Backgro... | class Response:
media_type = None
charset = "utf-8"
def __init__(
self,
content: typing.Any = None,
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optional[Backgro... | cookie: "http.cookies.BaseCookie[str]" = http.cookies.SimpleCookie()
cookie[key] = value
if max_age is not None:
cookie[key]["max-age"] = max_age
if expires is not None:
if isinstance(expires, datetime):
cookie[key]["expires"] = format_datetime(exp... | cookie: "http.cookies.BaseCookie[str]" = http.cookies.SimpleCookie()
cookie[key] = value
if max_age is not None:
cookie[key]["max-age"] = max_age
if expires is not None:
if isinstance(expires, datetime):
cookie[key]["expires"] = format_datetime(exp... | 86 | 1,106 | 340 | 1,446 | import http.cookies
import json
import os
import stat
import typing
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
from prefect._vendor.starlette._compat import md5_hexdigest
fr... | import http.cookies
import json
import os
import stat
import typing
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
from prefect._vendor.starlette._compat import md5_hexdigest
fr... |
5,673 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/responses.py | 235,236 | 209,264 | stream_response | StreamingResponse | 236,250 | 236,250 | class StreamingResponse(Response):
body_iterator: AsyncContentStream
def __init__(
self,
content: ContentStream,
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optiona... | class StreamingResponse(Response):
body_iterator: AsyncContentStream
def __init__(
self,
content: ContentStream,
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optiona... | await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
async for chunk in self.body_iterator:
if not isinstance(chunk, bytes):
chunk = chunk.enco... | await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
async for chunk in self.body_iterator:
if not isinstance(chunk, bytes):
chunk = chunk.enco... | 37 | 434 | 156 | 590 | import http.cookies
import json
import os
import stat
import typing
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
from prefect._vendor.starlette._compat import md5_hexdigest
fr... | import http.cookies
import json
import os
import stat
import typing
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
from prefect._vendor.starlette._compat import md5_hexdigest
fr... |
5,674 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/schemas.py | 100,103 | 32,132 | parse_docstring | BaseSchemaGenerator | 106,126 | 103,126 | class BaseSchemaGenerator:
def get_schema(
self, routes: typing.List[BaseRoute]
) -> typing.Dict[str, typing.Any]:
raise NotImplementedError() # pragma: no cover
def get_endpoints(
self, routes: typing.List[BaseRoute]
) -> typing.List[EndpointInfo]:
"""
Given th... | class BaseSchemaGenerator:
def get_schema(
self, routes: typing.List[BaseRoute]
) -> typing.Dict[str, typing.Any]:
raise NotImplementedError() # pragma: no cover
def get_endpoints(
self, routes: typing.List[BaseRoute]
) -> typing.List[EndpointInfo]:
"""
Given th... | docstring = func_or_method.__doc__
if not docstring:
return {}
assert yaml is not None, "`pyyaml` must be installed to use parse_docstring."
# We support having regular docstrings before the schema
# definition. Here we return just the schema part from
# the... | """
Given a function, parse the docstring as YAML and return a dictionary of info.
"""
docstring = func_or_method.__doc__
if not docstring:
return {}
assert yaml is not None, "`pyyaml` must be installed to use parse_docstring."
# We support having re... | 75 | 802 | 187 | 989 | import inspect
import re
import typing
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.responses import Response
from prefect._vendor.starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type... | import inspect
import re
import typing
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.responses import Response
from prefect._vendor.starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type... |
5,675 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/schemas.py | 18,19 | 15,26 | render | OpenAPIResponse | 19,26 | 19,26 | class OpenAPIResponse(Response):
media_type = "application/vnd.oai.openapi"
def render(self, content: typing.Any) -> bytes:
FILL_FUNC_BODY | class OpenAPIResponse(Response):
media_type = "application/vnd.oai.openapi"
def render(self, content: typing.Any) -> bytes:
FILL_FUNC_BODY | assert yaml is not None, "`pyyaml` must be installed to use OpenAPIResponse."
assert isinstance(
content, dict
), "The schema passed to OpenAPIResponse should be a dictionary."
return yaml.dump(content, default_flow_style=False).encode("utf-8")
| assert yaml is not None, "`pyyaml` must be installed to use OpenAPIResponse."
assert isinstance(
content, dict
), "The schema passed to OpenAPIResponse should be a dictionary."
return yaml.dump(content, default_flow_style=False).encode("utf-8")
| 29 | 54 | 84 | 138 | import inspect
import re
import typing
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.responses import Response
from prefect._vendor.starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type... | import inspect
import re
import typing
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.responses import Response
from prefect._vendor.starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type... |
5,676 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/schemas.py | 136,139 | 132,155 | get_schema | SchemaGenerator | 139,155 | 139,155 | class SchemaGenerator(BaseSchemaGenerator):
def __init__(self, base_schema: typing.Dict[str, typing.Any]) -> None:
self.base_schema = base_schema
def get_schema(
self, routes: typing.List[BaseRoute]
) -> typing.Dict[str, typing.Any]:
FILL_FUNC_BODY | class SchemaGenerator(BaseSchemaGenerator):
def __init__(self, base_schema: typing.Dict[str, typing.Any]) -> None:
self.base_schema = base_schema
def get_schema(
self, routes: typing.List[BaseRoute]
) -> typing.Dict[str, typing.Any]:
FILL_FUNC_BODY | schema = dict(self.base_schema)
schema.setdefault("paths", {})
endpoints_info = self.get_endpoints(routes)
for endpoint in endpoints_info:
parsed = self.parse_docstring(endpoint.func)
if not parsed:
continue
if endpoint.path not in s... | schema = dict(self.base_schema)
schema.setdefault("paths", {})
endpoints_info = self.get_endpoints(routes)
for endpoint in endpoints_info:
parsed = self.parse_docstring(endpoint.func)
if not parsed:
continue
if endpoint.path not in s... | 32 | 95 | 148 | 243 | import inspect
import re
import typing
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.responses import Response
from prefect._vendor.starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type... | import inspect
import re
import typing
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.responses import Response
from prefect._vendor.starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type... |
5,678 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/websockets.py | 125,126 | 21,185 | receive_json | WebSocket | 126,141 | 126,141 | class WebSocket(HTTPConnection):
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
super().__init__(scope)
assert scope["type"] == "websocket"
self._receive = receive
self._send = send
self.client_state = WebSocketState.CONNECTING
self.applicatio... | class WebSocket(HTTPConnection):
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
super().__init__(scope)
assert scope["type"] == "websocket"
self._receive = receive
self._send = send
self.client_state = WebSocketState.CONNECTING
self.applicatio... | if mode not in {"text", "binary"}:
raise RuntimeError('The "mode" argument should be "text" or "binary".')
if self.application_state != WebSocketState.CONNECTED:
raise RuntimeError(
'WebSocket is not connected. Need to call "accept" first.'
)
m... | if mode not in {"text", "binary"}:
raise RuntimeError('The "mode" argument should be "text" or "binary".')
if self.application_state != WebSocketState.CONNECTED:
raise RuntimeError(
'WebSocket is not connected. Need to call "accept" first.'
)
m... | 49 | 1,677 | 163 | 1,840 | import enum
import json
import typing
from prefect._vendor.starlette.requests import HTTPConnection
from prefect._vendor.starlette.types import Message, Receive, Scope, Send
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
DISCONNECTED = 2
class WebSocketDisconnect(Exception):
def __in... | import enum
import json
import typing
from prefect._vendor.starlette.requests import HTTPConnection
from prefect._vendor.starlette.types import Message, Receive, Scope, Send
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
DISCONNECTED = 2
class WebSocketDisconnect(Exception):
def __in... |
5,679 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/automations.py | 46,48 | 43,163 | create | Automation | 67,72 | 48,72 | class Automation(AutomationCore):
id: Optional[UUID] = Field(default=None, description="The ID of this automation")
@sync_compatible
async def create(self: Self) -> Self:
FILL_FUNC_BODY @sync_compatible
async def update(self: Self):
"""
Updates an existing automation.
auto = ... | class Automation(AutomationCore):
id: Optional[UUID] = Field(default=None, description="The ID of this automation")
@sync_compatible
async def create(self: Self) -> Self:
"""
Create a new automation.
auto_to_create = Automation(
name="woodchonk",
trigger=Eve... | client, _ = get_or_create_client()
automation = AutomationCore(**self.dict(exclude={"id"}))
self.id = await client.create_automation(automation=automation)
return self
| """
Create a new automation.
auto_to_create = Automation(
name="woodchonk",
trigger=EventTrigger(
expect={"animal.walked"},
match={
"genus": "Marmota",
"species": "monax",
},
... | 13 | 1,058 | 64 | 1,122 | from typing import Optional
from uuid import UUID
from pydantic import Field
from typing_extensions import Self
from prefect.client.utilities import get_or_create_client
from prefect.events.schemas.automations import (
AutomationCore,
CompositeTrigger,
CompoundTrigger,
EventTrigger,
MetricTrigger,... | from typing import Optional
from uuid import UUID
from pydantic import Field
from typing_extensions import Self
from prefect.client.utilities import get_or_create_client
from prefect.events.schemas.automations import (
AutomationCore,
CompositeTrigger,
CompoundTrigger,
EventTrigger,
MetricTrigger,... |
5,680 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/blocks/abstract.py | 36,38 | 27,63 | logger | CredentialsBlock | 47,52 | 38,52 | class CredentialsBlock(Block, ABC):
"""
Stores credentials for an external system and exposes a client for interacting
with that system. Can also hold config that is tightly coupled to credentials
(domain, endpoint, account ID, etc.) Will often be composed with other blocks.
Parent block should rely... | class CredentialsBlock(Block, ABC):
"""
Stores credentials for an external system and exposes a client for interacting
with that system. Can also hold config that is tightly coupled to credentials
(domain, endpoint, account ID, etc.) Will often be composed with other blocks.
Parent block should rely... | try:
return get_run_logger()
except MissingContextError:
return get_logger(self.__class__.__name__)
| """
Returns a logger based on whether the CredentialsBlock
is called from within a flow or task run context.
If a run context is present, the logger property returns a run logger.
Else, it returns a default logger labeled with the class's name.
Returns:
The r... | 7 | 285 | 41 | 326 | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... |
5,681 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/blocks/abstract.py | 284,288 | 189,333 | execute_many | DatabaseBlock | 297,300 | 288,300 | class DatabaseBlock(Block, ABC):
"""
An abstract block type that represents a database and
provides an interface for interacting with it.
Blocks that implement this interface have the option to accept
credentials directly via attributes or via a nested `CredentialsBlock`.
Use of a nested crede... | class DatabaseBlock(Block, ABC):
"""
An abstract block type that represents a database and
provides an interface for interacting with it.
Blocks that implement this interface have the option to accept
credentials directly via attributes or via a nested `CredentialsBlock`.
Use of a nested crede... |
# context management methods are not abstract methods because
# they are not supported by all database drivers
| """
Executes multiple operations on the database. This method is intended to be used
for operations that do not return data, such as INSERT, UPDATE, or DELETE.
Args:
operation: The SQL query or other operation to be executed.
seq_of_parameters: The sequence of pa... | 18 | 1,203 | 26 | 1,229 | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... |
5,682 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/blocks/abstract.py | 176,178 | 154,189 | trigger | JobBlock | 182,189 | 178,189 | class JobBlock(Block, ABC):
"""
Block that represents an entity in an external service
that can trigger a long running execution.
"""
@property
def logger(self) -> Logger:
"""
Returns a logger based on whether the JobBlock
is called from within a flow or task run context... | class JobBlock(Block, ABC):
"""
Block that represents an entity in an external service
that can trigger a long running execution.
"""
@property
def logger(self) -> Logger:
"""
Returns a logger based on whether the JobBlock
is called from within a flow or task run context... |
# TODO: This interface is heavily influenced by
# [PEP 249](https://peps.python.org/pep-0249/)
# Primarily intended for use with relational databases.
# A separate interface may be necessary for
# non relational databases.
| """
Triggers a job run in an external service and returns a JobRun object
to track the execution of the run.
"""
# TODO: This interface is heavily influenced by
# [PEP 249](https://peps.python.org/pep-0249/)
# Primarily intended for use with relational databases.
# A separate interface... | 31 | 238 | 74 | 312 | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... |
5,683 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/blocks/abstract.py | 125,127 | 119,154 | logger | JobRun | 136,141 | 127,141 | class JobRun(ABC, Generic[T]): # not a block
"""
Represents a job run in an external system. Allows waiting
for the job run's completion and fetching its results.
"""
@property
def logger(self) -> Logger:
FILL_FUNC_BODY @abstractmethod
async def wait_for_completion(self) -> Logger:
... | class JobRun(ABC, Generic[T]): # not a block
"""
Represents a job run in an external system. Allows waiting
for the job run's completion and fetching its results.
"""
@property
def logger(self) -> Logger:
"""
Returns a logger based on whether the JobRun
is called from w... | try:
return get_run_logger()
except MissingContextError:
return get_logger(self.__class__.__name__)
| """
Returns a logger based on whether the JobRun
is called from within a flow or task run context.
If a run context is present, the logger property returns a run logger.
Else, it returns a default logger labeled with the class's name.
Returns:
The run logger ... | 7 | 251 | 41 | 292 | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... |
5,684 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/blocks/abstract.py | 78,80 | 70,119 | logger | NotificationBlock | 89,94 | 80,94 | class NotificationBlock(Block, ABC):
"""
Block that represents a resource in an external system that is able to send notifications.
"""
_block_schema_capabilities = ["notify"]
_events_excluded_methods = Block._events_excluded_methods + ["notify"]
@property
def logger(self) -> Logger:
FILL_... | class NotificationBlock(Block, ABC):
"""
Block that represents a resource in an external system that is able to send notifications.
"""
_block_schema_capabilities = ["notify"]
_events_excluded_methods = Block._events_excluded_methods + ["notify"]
@property
def logger(self) -> Logger:
... | try:
return get_run_logger()
except MissingContextError:
return get_logger(self.__class__.__name__)
| """
Returns a logger based on whether the NotificationBlock
is called from within a flow or task run context.
If a run context is present, the logger property returns a run logger.
Else, it returns a default logger labeled with the class's name.
Returns:
The ... | 7 | 365 | 41 | 406 | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... |
5,685 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/blocks/abstract.py | 339,341 | 333,466 | logger | ObjectStorageBlock | 350,355 | 341,355 | class ObjectStorageBlock(Block, ABC):
"""
Block that represents a resource in an external service that can store
objects.
"""
@property
def logger(self) -> Logger:
FILL_FUNC_BODY @abstractmethod
async def download_object_to_path(
self,
from_path: str,
to_path: Uni... | class ObjectStorageBlock(Block, ABC):
"""
Block that represents a resource in an external service that can store
objects.
"""
@property
def logger(self) -> Logger:
"""
Returns a logger based on whether the ObjectStorageBlock
is called from within a flow or task run conte... | try:
return get_run_logger()
except MissingContextError:
return get_logger(self.__class__.__name__)
| """
Returns a logger based on whether the ObjectStorageBlock
is called from within a flow or task run context.
If a run context is present, the logger property returns a run logger.
Else, it returns a default logger labeled with the class's name.
Returns:
The... | 7 | 1,084 | 41 | 1,125 | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... |
5,686 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/blocks/abstract.py | 471,473 | 466,507 | logger | SecretBlock | 482,487 | 473,487 | class SecretBlock(Block, ABC):
"""
Block that represents a resource that can store and retrieve secrets.
"""
@property
def logger(self) -> Logger:
FILL_FUNC_BODY @abstractmethod
async def read_secret(self) -> bytes:
"""
Reads the configured secret from the secret storage serv... | class SecretBlock(Block, ABC):
"""
Block that represents a resource that can store and retrieve secrets.
"""
@property
def logger(self) -> Logger:
"""
Returns a logger based on whether the SecretBlock
is called from within a flow or task run context.
If a run context... | try:
return get_run_logger()
except MissingContextError:
return get_logger(self.__class__.__name__)
| """
Returns a logger based on whether the SecretBlock
is called from within a flow or task run context.
If a run context is present, the logger property returns a run logger.
Else, it returns a default logger labeled with the class's name.
Returns:
The run lo... | 7 | 277 | 41 | 318 | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... | from abc import ABC, abstractmethod
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Generic,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Self
from prefect.b... |
5,689 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/blocks/core.py | 218,220 | 213,264 | schema_extra | Config | 223,264 | 220,264 | class Config:
extra = "allow"
json_encoders = {SecretDict: lambda v: v.dict()}
@staticmethod
def schema_extra(schema: Dict[str, Any], model: Type["Block"]):
FILL_FUNC_BODY | class Config:
extra = "allow"
json_encoders = {SecretDict: lambda v: v.dict()}
@staticmethod
def schema_extra(schema: Dict[str, Any], model: Type["Block"]):
"""
Customizes Pydantic's schema generation feature to add blocks related information.
""... | schema["block_type_slug"] = model.get_block_type_slug()
# Ensures args and code examples aren't included in the schema
description = model.get_description()
if description:
schema["description"] = description
else:
# Prevent the... | """
Customizes Pydantic's schema generation feature to add blocks related information.
"""
schema["block_type_slug"] = model.get_block_type_slug()
# Ensures args and code examples aren't included in the schema
description = model.get_description()
... | 176 | 98 | 555 | 653 | import hashlib
import html
import inspect
import sys
import warnings
from abc import ABC
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Dict,
FrozenSet,
List,
Optional,
Type,
TypeVar,
Union,
)
from uuid import UUID, uuid4
from griffe.dataclasses import Docstrin... | import hashlib
import html
import inspect
import sys
import warnings
from abc import ABC
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Dict,
FrozenSet,
List,
Optional,
Type,
TypeVar,
Union,
)
from uuid import UUID, uuid4
from griffe.dataclasses import Docstrin... |
5,690 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/cli/_types.py | 19,20 | 1,180 | SettingsOption | 21,35 | 20,35 | """
Custom Prefect CLI types
"""
import functools
import sys
from typing import List, Optional
import typer
from rich.console import Console
from rich.theme import Theme
from prefect._internal.compatibility.deprecated import generate_deprecation_message
from prefect.cli._utilities import with_cli_exception_handling
... | """
Custom Prefect CLI types
"""
import functools
import sys
from typing import List, Optional
import typer
from rich.console import Console
from rich.theme import Theme
from prefect._internal.compatibility.deprecated import generate_deprecation_message
from prefect.cli._utilities import with_cli_exception_handling
... |
return typer.Option(
# The default is dynamically retrieved
setting.value,
*args,
# Typer shows "(dynamic)" by default. We'd like to actually show the value
# that would be used if the parameter is not specified and a reference if the
# source is from the environment... | """Custom `typer.Option` factory to load the default value from settings"""
return typer.Option(
# The default is dynamically retrieved
setting.value,
*args,
# Typer shows "(dynamic)" by default. We'd like to actually show the value
# that would be used if the parameter ... | 61 | 1,460 | 151 | 1,611 | """
Custom Prefect CLI types
"""
import functools
import sys
from typing import List, Optional
import typer
from rich.console import Console
from rich.theme import Theme
from prefect._internal.compatibility.deprecated import generate_deprecation_message
from prefect.cli._utilities import with_cli_exception_handling
... | """
Custom Prefect CLI types
"""
import functools
import sys
from typing import List, Optional
import typer
from rich.console import Console
from rich.theme import Theme
from prefect._internal.compatibility.deprecated import generate_deprecation_message
from prefect.cli._utilities import with_cli_exception_handling
... | |
5,691 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/cli/_types.py | 137,138 | 59,180 | wrapper | PrefectTyper | 138,170 | 138,170 | class PrefectTyper(typer.Typer):
"""
Wraps commands created by `Typer` to support async functions and handle errors.
"""
console: Console
def __init__(
self,
*args,
deprecated: bool = False,
deprecated_start_date: Optional[str] = None,
deprecated_help: str =... | class PrefectTyper(typer.Typer):
"""
Wraps commands created by `Typer` to support async functions and handle errors.
"""
console: Console
def __init__(
self,
*args,
deprecated: bool = False,
deprecated_start_date: Optional[str] = None,
deprecated_help: str =... | if is_async_fn(fn):
fn = sync_compatible(fn)
fn = with_cli_exception_handling(fn)
if deprecated:
if not deprecated_name or not deprecated_start_date:
raise ValueError(
"Provide the name of the deprecated comm... | if is_async_fn(fn):
fn = sync_compatible(fn)
fn = with_cli_exception_handling(fn)
if deprecated:
if not deprecated_name or not deprecated_start_date:
raise ValueError(
"Provide the name of the deprecated comm... | 95 | 774 | 371 | 1,145 | """
Custom Prefect CLI types
"""
import functools
import sys
from typing import List, Optional
import typer
from rich.console import Console
from rich.theme import Theme
from prefect._internal.compatibility.deprecated import generate_deprecation_message
from prefect.cli._utilities import with_cli_exception_handling
... | """
Custom Prefect CLI types
"""
import functools
import sys
from typing import List, Optional
import typer
from rich.console import Console
from rich.theme import Theme
from prefect._internal.compatibility.deprecated import generate_deprecation_message
from prefect.cli._utilities import with_cli_exception_handling
... |
5,692 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/cli/_utilities.py | 37,38 | 1,53 | with_cli_exception_handling | 38,53 | 38,53 | """
Utilities for Prefect CLI commands
"""
import functools
import traceback
import typer
from click.exceptions import ClickException
from prefect.exceptions import MissingProfileError
from prefect.settings import PREFECT_TEST_MODE
def exit_with_error(message, code=1, **kwargs):
"""
Utility to print a styl... | """
Utilities for Prefect CLI commands
"""
import functools
import traceback
import typer
from click.exceptions import ClickException
from prefect.exceptions import MissingProfileError
from prefect.settings import PREFECT_TEST_MODE
def exit_with_error(message, code=1, **kwargs):
"""
Utility to print a styl... | @functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except (typer.Exit, typer.Abort, ClickException):
raise # Do not capture click or typer exceptions
except MissingProfileError as exc:
exit_with_error(exc)
excep... | @functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except (typer.Exit, typer.Abort, ClickException):
raise # Do not capture click or typer exceptions
except MissingProfileError as exc:
exit_with_error(exc)
excep... | 43 | 269 | 158 | 427 | """
Utilities for Prefect CLI commands
"""
import functools
import traceback
import typer
from click.exceptions import ClickException
from prefect.exceptions import MissingProfileError
from prefect.settings import PREFECT_TEST_MODE
def exit_with_error(message, code=1, **kwargs):
"""
Utility to print a styl... | """
Utilities for Prefect CLI commands
"""
import functools
import traceback
import typer
from click.exceptions import ClickException
from prefect.exceptions import MissingProfileError
from prefect.settings import PREFECT_TEST_MODE
def exit_with_error(message, code=1, **kwargs):
"""
Utility to print a styl... | |
5,693 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/cli/cloud/webhook.py | 180,182 | 1,198 | delete | 185,198 | 182,198 | """
Command line interface for working with webhooks
"""
from typing import Dict, List
from uuid import UUID
import typer
from rich.table import Table
from prefect.cli._types import PrefectTyper
from prefect.cli._utilities import exit_with_error
from prefect.cli.cloud import cloud_app, confirm_logged_in
from prefect... | """
Command line interface for working with webhooks
"""
from typing import Dict, List
from uuid import UUID
import typer
from rich.table import Table
from prefect.cli._types import PrefectTyper
from prefect.cli._utilities import exit_with_error
from prefect.cli.cloud import cloud_app, confirm_logged_in
from prefect... | confirm_logged_in()
confirm_delete = typer.confirm(
"Are you sure you want to delete it? This cannot be undone."
)
if not confirm_delete:
return
# The /webhooks API lives inside the /accounts/{id}/workspaces/{id} routing tree
async with get_cloud_client(host=PREFECT_API_URL.va... | """
Delete an existing Cloud webhook
"""
confirm_logged_in()
confirm_delete = typer.confirm(
"Are you sure you want to delete it? This cannot be undone."
)
if not confirm_delete:
return
# The /webhooks API lives inside the /accounts/{id}/workspaces/{id} routing tree
... | 43 | 1,873 | 163 | 2,036 | """
Command line interface for working with webhooks
"""
from typing import Dict, List
from uuid import UUID
import typer
from rich.table import Table
from prefect.cli._types import PrefectTyper
from prefect.cli._utilities import exit_with_error
from prefect.cli.cloud import cloud_app, confirm_logged_in
from prefect... | """
Command line interface for working with webhooks
"""
from typing import Dict, List
from uuid import UUID
import typer
from rich.table import Table
from prefect.cli._types import PrefectTyper
from prefect.cli._utilities import exit_with_error
from prefect.cli.cloud import cloud_app, confirm_logged_in
from prefect... | |
5,695 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/cli/events.py | 27,42 | 1,86 | stream | 46,63 | 42,63 | import asyncio
from enum import Enum
import orjson
import typer
import websockets
from anyio import open_file
from prefect.cli._types import PrefectTyper
from prefect.cli._utilities import exit_with_error
from prefect.cli.root import app
from prefect.events import Event
from prefect.events.clients import (
Prefec... | import asyncio
from enum import Enum
import orjson
import typer
import websockets
from anyio import open_file
from prefect.cli._types import PrefectTyper
from prefect.cli._utilities import exit_with_error
from prefect.cli.root import app
from prefect.events import Event
from prefect.events.clients import (
Prefec... |
try:
if account:
events_subscriber = PrefectCloudAccountEventSubscriber()
else:
events_subscriber = get_events_subscriber()
app.console.print("Subscribing to event stream...")
async with events_subscriber as subscriber:
async for event in subscri... | """Subscribes to the event stream of a workspace, printing each event
as it is received. By default, events are printed as JSON, but can be
printed as text by passing `--format text`.
"""
try:
if account:
events_subscriber = PrefectCloudAccountEventSubscriber()
else:
... | 36 | 716 | 152 | 868 | import asyncio
from enum import Enum
import orjson
import typer
import websockets
from anyio import open_file
from prefect.cli._types import PrefectTyper
from prefect.cli._utilities import exit_with_error
from prefect.cli.root import app
from prefect.events import Event
from prefect.events.clients import (
Prefec... | import asyncio
from enum import Enum
import orjson
import typer
import websockets
from anyio import open_file
from prefect.cli._types import PrefectTyper
from prefect.cli._utilities import exit_with_error
from prefect.cli.root import app
from prefect.events import Event
from prefect.events.clients import (
Prefec... | |
5,696 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/cli/kubernetes.py | 118,120 | 1,157 | manifest_flow_run_job | 137,157 | 120,157 | """
Command line interface for working with Prefect on Kubernetes
"""
from string import Template
import typer
import yaml
import prefect
from prefect.cli._types import PrefectTyper, SettingsOption
from prefect.cli.root import app
from prefect.infrastructure import KubernetesJob
from prefect.settings import (
PRE... | """
Command line interface for working with Prefect on Kubernetes
"""
from string import Template
import typer
import yaml
import prefect
from prefect.cli._types import PrefectTyper, SettingsOption
from prefect.cli.root import app
from prefect.infrastructure import KubernetesJob
from prefect.settings import (
PRE... |
KubernetesJob.base_job_manifest()
output = yaml.dump(KubernetesJob.base_job_manifest())
# add some commentary where appropriate
output = output.replace(
"metadata:\n labels:",
"metadata:\n # labels are required, even if empty\n labels:",
)
output = output.replace(
"... | """
Prints the default KubernetesJob Job manifest.
Use this file to fully customize your `KubernetesJob` deployments.
\b
Example:
\b
$ prefect kubernetes manifest flow-run-job
\b
Output, a YAML file:
\b
apiVersion: batch/v1
kind: Job
...
... | 53 | 1,059 | 187 | 1,246 | """
Command line interface for working with Prefect on Kubernetes
"""
from string import Template
import typer
import yaml
import prefect
from prefect.cli._types import PrefectTyper, SettingsOption
from prefect.cli.root import app
from prefect.infrastructure import KubernetesJob
from prefect.settings import (
PRE... | """
Command line interface for working with Prefect on Kubernetes
"""
from string import Template
import typer
import yaml
import prefect
from prefect.cli._types import PrefectTyper, SettingsOption
from prefect.cli.root import app
from prefect.infrastructure import KubernetesJob
from prefect.settings import (
PRE... | |
5,700 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/client/collections.py | 20,23 | 1,35 | get_collections_metadata_client | 30,35 | 23,35 | from typing import Any, Dict, Optional
from typing_extensions import Protocol
from prefect.client.cloud import get_cloud_client
from prefect.client.orchestration import ServerType, get_client
class CollectionsMetadataClient(Protocol):
async def read_worker_metadata(self) -> Dict[str, Any]:
...
asyn... | from typing import Any, Dict, Optional
from typing_extensions import Protocol
from prefect.client.cloud import get_cloud_client
from prefect.client.orchestration import ServerType, get_client
class CollectionsMetadataClient(Protocol):
async def read_worker_metadata(self) -> Dict[str, Any]:
...
asyn... | orchestration_client = get_client(httpx_settings=httpx_settings)
if orchestration_client.server_type == ServerType.CLOUD:
return get_cloud_client(httpx_settings=httpx_settings)
else:
return orchestration_client
| """
Creates a client that can be used to fetch metadata for
Prefect collections.
Will return a `CloudClient` if profile is set to connect
to Prefect Cloud, otherwise will return an `OrchestrationClient`.
"""
orchestration_client = get_client(httpx_settings=httpx_settings)
if orchestrati... | 12 | 239 | 81 | 320 | from typing import Any, Dict, Optional
from typing_extensions import Protocol
from prefect.client.cloud import get_cloud_client
from prefect.client.orchestration import ServerType, get_client
class CollectionsMetadataClient(Protocol):
async def read_worker_metadata(self) -> Dict[str, Any]:
...
asyn... | from typing import Any, Dict, Optional
from typing_extensions import Protocol
from prefect.client.cloud import get_cloud_client
from prefect.client.orchestration import ServerType, get_client
class CollectionsMetadataClient(Protocol):
async def read_worker_metadata(self) -> Dict[str, Any]:
...
asyn... | |
5,701 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/client/collections.py | 10,11 | 9,20 | read_worker_metadata | CollectionsMetadataClient | 11,13 | 11,13 | class CollectionsMetadataClient(Protocol):
async def read_worker_metadata(self) -> Dict[str, Any]:
FILL_FUNC_BODY async def __aenter__(self) -> "CollectionsMetadataClient":
...
async def __aexit__(self, *exc_info) -> Any:
...
| class CollectionsMetadataClient(Protocol):
async def read_worker_metadata(self) -> Dict[str, Any]:
FILL_FUNC_BODY async def __aenter__(self) -> "CollectionsMetadataClient":
...
async def __aexit__(self, *exc_info) -> Any:
...
| ...
| ...
| 1 | 85 | 6 | 91 | from typing import Any, Dict, Optional
from typing_extensions import Protocol
from prefect.client.cloud import get_cloud_client
from prefect.client.orchestration import ServerType, get_client
class CollectionsMetadataClient(Protocol):
async def read_worker_metadata(self) -> Dict[str, Any]:
FILL_FUNC_BODY asy... | from typing import Any, Dict, Optional
from typing_extensions import Protocol
from prefect.client.cloud import get_cloud_client
from prefect.client.orchestration import ServerType, get_client
class CollectionsMetadataClient(Protocol):
async def read_worker_metadata(self) -> Dict[str, Any]:
FILL_FUNC_BODY asy... |
5,704 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/client/orchestration.py | 174,175 | 169,181 | supports_automations | ServerType | 175,181 | 175,181 | class ServerType(AutoEnum):
EPHEMERAL = AutoEnum.auto()
SERVER = AutoEnum.auto()
CLOUD = AutoEnum.auto()
def supports_automations(self) -> bool:
FILL_FUNC_BODY | class ServerType(AutoEnum):
EPHEMERAL = AutoEnum.auto()
SERVER = AutoEnum.auto()
CLOUD = AutoEnum.auto()
def supports_automations(self) -> bool:
FILL_FUNC_BODY | if self == ServerType.CLOUD:
return True
return PREFECT_EXPERIMENTAL_EVENTS and PREFECT_API_SERVICES_TRIGGERS_ENABLED
| if self == ServerType.CLOUD:
return True
return PREFECT_EXPERIMENTAL_EVENTS and PREFECT_API_SERVICES_TRIGGERS_ENABLED
| 10 | 66 | 59 | 125 | import asyncio
import datetime
import warnings
from contextlib import AsyncExitStack
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
NoReturn,
Optional,
Set,
Tuple,
TypeVar,
Union,
)
from uuid import UUID, uuid4
import certifi
import httpcore
import httpx
impo... | import asyncio
import datetime
import warnings
from contextlib import AsyncExitStack
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
NoReturn,
Optional,
Set,
Tuple,
TypeVar,
Union,
)
from uuid import UUID, uuid4
import certifi
import httpcore
import httpx
impo... |
5,706 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/client/utilities.py | 30,33 | 1,103 | get_or_create_client | 42,66 | 33,66 | """
Utilities for working with clients.
"""
# This module must not import from `prefect.client` when it is imported to avoid
# circular imports for decorators such as `inject_client` which are widely used.
from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Co... | """
Utilities for working with clients.
"""
# This module must not import from `prefect.client` when it is imported to avoid
# circular imports for decorators such as `inject_client` which are widely used.
from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Co... | if client is not None:
return client, True
from prefect._internal.concurrency.event_loop import get_running_loop
from prefect.context import FlowRunContext, TaskRunContext
flow_run_context = FlowRunContext.get()
task_run_context = TaskRunContext.get()
if (
flow_run_context
... | """
Returns provided client, infers a client from context if available, or creates a new client.
Args:
- client (PrefectClient, optional): an optional client to use
Returns:
- tuple: a tuple of the client and a boolean indicating if the client was inferred from context
"""
if c... | 59 | 704 | 250 | 954 | """
Utilities for working with clients.
"""
# This module must not import from `prefect.client` when it is imported to avoid
# circular imports for decorators such as `inject_client` which are widely used.
from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Co... | """
Utilities for working with clients.
"""
# This module must not import from `prefect.client` when it is imported to avoid
# circular imports for decorators such as `inject_client` which are widely used.
from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Co... | |
5,707 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/concurrency/events.py | 8,15 | 1,60 | _emit_concurrency_event | 15,41 | 15,41 | from typing import Dict, List, Literal, Optional, Union
from uuid import UUID
from prefect.client.schemas.responses import MinimalConcurrencyLimitResponse
from prefect.events import Event, RelatedResource, emit_event
def _emit_concurrency_event(
phase: Union[Literal["acquired"], Literal["released"]],
primary... | from typing import Dict, List, Literal, Optional, Union
from uuid import UUID
from prefect.client.schemas.responses import MinimalConcurrencyLimitResponse
from prefect.events import Event, RelatedResource, emit_event
def _emit_concurrency_event(
phase: Union[Literal["acquired"], Literal["released"]],
primary... | resource: Dict[str, str] = {
"prefect.resource.id": f"prefect.concurrency-limit.{primary_limit.id}",
"prefect.resource.name": primary_limit.name,
"slots-acquired": str(slots),
"limit": str(primary_limit.limit),
}
related = [
RelatedResource.parse_obj(
{
... | resource: Dict[str, str] = {
"prefect.resource.id": f"prefect.concurrency-limit.{primary_limit.id}",
"prefect.resource.name": primary_limit.name,
"slots-acquired": str(slots),
"limit": str(primary_limit.limit),
}
related = [
RelatedResource.parse_obj(
{
... | 41 | 333 | 252 | 585 | from typing import Dict, List, Literal, Optional, Union
from uuid import UUID
from prefect.client.schemas.responses import MinimalConcurrencyLimitResponse
from prefect.events import Event, RelatedResource, emit_event
def _emit_concurrency_event(
phase: Union[Literal["acquired"], Literal["released"]],
primary... | from typing import Dict, List, Literal, Optional, Union
from uuid import UUID
from prefect.client.schemas.responses import MinimalConcurrencyLimitResponse
from prefect.events import Event, RelatedResource, emit_event
def _emit_concurrency_event(
phase: Union[Literal["acquired"], Literal["released"]],
primary... | |
5,708 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/concurrency/sync.py | 27,33 | 1,104 | concurrency | 58,80 | 33,80 | from contextlib import contextmanager
from typing import List, Optional, Union, cast
import pendulum
try:
from pendulum import Interval
except ImportError:
# pendulum < 3
from pendulum.period import Period as Interval # type: ignore
from prefect._internal.concurrency.api import create_call, from_sync
fr... | from contextlib import contextmanager
from typing import List, Optional, Union, cast
import pendulum
try:
from pendulum import Interval
except ImportError:
# pendulum < 3
from pendulum.period import Period as Interval # type: ignore
from prefect._internal.concurrency.api import create_call, from_sync
fr... | names = names if isinstance(names, list) else [names]
with timeout(seconds=timeout_seconds):
limits: List[MinimalConcurrencyLimitResponse] = _call_async_function_from_sync(
_acquire_concurrency_slots, names, occupy
)
acquisition_time = pendulum.now("UTC")
emitted_events = _e... | """A context manager that acquires and releases concurrency slots from the
given concurrency limits.
Args:
names: The names of the concurrency limits to acquire slots from.
occupy: The number of slots to acquire and hold from each limit.
timeout_seconds: The number of seconds to wai... | 43 | 749 | 242 | 991 | from contextlib import contextmanager
from typing import List, Optional, Union, cast
import pendulum
try:
from pendulum import Interval
except ImportError:
# pendulum < 3
from pendulum.period import Period as Interval # type: ignore
from prefect._internal.concurrency.api import create_call, from_sync
fr... | from contextlib import contextmanager
from typing import List, Optional, Union, cast
import pendulum
try:
from pendulum import Interval
except ImportError:
# pendulum < 3
from pendulum.period import Period as Interval # type: ignore
from prefect._internal.concurrency.api import create_call, from_sync
fr... | |
5,709 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/deployments/schedules.py | 17,21 | 1,51 | create_minimal_deployment_schedule | 21,27 | 21,27 | from typing import List, Optional, Sequence, Union, get_args
from prefect.client.schemas.objects import MinimalDeploymentSchedule
from prefect.client.schemas.schedules import SCHEDULE_TYPES
try:
from prefect.server.schemas.schedules import SCHEDULE_TYPES as SERVER_SCHEDULE_TYPES
SERVER_SCHEDULE_TYPES = get_a... | from typing import List, Optional, Sequence, Union, get_args
from prefect.client.schemas.objects import MinimalDeploymentSchedule
from prefect.client.schemas.schedules import SCHEDULE_TYPES
try:
from prefect.server.schemas.schedules import SCHEDULE_TYPES as SERVER_SCHEDULE_TYPES
SERVER_SCHEDULE_TYPES = get_a... | return MinimalDeploymentSchedule(
schedule=schedule,
active=active if active is not None else True,
)
| return MinimalDeploymentSchedule(
schedule=schedule,
active=active if active is not None else True,
)
| 12 | 520 | 41 | 561 | from typing import List, Optional, Sequence, Union, get_args
from prefect.client.schemas.objects import MinimalDeploymentSchedule
from prefect.client.schemas.schedules import SCHEDULE_TYPES
try:
from prefect.server.schemas.schedules import SCHEDULE_TYPES as SERVER_SCHEDULE_TYPES
SERVER_SCHEDULE_TYPES = get_a... | from typing import List, Optional, Sequence, Union, get_args
from prefect.client.schemas.objects import MinimalDeploymentSchedule
from prefect.client.schemas.schedules import SCHEDULE_TYPES
try:
from prefect.server.schemas.schedules import SCHEDULE_TYPES as SERVER_SCHEDULE_TYPES
SERVER_SCHEDULE_TYPES = get_a... | |
5,713 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/deprecated/data_documents.py | 120,121 | 82,153 | decode | DataDocument | 126,135 | 121,135 | class DataDocument(PrefectBaseModel, Generic[D]):
"""
A data document includes an encoding string and a blob of encoded data
Subclasses can define the expected type for the blob's underlying type using the
generic variable `D`.
For example `DataDocument[str]` indicates that a string should be pass... | class DataDocument(PrefectBaseModel, Generic[D]):
"""
A data document includes an encoding string and a blob of encoded data
Subclasses can define the expected type for the blob's underlying type using the
generic variable `D`.
For example `DataDocument[str]` indicates that a string should be pass... | if self.has_cached_data():
return self._data
# Dispatch decoding
data = lookup_serializer(self.encoding).loads(self.blob)
self._cache_data(data)
return data
| """
Get the data from a data document
A serializer must be registered for the document's encoding
"""
if self.has_cached_data():
return self._data
# Dispatch decoding
data = lookup_serializer(self.encoding).loads(self.blob)
self._cache_data(... | 13 | 563 | 71 | 634 | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... |
5,714 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/deprecated/data_documents.py | 174,176 | 153,179 | loads | DocumentJSONSerializer | 176,179 | 176,179 | @register_serializer("json")
class DocumentJSONSerializer:
"""
Serializes data to JSON.
Input types must be compatible with the stdlib json library.
Wraps the `json` library to serialize to UTF-8 bytes instead of string types.
"""
@staticmethod
@deprecated_callable(
start_date="Se... | @register_serializer("json")
class DocumentJSONSerializer:
"""
Serializes data to JSON.
Input types must be compatible with the stdlib json library.
Wraps the `json` library to serialize to UTF-8 bytes instead of string types.
"""
@staticmethod
@deprecated_callable(
start_date="Se... | return json.loads(blob.decode())
| return json.loads(blob.decode())
| 2 | 185 | 17 | 202 | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... |
5,715 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/deprecated/data_documents.py | 218,220 | 197,227 | loads | DocumentPickleSerializer | 220,227 | 220,227 | @register_serializer("cloudpickle")
class DocumentPickleSerializer:
"""
Serializes arbitrary objects using the pickle protocol.
Wraps `cloudpickle` to encode bytes in base64 for safe transmission.
"""
@staticmethod
@deprecated_callable(
start_date="Sep 2022",
help=(
... | @register_serializer("cloudpickle")
class DocumentPickleSerializer:
"""
Serializes arbitrary objects using the pickle protocol.
Wraps `cloudpickle` to encode bytes in base64 for safe transmission.
"""
@staticmethod
@deprecated_callable(
start_date="Sep 2022",
help=(
... | return cloudpickle.loads(base64.decodebytes(blob))
# TODO: Consider adding python version data to pickle payloads to raise
# more helpful errors for users.
# A TypeError("expected bytes-like object, not int") will be raised if
# a document is deserialized by Pyt... | return cloudpickle.loads(base64.decodebytes(blob))
# TODO: Consider adding python version data to pickle payloads to raise
# more helpful errors for users.
# A TypeError("expected bytes-like object, not int") will be raised if
# a document is deserialized by Pyt... | 43 | 196 | 102 | 298 | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... |
5,716 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/deprecated/data_documents.py | 233,242 | 227,251 | dumps | PackageManifestSerializer | 242,244 | 242,244 | @register_serializer("package-manifest")
class PackageManifestSerializer:
"""
Serializes a package manifest.
"""
@staticmethod
@deprecated_callable(
start_date="Sep 2022",
help=(
"Data document serializers should not be used. Use result serializers"
" instead... | @register_serializer("package-manifest")
class PackageManifestSerializer:
"""
Serializes a package manifest.
"""
@staticmethod
@deprecated_callable(
start_date="Sep 2022",
help=(
"Data document serializers should not be used. Use result serializers"
" instead... | return data.json().encode()
| return data.json().encode()
| 2 | 173 | 12 | 185 | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... |
5,717 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/deprecated/data_documents.py | 268,270 | 251,273 | loads | ResultSerializer | 270,273 | 270,273 | @register_serializer("result")
class ResultSerializer:
"""
Serializes a result object
"""
@staticmethod
@deprecated_callable(
start_date="Sep 2022",
help=(
"Data document serializers should not be used. Use result serializers"
" instead."
),
)
... | @register_serializer("result")
class ResultSerializer:
"""
Serializes a result object
"""
@staticmethod
@deprecated_callable(
start_date="Sep 2022",
help=(
"Data document serializers should not be used. Use result serializers"
" instead."
),
)
... | return _Result.parse_raw(blob)
| return _Result.parse_raw(blob)
| 2 | 142 | 17 | 159 | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... |
5,718 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/deprecated/data_documents.py | 53,55 | 44,58 | loads | Serializer | 55,58 | 55,58 | class Serializer(Protocol[D]):
"""
Define a serializer that can encode data of type 'D' into bytes
"""
@staticmethod
def dumps(data: D, **kwargs: Any) -> bytes:
raise NotImplementedError
@staticmethod
def loads(blob: bytes) -> D:
FILL_FUNC_BODY | class Serializer(Protocol[D]):
"""
Define a serializer that can encode data of type 'D' into bytes
"""
@staticmethod
def dumps(data: D, **kwargs: Any) -> bytes:
raise NotImplementedError
@staticmethod
def loads(blob: bytes) -> D:
FILL_FUNC_BODY | raise NotImplementedError
| raise NotImplementedError
| 2 | 95 | 13 | 108 | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... |
5,719 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/deprecated/data_documents.py | 181,190 | 179,197 | dumps | TextSerializer | 190,192 | 190,192 | @register_serializer("text")
class TextSerializer:
@staticmethod
@deprecated_callable(
start_date="Sep 2022",
help=(
"Data document serializers should not be used. Use result serializers"
" instead."
),
)
def dumps(data: str) -> bytes:
FILL_FUNC_BODY @s... | @register_serializer("text")
class TextSerializer:
@staticmethod
@deprecated_callable(
start_date="Sep 2022",
help=(
"Data document serializers should not be used. Use result serializers"
" instead."
),
)
def dumps(data: str) -> bytes:
FILL_FUNC_BODY @s... | return data.encode()
| return data.encode()
| 2 | 126 | 10 | 136 | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... | import base64
import json
import uuid
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
Tuple,
Type,
TypeVar,
Union,
)
import cloudpickle
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
import pydantic.v1 as pydantic
e... |
5,720 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/deprecated/packaging/base.py | 84,85 | 67,97 | base_manifest | Packager | 85,92 | 85,92 | @deprecated_class(start_date="Mar 2024")
@add_type_dispatch
class Packager(BaseModel, abc.ABC):
"""
DEPRECATION WARNING:
This class is deprecated as of version March 2024 and will not be available after September 2024.
Creates a package for a flow.
A package contains the flow and is typically sto... | @deprecated_class(start_date="Mar 2024")
@add_type_dispatch
class Packager(BaseModel, abc.ABC):
"""
DEPRECATION WARNING:
This class is deprecated as of version March 2024 and will not be available after September 2024.
Creates a package for a flow.
A package contains the flow and is typically sto... | manifest_cls: Type[BaseModel] = lookup_type(PackageManifest, self.type)
return manifest_cls.construct(
type=self.type,
flow_name=flow.name,
flow_parameter_schema=parameter_schema(flow.fn),
)
| manifest_cls: Type[BaseModel] = lookup_type(PackageManifest, self.type)
return manifest_cls.construct(
type=self.type,
flow_name=flow.name,
flow_parameter_schema=parameter_schema(flow.fn),
)
| 11 | 220 | 78 | 298 | """
DEPRECATION WARNING:
This module is deprecated as of March 2024 and will not be available after September 2024.
"""
import abc
from typing import Generic, Type, TypeVar
from prefect._internal.compatibility.deprecated import deprecated_class
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V... | """
DEPRECATION WARNING:
This module is deprecated as of March 2024 and will not be available after September 2024.
"""
import abc
from typing import Generic, Type, TypeVar
from prefect._internal.compatibility.deprecated import deprecated_class
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V... |
5,721 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/events/instrument.py | 108,109 | 1,136 | instrument_method_calls_on_class_instances | 122,136 | 109,136 | import functools
import inspect
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from prefect.events import emit_event
ResourceTuple = Tuple[Dict[str, Any], List[Dict[str, Any]]]
def emit_instance_method_ca... | import functools
import inspect
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from prefect.events import emit_event
ResourceTuple = Tuple[Dict[str, Any], List[Dict[str, Any]]]
def emit_instance_method_ca... |
required_events_methods = ["_event_kind", "_event_method_called_resources"]
for method_name in required_events_methods:
if not hasattr(cls, method_name):
raise RuntimeError(
f"Unable to instrument class {cls}. Class must define {method_name!r}."
)
for method... | """Given a Python class, instruments all "public" methods that are
defined directly on the class to emit events when called.
Examples:
@instrument_class
class MyClass(MyBase):
def my_method(self):
... this method will be instrumented ...
def _my_met... | 39 | 891 | 167 | 1,058 | import functools
import inspect
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from prefect.events import emit_event
ResourceTuple = Tuple[Dict[str, Any], List[Dict[str, Any]]]
def emit_instance_method_ca... | import functools
import inspect
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from prefect.events import emit_event
ResourceTuple = Tuple[Dict[str, Any], List[Dict[str, Any]]]
def emit_instance_method_ca... | |
5,722 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/events/schemas/deployment_triggers.py | 245,246 | 126,296 | as_automation | DeploymentTrigger | 246,280 | 246,280 | @deprecated_class(
start_date="Mar 2024",
help=textwrap.dedent(
"""
To associate a specific kind of trigger with a Deployment, use one of the more
specific deployment trigger types instead:
* DeploymentEventTrigger to associate an EventTrigger with a deployment
* DeploymentMetricTrigger... | @deprecated_class(
start_date="Mar 2024",
help=textwrap.dedent(
"""
To associate a specific kind of trigger with a Deployment, use one of the more
specific deployment trigger types instead:
* DeploymentEventTrigger to associate an EventTrigger with a deployment
* DeploymentMetricTrigger... | assert self.name
trigger: TriggerTypes
if self.posture == Posture.Metric:
assert self.metric
trigger = MetricTrigger(
type="metric",
match=self.match,
match_related=self.match_related,
posture=self.posture,... | assert self.name
trigger: TriggerTypes
if self.posture == Posture.Metric:
assert self.metric
trigger = MetricTrigger(
type="metric",
match=self.match,
match_related=self.match_related,
posture=self.posture,... | 41 | 1,336 | 278 | 1,614 | """
Schemas for defining triggers within a Prefect deployment YAML. This is a separate
parallel hierarchy for representing triggers so that they can also include the
information necessary to create an automation.
These triggers should follow the validation rules of the main Trigger class hierarchy as
closely as possi... | """
Schemas for defining triggers within a Prefect deployment YAML. This is a separate
parallel hierarchy for representing triggers so that they can also include the
information necessary to create an automation.
These triggers should follow the validation rules of the main Trigger class hierarchy as
closely as possi... |
5,723 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/events/schemas/labelling.py | 82,83 | 74,107 | items | Labelled | 83,85 | 83,85 | class Labelled(PrefectBaseModel, extra="ignore"): # type: ignore[call-arg]
"""An object defined by string labels and values"""
__root__: Dict[str, str]
def keys(self) -> Iterable[str]:
return self.__root__.keys()
def items(self) -> Iterable[Tuple[str, str]]:
FILL_FUNC_BODY def __getitem__... | class Labelled(PrefectBaseModel, extra="ignore"): # type: ignore[call-arg]
"""An object defined by string labels and values"""
__root__: Dict[str, str]
def keys(self) -> Iterable[str]:
return self.__root__.keys()
def items(self) -> Iterable[Tuple[str, str]]:
FILL_FUNC_BODY def __getitem__... | return self.__root__.items()
| return self.__root__.items()
| 2 | 368 | 13 | 381 | from typing import Dict, Iterable, Iterator, List, Optional, Tuple
from prefect._internal.schemas.bases import PrefectBaseModel
class LabelDiver:
"""The LabelDiver supports templating use cases for any Labelled object, by
presenting the labels as a graph of objects that may be accessed by attribute. For
... | from typing import Dict, Iterable, Iterator, List, Optional, Tuple
from prefect._internal.schemas.bases import PrefectBaseModel
class LabelDiver:
"""The LabelDiver supports templating use cases for any Labelled object, by
presenting the labels as a graph of objects that may be accessed by attribute. For
... |
5,724 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/events/utilities.py | 21,30 | 1,90 | emit_event | 50,90 | 30,90 | from datetime import timedelta
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
import pendulum
from prefect._internal.schemas.fields import DateTimeTZ
from .clients import (
AssertingEventsClient,
PrefectCloudEventsClient,
PrefectEphemeralEventsClient,
PrefectEventsClient,
)... | from datetime import timedelta
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
import pendulum
from prefect._internal.schemas.fields import DateTimeTZ
from .clients import (
AssertingEventsClient,
PrefectCloudEventsClient,
PrefectEphemeralEventsClient,
PrefectEventsClient,
)... | if not should_emit_events():
return None
operational_clients = [
AssertingEventsClient,
PrefectCloudEventsClient,
PrefectEventsClient,
PrefectEphemeralEventsClient,
]
worker_instance = EventsWorker.instance()
if worker_instance.client_type not in operational... | """
Send an event to Prefect Cloud.
Args:
event: The name of the event that happened.
resource: The primary Resource this event concerns.
occurred: When the event happened from the sender's perspective.
Defaults to the current datetime.
related: A list of a... | 89 | 443 | 342 | 785 | from datetime import timedelta
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
import pendulum
from prefect._internal.schemas.fields import DateTimeTZ
from .clients import (
AssertingEventsClient,
PrefectCloudEventsClient,
PrefectEphemeralEventsClient,
PrefectEventsClient,
)... | from datetime import timedelta
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
import pendulum
from prefect._internal.schemas.fields import DateTimeTZ
from .clients import (
AssertingEventsClient,
PrefectCloudEventsClient,
PrefectEphemeralEventsClient,
PrefectEventsClient,
)... | |
5,725 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/events/worker.py | 36,37 | 1,108 | emit_events_to_cloud | 37,43 | 37,43 | from contextlib import asynccontextmanager
from contextvars import Context, copy_context
from typing import Any, Dict, Optional, Tuple, Type
from uuid import UUID
from typing_extensions import Self
from prefect._internal.concurrency.services import QueueService
from prefect.settings import (
PREFECT_API_KEY,
... | from contextlib import asynccontextmanager
from contextvars import Context, copy_context
from typing import Any, Dict, Optional, Tuple, Type
from uuid import UUID
from typing_extensions import Self
from prefect._internal.concurrency.services import QueueService
from prefect.settings import (
PREFECT_API_KEY,
... | api_url = PREFECT_API_URL.value()
return isinstance(api_url, str) and api_url.startswith(
PREFECT_CLOUD_API_URL.value()
)
| api_url = PREFECT_API_URL.value()
return isinstance(api_url, str) and api_url.startswith(
PREFECT_CLOUD_API_URL.value()
)
| 10 | 1,004 | 64 | 1,068 | from contextlib import asynccontextmanager
from contextvars import Context, copy_context
from typing import Any, Dict, Optional, Tuple, Type
from uuid import UUID
from typing_extensions import Self
from prefect._internal.concurrency.services import QueueService
from prefect.settings import (
PREFECT_API_KEY,
... | from contextlib import asynccontextmanager
from contextvars import Context, copy_context
from typing import Any, Dict, Optional, Tuple, Type
from uuid import UUID
from typing_extensions import Self
from prefect._internal.concurrency.services import QueueService
from prefect.settings import (
PREFECT_API_KEY,
... | |
5,726 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/events/worker.py | 84,88 | 52,108 | instance | EventsWorker | 88,108 | 88,108 | class EventsWorker(QueueService[Event]):
def __init__(
self, client_type: Type[EventsClient], client_options: Tuple[Tuple[str, Any]]
):
super().__init__(client_type, client_options)
self.client_type = client_type
self.client_options = client_options
self._client: EventsCl... | class EventsWorker(QueueService[Event]):
def __init__(
self, client_type: Type[EventsClient], client_options: Tuple[Tuple[str, Any]]
):
super().__init__(client_type, client_options)
self.client_type = client_type
self.client_options = client_options
self._client: EventsCl... | client_kwargs = {}
# Select a client type for this worker based on settings
if client_type is None:
if emit_events_to_cloud():
client_type = PrefectCloudEventsClient
client_kwargs = {
"api_url": PREFECT_API_URL.value(),
... | client_kwargs = {}
# Select a client type for this worker based on settings
if client_type is None:
if emit_events_to_cloud():
client_type = PrefectCloudEventsClient
client_kwargs = {
"api_url": PREFECT_API_URL.value(),
... | 66 | 394 | 228 | 622 | from contextlib import asynccontextmanager
from contextvars import Context, copy_context
from typing import Any, Dict, Optional, Tuple, Type
from uuid import UUID
from typing_extensions import Self
from prefect._internal.concurrency.services import QueueService
from prefect.settings import (
PREFECT_API_KEY,
... | from contextlib import asynccontextmanager
from contextvars import Context, copy_context
from typing import Any, Dict, Optional, Tuple, Type
from uuid import UUID
from typing_extensions import Self
from prefect._internal.concurrency.services import QueueService
from prefect.settings import (
PREFECT_API_KEY,
... |
5,727 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/flow_runs.py | 13,21 | 1,91 | wait_for_flow_run | 77,91 | 21,91 | from typing import Optional
from uuid import UUID
import anyio
from prefect.client.orchestration import PrefectClient
from prefect.client.schemas import FlowRun
from prefect.client.utilities import inject_client
from prefect.exceptions import FlowRunWaitTimeout
from prefect.logging import get_logger
@inject_client
... | from typing import Optional
from uuid import UUID
import anyio
from prefect.client.orchestration import PrefectClient
from prefect.client.schemas import FlowRun
from prefect.client.utilities import inject_client
from prefect.exceptions import FlowRunWaitTimeout
from prefect.logging import get_logger
@inject_client
... | assert client is not None, "Client injection failed"
logger = get_logger()
with anyio.move_on_after(timeout):
while True:
flow_run = await client.read_flow_run(flow_run_id)
flow_state = flow_run.state
if log_states:
logger.info(f"Flow run is in sta... | """
Waits for the prefect flow run to finish and returns the FlowRun
Args:
flow_run_id: The flow run ID for the flow run to wait for.
timeout: The wait timeout in seconds. Defaults to 10800 (3 hours).
poll_interval: The poll interval in seconds. Defaults to 5.
Returns:
... | 52 | 715 | 188 | 903 | from typing import Optional
from uuid import UUID
import anyio
from prefect.client.orchestration import PrefectClient
from prefect.client.schemas import FlowRun
from prefect.client.utilities import inject_client
from prefect.exceptions import FlowRunWaitTimeout
from prefect.logging import get_logger
@inject_client
... | from typing import Optional
from uuid import UUID
import anyio
from prefect.client.orchestration import PrefectClient
from prefect.client.schemas import FlowRun
from prefect.client.utilities import inject_client
from prefect.exceptions import FlowRunWaitTimeout
from prefect.logging import get_logger
@inject_client
... | |
5,730 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/logging/configuration.py | 30,31 | 1,111 | load_logging_config | 34,65 | 31,65 | import logging
import logging.config
import os
import re
import string
import warnings
from functools import partial
from pathlib import Path
from typing import Any, Dict, Optional
import yaml
from prefect.settings import (
PREFECT_LOGGING_EXTRA_LOGGERS,
PREFECT_LOGGING_SETTINGS_PATH,
SETTING_VARIABLES,
)... | import logging
import logging.config
import os
import re
import string
import warnings
from functools import partial
from pathlib import Path
from typing import Any, Dict, Optional
import yaml
from prefect.settings import (
PREFECT_LOGGING_EXTRA_LOGGERS,
PREFECT_LOGGING_SETTINGS_PATH,
SETTING_VARIABLES,
)... | template = string.Template(path.read_text())
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
config = yaml.safe_load(
# Substitute settings into the template in format $SETTING / ${SETTING}
template.substitute(
... | """
Loads logging configuration from a path allowing override from the environment
"""
template = string.Template(path.read_text())
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
config = yaml.safe_load(
# Substitute setting... | 84 | 744 | 317 | 1,061 | import logging
import logging.config
import os
import re
import string
import warnings
from functools import partial
from pathlib import Path
from typing import Any, Dict, Optional
import yaml
from prefect.settings import (
PREFECT_LOGGING_EXTRA_LOGGERS,
PREFECT_LOGGING_SETTINGS_PATH,
SETTING_VARIABLES,
)... | import logging
import logging.config
import os
import re
import string
import warnings
from functools import partial
from pathlib import Path
from typing import Any, Dict, Optional
import yaml
from prefect.settings import (
PREFECT_LOGGING_EXTRA_LOGGERS,
PREFECT_LOGGING_SETTINGS_PATH,
SETTING_VARIABLES,
)... | |
5,731 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/logging/filters.py | 8,9 | 1,42 | redact_substr | 19,29 | 9,29 | import logging
from typing import Any
from prefect.utilities.collections import visit_collection
from prefect.utilities.names import obfuscate
def redact_substr(obj: Any, substr: str):
FILL_FUNC_BODYclass ObfuscateApiKeyFilter(logging.Filter):
"""
A logging filter that obfuscates any string that matches the ... | import logging
from typing import Any
from prefect.utilities.collections import visit_collection
from prefect.utilities.names import obfuscate
def redact_substr(obj: Any, substr: str):
"""
Redact a string from a potentially nested object.
Args:
obj: The object to redact the string from
s... |
def redact_item(item):
if isinstance(item, str):
return item.replace(substr, obfuscate(substr))
return item
redacted_obj = visit_collection(obj, visit_fn=redact_item, return_data=True)
return redacted_obj
| """
Redact a string from a potentially nested object.
Args:
obj: The object to redact the string from
substr: The string to redact.
Returns:
Any: The object with the API key redacted.
"""
def redact_item(item):
if isinstance(item, str):
return item.... | 17 | 261 | 91 | 352 | import logging
from typing import Any
from prefect.utilities.collections import visit_collection
from prefect.utilities.names import obfuscate
def redact_substr(obj: Any, substr: str):
FILL_FUNC_BODYclass ObfuscateApiKeyFilter(logging.Filter):
"""
A logging filter that obfuscates any string that matches the ... | import logging
from typing import Any
from prefect.utilities.collections import visit_collection
from prefect.utilities.names import obfuscate
def redact_substr(obj: Any, substr: str):
"""
Redact a string from a potentially nested object.
Args:
obj: The object to redact the string from
s... | |
5,732 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/logging/filters.py | 34,35 | 29,42 | filter | ObfuscateApiKeyFilter | 35,42 | 35,42 | class ObfuscateApiKeyFilter(logging.Filter):
"""
A logging filter that obfuscates any string that matches the obfuscate_string function.
"""
def filter(self, record: logging.LogRecord) -> bool:
FILL_FUNC_BODY | class ObfuscateApiKeyFilter(logging.Filter):
"""
A logging filter that obfuscates any string that matches the obfuscate_string function.
"""
def filter(self, record: logging.LogRecord) -> bool:
FILL_FUNC_BODY | # Need to import here to avoid circular imports
from prefect.settings import PREFECT_API_KEY
if PREFECT_API_KEY:
record.msg = redact_substr(record.msg, PREFECT_API_KEY.value())
return True
| # Need to import here to avoid circular imports
from prefect.settings import PREFECT_API_KEY
if PREFECT_API_KEY:
record.msg = redact_substr(record.msg, PREFECT_API_KEY.value())
return True
| 21 | 72 | 77 | 149 | import logging
from typing import Any
from prefect.utilities.collections import visit_collection
from prefect.utilities.names import obfuscate
def redact_substr(obj: Any, substr: str):
"""
Redact a string from a potentially nested object.
Args:
obj: The object to redact the string from
s... | import logging
from typing import Any
from prefect.utilities.collections import visit_collection
from prefect.utilities.names import obfuscate
def redact_substr(obj: Any, substr: str):
"""
Redact a string from a potentially nested object.
Args:
obj: The object to redact the string from
s... |
5,733 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/logging/formatters.py | 17,18 | 1,135 | format_exception_info | 18,35 | 18,35 | import logging.handlers
import sys
import traceback
from types import TracebackType
from typing import Optional, Tuple, Type, Union
import orjson
from prefect.serializers import JSONSerializer
ExceptionInfoType = Union[
Tuple[Type[BaseException], BaseException, Optional[TracebackType]],
Tuple[None, None, Non... | import logging.handlers
import sys
import traceback
from types import TracebackType
from typing import Optional, Tuple, Type, Union
import orjson
from prefect.serializers import JSONSerializer
ExceptionInfoType = Union[
Tuple[Type[BaseException], BaseException, Optional[TracebackType]],
Tuple[None, None, Non... | # if sys.exc_info() returned a (None, None, None) tuple,
# then there's nothing to format
if exc_info[0] is None:
return {}
(exception_type, exception_obj, exception_traceback) = exc_info
return {
"type": exception_type.__name__,
"message": str(exception_obj),
"trace... | # if sys.exc_info() returned a (None, None, None) tuple,
# then there's nothing to format
if exc_info[0] is None:
return {}
(exception_type, exception_obj, exception_traceback) = exc_info
return {
"type": exception_type.__name__,
"message": str(exception_obj),
"trace... | 41 | 1,102 | 156 | 1,258 | import logging.handlers
import sys
import traceback
from types import TracebackType
from typing import Optional, Tuple, Type, Union
import orjson
from prefect.serializers import JSONSerializer
ExceptionInfoType = Union[
Tuple[Type[BaseException], BaseException, Optional[TracebackType]],
Tuple[None, None, Non... | import logging.handlers
import sys
import traceback
from types import TracebackType
from typing import Optional, Tuple, Type, Union
import orjson
from prefect.serializers import JSONSerializer
ExceptionInfoType = Union[
Tuple[Type[BaseException], BaseException, Optional[TracebackType]],
Tuple[None, None, Non... | |
5,734 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/logging/formatters.py | 55,56 | 35,73 | format | JsonFormatter | 56,73 | 56,73 | class JsonFormatter(logging.Formatter):
"""
Formats log records as a JSON string.
The format may be specified as "pretty" to format the JSON with indents and
newlines.
"""
def __init__(self, fmt, dmft, style) -> None: # noqa
super().__init__()
if fmt not in ["pretty", "defaul... | class JsonFormatter(logging.Formatter):
"""
Formats log records as a JSON string.
The format may be specified as "pretty" to format the JSON with indents and
newlines.
"""
def __init__(self, fmt, dmft, style) -> None: # noqa
super().__init__()
if fmt not in ["pretty", "defaul... | record_dict = record.__dict__.copy()
# GCP severity detection compatibility
record_dict.setdefault("severity", record.levelname)
# replace any exception tuples returned by `sys.exc_info()`
# with a JSON-serializable `dict`.
if record.exc_info:
record_dict["e... | record_dict = record.__dict__.copy()
# GCP severity detection compatibility
record_dict.setdefault("severity", record.levelname)
# replace any exception tuples returned by `sys.exc_info()`
# with a JSON-serializable `dict`.
if record.exc_info:
record_dict["e... | 47 | 220 | 185 | 405 | import logging.handlers
import sys
import traceback
from types import TracebackType
from typing import Optional, Tuple, Type, Union
import orjson
from prefect.serializers import JSONSerializer
ExceptionInfoType = Union[
Tuple[Type[BaseException], BaseException, Optional[TracebackType]],
Tuple[None, None, Non... | import logging.handlers
import sys
import traceback
from types import TracebackType
from typing import Optional, Tuple, Type, Union
import orjson
from prefect.serializers import JSONSerializer
ExceptionInfoType = Union[
Tuple[Type[BaseException], BaseException, Optional[TracebackType]],
Tuple[None, None, Non... |
5,735 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/logging/formatters.py | 126,127 | 73,135 | formatMessage | PrefectFormatter | 127,135 | 127,135 | class PrefectFormatter(logging.Formatter):
def __init__(
self,
format=None,
datefmt=None,
style="%",
validate=True,
*,
defaults=None,
task_run_fmt: str = None,
flow_run_fmt: str = None,
) -> None:
"""
Implementation of the s... | class PrefectFormatter(logging.Formatter):
def __init__(
self,
format=None,
datefmt=None,
style="%",
validate=True,
*,
defaults=None,
task_run_fmt: str = None,
flow_run_fmt: str = None,
) -> None:
"""
Implementation of the s... | if record.name == "prefect.flow_runs":
style = self._flow_run_style
elif record.name == "prefect.task_runs":
style = self._task_run_style
else:
style = self._style
return style.format(record)
| if record.name == "prefect.flow_runs":
style = self._flow_run_style
elif record.name == "prefect.task_runs":
style = self._task_run_style
else:
style = self._style
return style.format(record)
| 20 | 537 | 83 | 620 | import logging.handlers
import sys
import traceback
from types import TracebackType
from typing import Optional, Tuple, Type, Union
import orjson
from prefect.serializers import JSONSerializer
ExceptionInfoType = Union[
Tuple[Type[BaseException], BaseException, Optional[TracebackType]],
Tuple[None, None, Non... | import logging.handlers
import sys
import traceback
from types import TracebackType
from typing import Optional, Tuple, Type, Union
import orjson
from prefect.serializers import JSONSerializer
ExceptionInfoType = Union[
Tuple[Type[BaseException], BaseException, Optional[TracebackType]],
Tuple[None, None, Non... |
5,737 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/logging/loggers.py | 358,359 | 303,361 | text | LogEavesdropper | 360,361 | 359,361 | class LogEavesdropper(logging.Handler):
"""A context manager that collects logs for the duration of the context
Example:
```python
import logging
from prefect.logging import LogEavesdropper
with LogEavesdropper("my_logger") as eavesdropper:
logging.getLogger("my_lo... | class LogEavesdropper(logging.Handler):
"""A context manager that collects logs for the duration of the context
Example:
```python
import logging
from prefect.logging import LogEavesdropper
with LogEavesdropper("my_logger") as eavesdropper:
logging.getLogger("my_lo... | return "\n".join(self._lines)
| """Return the collected logs as a single newline-delimited string"""
return "\n".join(self._lines)
| 2 | 585 | 13 | 598 | import io
import logging
import sys
import warnings
from builtins import print
from contextlib import contextmanager
from functools import lru_cache
from logging import LogRecord
from typing import TYPE_CHECKING, Dict, List, Optional, Union
from typing_extensions import Self
import prefect
from prefect.exceptions imp... | import io
import logging
import sys
import warnings
from builtins import print
from contextlib import contextmanager
from functools import lru_cache
from logging import LogRecord
from typing import TYPE_CHECKING, Dict, List, Optional, Union
from typing_extensions import Self
import prefect
from prefect.exceptions imp... |
5,738 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/logging/loggers.py | 56,59 | 25,71 | getChild | PrefectLogAdapter | 59,71 | 59,71 | class PrefectLogAdapter(logging.LoggerAdapter):
"""
Adapter that ensures extra kwargs are passed through correctly; without this
the `extra` fields set on the adapter would overshadow any provided on a
log-by-log basis.
See https://bugs.python.org/issue32732 — the Python team has declared that this... | class PrefectLogAdapter(logging.LoggerAdapter):
"""
Adapter that ensures extra kwargs are passed through correctly; without this
the `extra` fields set on the adapter would overshadow any provided on a
log-by-log basis.
See https://bugs.python.org/issue32732 — the Python team has declared that this... | if extra is None:
extra = {}
return PrefectLogAdapter(
self.logger.getChild(suffix),
extra={
**self.extra,
**extra,
},
)
| if extra is None:
extra = {}
return PrefectLogAdapter(
self.logger.getChild(suffix),
extra={
**self.extra,
**extra,
},
)
| 15 | 353 | 70 | 423 | import io
import logging
import sys
import warnings
from builtins import print
from contextlib import contextmanager
from functools import lru_cache
from logging import LogRecord
from typing import TYPE_CHECKING, Dict, List, Optional, Union
from typing_extensions import Self
import prefect
from prefect.exceptions imp... | import io
import logging
import sys
import warnings
from builtins import print
from contextlib import contextmanager
from functools import lru_cache
from logging import LogRecord
from typing import TYPE_CHECKING, Dict, List, Optional, Union
from typing_extensions import Self
import prefect
from prefect.exceptions imp... |
5,739 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/plugins.py | 41,42 | 1,127 | load_extra_entrypoints | 42,103 | 42,103 | """
Utilities for loading plugins that extend Prefect's functionality.
Plugins are detected by entry point definitions in package setup files.
Currently supported entrypoints:
- prefect.collections: Identifies this package as a Prefect collection that
should be imported when Prefect is imported.
"""
impor... | """
Utilities for loading plugins that extend Prefect's functionality.
Plugins are detected by entry point definitions in package setup files.
Currently supported entrypoints:
- prefect.collections: Identifies this package as a Prefect collection that
should be imported when Prefect is imported.
"""
impor... | # Note: Return values are only exposed for testing.
results = {}
if not prefect.settings.PREFECT_EXTRA_ENTRYPOINTS.value():
return results
values = {
value.strip()
for value in prefect.settings.PREFECT_EXTRA_ENTRYPOINTS.value().split(",")
}
entrypoints = []
for val... | # Note: Return values are only exposed for testing.
results = {}
if not prefect.settings.PREFECT_EXTRA_ENTRYPOINTS.value():
return results
values = {
value.strip()
for value in prefect.settings.PREFECT_EXTRA_ENTRYPOINTS.value().split(",")
}
entrypoints = []
for val... | 133 | 606 | 537 | 1,143 | """
Utilities for loading plugins that extend Prefect's functionality.
Plugins are detected by entry point definitions in package setup files.
Currently supported entrypoints:
- prefect.collections: Identifies this package as a Prefect collection that
should be imported when Prefect is imported.
"""
impor... | """
Utilities for loading plugins that extend Prefect's functionality.
Plugins are detected by entry point definitions in package setup files.
Currently supported entrypoints:
- prefect.collections: Identifies this package as a Prefect collection that
should be imported when Prefect is imported.
"""
impor... | |
5,740 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/pydantic/main.py | 20,21 | 19,28 | _reset_fields | PrefectBaseModel | 25,28 | 21,28 | class PrefectBaseModel(BaseModel):
def _reset_fields(self) -> typing.Set[str]:
FILL_FUNC_BODY | class PrefectBaseModel(BaseModel):
def _reset_fields(self) -> typing.Set[str]:
"""
A set of field names that are reset when the PrefectBaseModel is copied.
These fields are also disregarded for equality comparisons.
"""
FILL_FUNC_BODY | return set()
| """
A set of field names that are reset when the PrefectBaseModel is copied.
These fields are also disregarded for equality comparisons.
"""
return set()
| 2 | 77 | 10 | 87 | """
This file defines a `PrefectBaseModel` class that extends the `BaseModel` (imported from the internal compatibility layer).
"""
import typing
from prefect._internal.pydantic._compat import (
BaseModel,
ConfigDict,
Field,
FieldInfo,
PrivateAttr,
SecretStr,
ValidationError,
field_vali... | """
This file defines a `PrefectBaseModel` class that extends the `BaseModel` (imported from the internal compatibility layer).
"""
import typing
from prefect._internal.pydantic._compat import (
BaseModel,
ConfigDict,
Field,
FieldInfo,
PrivateAttr,
SecretStr,
ValidationError,
field_vali... |
5,742 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/runner/storage.py | 544,545 | 501,567 | to_pull_step | BlockStorageAdapter | 545,561 | 545,561 | class BlockStorageAdapter:
"""
A storage adapter for a storage block object to allow it to be used as a
runner storage object.
"""
def __init__(
self,
block: Union[ReadableDeploymentStorage, WritableDeploymentStorage],
pull_interval: Optional[int] = 60,
):
self._... | class BlockStorageAdapter:
"""
A storage adapter for a storage block object to allow it to be used as a
runner storage object.
"""
def __init__(
self,
block: Union[ReadableDeploymentStorage, WritableDeploymentStorage],
pull_interval: Optional[int] = 60,
):
self._... | # Give blocks the change to implement their own pull step
if hasattr(self._block, "get_pull_step"):
return self._block.get_pull_step()
else:
if not self._block._block_document_name:
raise BlockNotSavedError(
"Block must be saved with `.... | # Give blocks the change to implement their own pull step
if hasattr(self._block, "get_pull_step"):
return self._block.get_pull_step()
else:
if not self._block._block_document_name:
raise BlockNotSavedError(
"Block must be saved with `.... | 49 | 470 | 189 | 659 | import shutil
import subprocess
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Optional, Protocol, TypedDict, Union, runtime_checkable
from urllib.parse import urlparse, urlsplit, urlunparse
from uuid import uuid4
import fsspec
from anyio import run_process
from prefect._internal.con... | import shutil
import subprocess
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Optional, Protocol, TypedDict, Union, runtime_checkable
from urllib.parse import urlparse, urlsplit, urlunparse
from uuid import uuid4
import fsspec
from anyio import run_process
from prefect._internal.con... |
5,744 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/runner/storage.py | 460,461 | 310,501 | to_pull_step | RemoteStorage | 465,489 | 461,489 | class RemoteStorage:
"""
Pulls the contents of a remote storage location to the local filesystem.
Parameters:
url: The URL of the remote storage location to pull from. Supports
`fsspec` URLs. Some protocols may require an additional `fsspec`
dependency to be installed. Refer... | class RemoteStorage:
"""
Pulls the contents of a remote storage location to the local filesystem.
Parameters:
url: The URL of the remote storage location to pull from. Supports
`fsspec` URLs. Some protocols may require an additional `fsspec`
dependency to be installed. Refer... |
def replace_block_with_placeholder(obj: Any) -> Any:
if isinstance(obj, Block):
return f"{{{{ {obj.get_block_placeholder()} }}}}"
return obj
settings_with_placeholders = visit_collection(
self._settings, replace_block_with_placeholder, return_data=Tr... | """
Returns a dictionary representation of the storage object that can be
used as a deployment pull step.
"""
def replace_block_with_placeholder(obj: Any) -> Any:
if isinstance(obj, Block):
return f"{{{{ {obj.get_block_placeholder()} }}}}"
... | 45 | 1,485 | 245 | 1,730 | import shutil
import subprocess
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Optional, Protocol, TypedDict, Union, runtime_checkable
from urllib.parse import urlparse, urlsplit, urlunparse
from uuid import uuid4
import fsspec
from anyio import run_process
from prefect._internal.con... | import shutil
import subprocess
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Optional, Protocol, TypedDict, Union, runtime_checkable
from urllib.parse import urlparse, urlsplit, urlunparse
from uuid import uuid4
import fsspec
from anyio import run_process
from prefect._internal.con... |
5,745 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/runner/storage.py | 48,50 | 26,75 | destination | RunnerStorage | 53,55 | 50,55 | @runtime_checkable
class RunnerStorage(Protocol):
"""
A storage interface for a runner to use to retrieve
remotely stored flow code.
"""
def set_base_path(self, path: Path):
"""
Sets the base path to use when pulling contents from remote storage to
local storage.
"""... | @runtime_checkable
class RunnerStorage(Protocol):
"""
A storage interface for a runner to use to retrieve
remotely stored flow code.
"""
def set_base_path(self, path: Path):
"""
Sets the base path to use when pulling contents from remote storage to
local storage.
"""... | ...
| """
The local file path to pull contents from remote storage to.
"""
...
| 1 | 308 | 6 | 314 | import shutil
import subprocess
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Optional, Protocol, TypedDict, Union, runtime_checkable
from urllib.parse import urlparse, urlsplit, urlunparse
from uuid import uuid4
import fsspec
from anyio import run_process
from prefect._internal.con... | import shutil
import subprocess
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Optional, Protocol, TypedDict, Union, runtime_checkable
from urllib.parse import urlparse, urlsplit, urlunparse
from uuid import uuid4
import fsspec
from anyio import run_process
from prefect._internal.con... |
5,746 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/runner/utils.py | 31,34 | 1,93 | merge_definitions | 41,54 | 34,54 | from copy import deepcopy
from typing import Any, Dict
from prefect._vendor.fastapi import FastAPI
from prefect._vendor.fastapi.openapi.utils import get_openapi
from prefect import __version__ as PREFECT_VERSION
def inject_schemas_into_openapi(
webserver: FastAPI, schemas_to_inject: Dict[str, Any]
) -> Dict[str... | from copy import deepcopy
from typing import Any, Dict
from prefect._vendor.fastapi import FastAPI
from prefect._vendor.fastapi.openapi.utils import get_openapi
from prefect import __version__ as PREFECT_VERSION
def inject_schemas_into_openapi(
webserver: FastAPI, schemas_to_inject: Dict[str, Any]
) -> Dict[str... | openapi_schema_copy = deepcopy(openapi_schema)
components = openapi_schema_copy.setdefault("components", {}).setdefault(
"schemas", {}
)
for definitions in injected_schemas.values():
if "definitions" in definitions:
for def_name, def_schema in definitions["definitions"].items... | """
Integrates definitions from injected schemas into the OpenAPI components.
Args:
injected_schemas: A dictionary of deployment-specific schemas.
openapi_schema: The base OpenAPI schema to update.
"""
openapi_schema_copy = deepcopy(openapi_schema)
components = openapi_schema_co... | 33 | 842 | 164 | 1,006 | from copy import deepcopy
from typing import Any, Dict
from prefect._vendor.fastapi import FastAPI
from prefect._vendor.fastapi.openapi.utils import get_openapi
from prefect import __version__ as PREFECT_VERSION
def inject_schemas_into_openapi(
webserver: FastAPI, schemas_to_inject: Dict[str, Any]
) -> Dict[str... | from copy import deepcopy
from typing import Any, Dict
from prefect._vendor.fastapi import FastAPI
from prefect._vendor.fastapi.openapi.utils import get_openapi
from prefect import __version__ as PREFECT_VERSION
def inject_schemas_into_openapi(
webserver: FastAPI, schemas_to_inject: Dict[str, Any]
) -> Dict[str... | |
5,747 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/api/admin.py | 31,41 | 1,86 | clear_database | 42,52 | 41,52 | """
Routes for admin-level interactions with the Prefect REST API.
"""
from prefect._vendor.fastapi import Body, Depends, Response, status
import prefect
import prefect.settings
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInterface
... | """
Routes for admin-level interactions with the Prefect REST API.
"""
from prefect._vendor.fastapi import Body, Depends, Response, status
import prefect
import prefect.settings
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInterface
... | if not confirm:
response.status_code = status.HTTP_400_BAD_REQUEST
return
async with db.session_context(begin_transaction=True) as session:
# work pool has a circular dependency on pool queue; delete it first
await session.execute(db.WorkPool.__table__.delete())
for table... | """Clear all database tables without dropping them."""
if not confirm:
response.status_code = status.HTTP_400_BAD_REQUEST
return
async with db.session_context(begin_transaction=True) as session:
# work pool has a circular dependency on pool queue; delete it first
await sessio... | 33 | 660 | 123 | 783 | """
Routes for admin-level interactions with the Prefect REST API.
"""
from prefect._vendor.fastapi import Body, Depends, Response, status
import prefect
import prefect.settings
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInterface
... | """
Routes for admin-level interactions with the Prefect REST API.
"""
from prefect._vendor.fastapi import Body, Depends, Response, status
import prefect
import prefect.settings
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInterface
... | |
5,748 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/api/clients.py | 162,165 | 54,207 | read_workspace_variables | OrchestrationClient | 165,199 | 165,199 | class OrchestrationClient(BaseClient):
async def read_deployment_raw(self, deployment_id: UUID) -> Response:
return await self._http_client.get(f"/deployments/{deployment_id}")
async def read_deployment(
self, deployment_id: UUID
) -> Optional[DeploymentResponse]:
try:
r... | class OrchestrationClient(BaseClient):
async def read_deployment_raw(self, deployment_id: UUID) -> Response:
return await self._http_client.get(f"/deployments/{deployment_id}")
async def read_deployment(
self, deployment_id: UUID
) -> Optional[DeploymentResponse]:
try:
r... | variables: Dict[str, str] = {}
offset = 0
filter = VariableFilter()
if names is not None and not names:
return variables
elif names is not None:
filter.name = VariableFilterName(any_=list(set(names)))
for offset in range(
0, self.MA... | variables: Dict[str, str] = {}
offset = 0
filter = VariableFilter()
if names is not None and not names:
return variables
elif names is not None:
filter.name = VariableFilterName(any_=list(set(names)))
for offset in range(
0, self.MA... | 73 | 1,438 | 295 | 1,733 | from typing import Dict, List, Optional
from urllib.parse import quote
from uuid import UUID
import httpx
from httpx import Response
from prefect._vendor.starlette import status
from typing_extensions import Self
from prefect._internal.pydantic import HAS_PYDANTIC_V2
from prefect.exceptions import ObjectNotFound
from... | from typing import Dict, List, Optional
from urllib.parse import quote
from uuid import UUID
import httpx
from httpx import Response
from prefect._vendor.starlette import status
from typing_extensions import Self
from prefect._internal.pydantic import HAS_PYDANTIC_V2
from prefect.exceptions import ObjectNotFound
from... |
5,749 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/api/clients.py | 211,212 | 207,229 | read_work_pool | WorkPoolsOrchestrationClient | 220,229 | 212,229 | class WorkPoolsOrchestrationClient(BaseClient):
async def __aenter__(self) -> Self:
return self
async def read_work_pool(self, work_pool_name: str) -> WorkPool:
FILL_FUNC_BODY | class WorkPoolsOrchestrationClient(BaseClient):
async def __aenter__(self) -> Self:
return self
async def read_work_pool(self, work_pool_name: str) -> WorkPool:
"""
Reads information for a given work pool
Args:
work_pool_name: The name of the work pool to for which t... | try:
response = await self._http_client.get(f"/work_pools/{work_pool_name}")
response.raise_for_status()
return pydantic.parse_obj_as(WorkPool, response.json())
except httpx.HTTPStatusError as e:
if e.response.status_code == status.HTTP_404_NOT_FOUND:
... | """
Reads information for a given work pool
Args:
work_pool_name: The name of the work pool to for which to get
information.
Returns:
Information about the requested work pool.
"""
try:
response = await self._http_client... | 23 | 125 | 127 | 252 | from typing import Dict, List, Optional
from urllib.parse import quote
from uuid import UUID
import httpx
from httpx import Response
from prefect._vendor.starlette import status
from typing_extensions import Self
from prefect._internal.pydantic import HAS_PYDANTIC_V2
from prefect.exceptions import ObjectNotFound
from... | from typing import Dict, List, Optional
from urllib.parse import quote
from uuid import UUID
import httpx
from httpx import Response
from prefect._vendor.starlette import status
from typing_extensions import Self
from prefect._internal.pydantic import HAS_PYDANTIC_V2
from prefect.exceptions import ObjectNotFound
from... |
5,750 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/api/collections.py | 26,28 | 1,68 | read_view_content | 29,46 | 28,46 | import json
from typing import Any, Dict
import httpx
from anyio import Path
from cachetools import TTLCache
from prefect._vendor.fastapi import HTTPException, status
from prefect.server.utilities.server import PrefectRouter
router = PrefectRouter(prefix="/collections", tags=["Collections"])
GLOBAL_COLLECTIONS_VIEW... | import json
from typing import Any, Dict
import httpx
from anyio import Path
from cachetools import TTLCache
from prefect._vendor.fastapi import HTTPException, status
from prefect.server.utilities.server import PrefectRouter
router = PrefectRouter(prefix="/collections", tags=["Collections"])
GLOBAL_COLLECTIONS_VIEW... | try:
return await get_collection_view(view)
except KeyError:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"View {view} not found in registry",
)
except httpx.HTTPStatusError as exc:
if exc.response.status_code == 404:
... | """Reads the content of a view from the prefect-collection-registry."""
try:
return await get_collection_view(view)
except KeyError:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"View {view} not found in registry",
)
except httpx.HTT... | 36 | 604 | 162 | 766 | import json
from typing import Any, Dict
import httpx
from anyio import Path
from cachetools import TTLCache
from prefect._vendor.fastapi import HTTPException, status
from prefect.server.utilities.server import PrefectRouter
router = PrefectRouter(prefix="/collections", tags=["Collections"])
GLOBAL_COLLECTIONS_VIEW... | import json
from typing import Any, Dict
import httpx
from anyio import Path
from cachetools import TTLCache
from prefect._vendor.fastapi import HTTPException, status
from prefect.server.utilities.server import PrefectRouter
router = PrefectRouter(prefix="/collections", tags=["Collections"])
GLOBAL_COLLECTIONS_VIEW... | |
5,751 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/api/dependencies.py | 98,99 | 1,170 | LimitBody | 103,127 | 99,127 | """
Utilities for injecting FastAPI dependencies.
"""
import logging
from base64 import b64decode
from typing import Optional
from uuid import UUID
from packaging.version import Version
from prefect._vendor.fastapi import Body, Depends, Header, HTTPException, status
from prefect._vendor.starlette.requests import Requ... | """
Utilities for injecting FastAPI dependencies.
"""
import logging
from base64 import b64decode
from typing import Optional
from uuid import UUID
from packaging.version import Version
from prefect._vendor.fastapi import Body, Depends, Header, HTTPException, status
from prefect._vendor.starlette.requests import Requ... |
def get_limit(
limit: int = Body(
None,
description="Defaults to PREFECT_API_DEFAULT_LIMIT if not provided.",
),
):
default_limit = PREFECT_API_DEFAULT_LIMIT.value()
limit = limit if limit is not None else default_limit
if not limit >= 0:
... | """
A `fastapi.Depends` factory for pulling a `limit: int` parameter from the
request body while determining the default from the current settings.
"""
def get_limit(
limit: int = Body(
None,
description="Defaults to PREFECT_API_DEFAULT_LIMIT if not provided.",
... | 69 | 1,463 | 241 | 1,704 | """
Utilities for injecting FastAPI dependencies.
"""
import logging
from base64 import b64decode
from typing import Optional
from uuid import UUID
from packaging.version import Version
from prefect._vendor.fastapi import Body, Depends, Header, HTTPException, status
from prefect._vendor.starlette.requests import Requ... | """
Utilities for injecting FastAPI dependencies.
"""
import logging
from base64 import b64decode
from typing import Optional
from uuid import UUID
from packaging.version import Version
from prefect._vendor.fastapi import Body, Depends, Header, HTTPException, status
from prefect._vendor.starlette.requests import Requ... | |
5,752 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/api/dependencies.py | 91,92 | 36,98 | _notify_of_outdated_version | EnforceMinimumAPIVersion | 92,98 | 92,98 | class EnforceMinimumAPIVersion:
"""
FastAPI Dependency used to check compatibility between the version of the api
and a given request.
Looks for the header 'X-PREFECT-API-VERSION' in the request and compares it
to the api's version. Rejects requests that are lower than the minimum version.
"""
... | class EnforceMinimumAPIVersion:
"""
FastAPI Dependency used to check compatibility between the version of the api
and a given request.
Looks for the header 'X-PREFECT-API-VERSION' in the request and compares it
to the api's version. Rejects requests that are lower than the minimum version.
"""
... | self.logger.error(
f"X-PREFECT-API-VERSION header specifies version '{request_version}' "
f"but minimum allowed version is '{self.minimum_api_version}'"
)
| self.logger.error(
f"X-PREFECT-API-VERSION header specifies version '{request_version}' "
f"but minimum allowed version is '{self.minimum_api_version}'"
)
| 14 | 606 | 62 | 668 | """
Utilities for injecting FastAPI dependencies.
"""
import logging
from base64 import b64decode
from typing import Optional
from uuid import UUID
from packaging.version import Version
from prefect._vendor.fastapi import Body, Depends, Header, HTTPException, status
from prefect._vendor.starlette.requests import Requ... | """
Utilities for injecting FastAPI dependencies.
"""
import logging
from base64 import b64decode
from typing import Optional
from uuid import UUID
from packaging.version import Version
from prefect._vendor.fastapi import Body, Depends, Header, HTTPException, status
from prefect._vendor.starlette.requests import Requ... |
5,753 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/api/root.py | 20,24 | 1,36 | perform_readiness_check | 24,36 | 24,36 | """
Contains the `hello` route for testing and healthcheck purposes.
"""
from prefect._vendor.fastapi import Depends, status
from prefect._vendor.fastapi.responses import JSONResponse
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInte... | """
Contains the `hello` route for testing and healthcheck purposes.
"""
from prefect._vendor.fastapi import Depends, status
from prefect._vendor.fastapi.responses import JSONResponse
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInte... | is_db_connectable = await db.is_db_connectable()
if is_db_connectable:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"message": "OK"},
)
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={"message": "Databa... | is_db_connectable = await db.is_db_connectable()
if is_db_connectable:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"message": "OK"},
)
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={"message": "Databa... | 21 | 196 | 123 | 319 | """
Contains the `hello` route for testing and healthcheck purposes.
"""
from prefect._vendor.fastapi import Depends, status
from prefect._vendor.fastapi.responses import JSONResponse
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInte... | """
Contains the `hello` route for testing and healthcheck purposes.
"""
from prefect._vendor.fastapi import Depends, status
from prefect._vendor.fastapi.responses import JSONResponse
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInte... | |
5,754 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/api/templates.py | 14,19 | 1,36 | validate_template | 19,36 | 19,36 | import orjson
from jinja2.exceptions import TemplateSyntaxError
from prefect._vendor.fastapi import Body, Response
from prefect.server.utilities.server import PrefectRouter
from prefect.server.utilities.user_templates import (
TemplateSecurityError,
validate_user_template,
)
router = PrefectRouter(prefix="/te... | import orjson
from jinja2.exceptions import TemplateSyntaxError
from prefect._vendor.fastapi import Body, Response
from prefect.server.utilities.server import PrefectRouter
from prefect.server.utilities.user_templates import (
TemplateSecurityError,
validate_user_template,
)
router = PrefectRouter(prefix="/te... | try:
validate_user_template(template)
return Response(content="", status_code=204)
except (TemplateSyntaxError, TemplateSecurityError) as e:
return Response(
status_code=422,
media_type="application/json",
content=orjson.dumps(
{
... | try:
validate_user_template(template)
return Response(content="", status_code=204)
except (TemplateSyntaxError, TemplateSecurityError) as e:
return Response(
status_code=422,
media_type="application/json",
content=orjson.dumps(
{
... | 28 | 155 | 146 | 301 | import orjson
from jinja2.exceptions import TemplateSyntaxError
from prefect._vendor.fastapi import Body, Response
from prefect.server.utilities.server import PrefectRouter
from prefect.server.utilities.user_templates import (
TemplateSecurityError,
validate_user_template,
)
router = PrefectRouter(prefix="/te... | import orjson
from jinja2.exceptions import TemplateSyntaxError
from prefect._vendor.fastapi import Body, Response
from prefect.server.utilities.server import PrefectRouter
from prefect.server.utilities.user_templates import (
TemplateSecurityError,
validate_user_template,
)
router = PrefectRouter(prefix="/te... | |
5,755 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/api/ui/schemas.py | 23,29 | 1,52 | validate_obj | 29,52 | 29,52 | from typing import Any, Dict
from prefect._vendor.fastapi import Body, Depends, HTTPException, status
from prefect.logging import get_logger
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInterface
from prefect.server.utilities.server... | from typing import Any, Dict
from prefect._vendor.fastapi import Body, Depends, HTTPException, status
from prefect.logging import get_logger
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInterface
from prefect.server.utilities.server... | schema = preprocess_schema(schema)
try:
is_valid_schema(schema, preprocess=False)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
)
async with db.session_context() as session:
ctx = await Hydra... | schema = preprocess_schema(schema)
try:
is_valid_schema(schema, preprocess=False)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
)
async with db.session_context() as session:
ctx = await Hydra... | 54 | 286 | 242 | 528 | from typing import Any, Dict
from prefect._vendor.fastapi import Body, Depends, HTTPException, status
from prefect.logging import get_logger
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInterface
from prefect.server.utilities.server... | from typing import Any, Dict
from prefect._vendor.fastapi import Body, Depends, HTTPException, status
from prefect.logging import get_logger
from prefect.server.database.dependencies import provide_database_interface
from prefect.server.database.interface import PrefectDBInterface
from prefect.server.utilities.server... | |
5,756 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/alembic_commands.py | 71,73 | 1,100 | alembic_revision | 80,88 | 73,88 | from functools import wraps
from pathlib import Path
from threading import Lock
import prefect.server
ALEMBIC_LOCK = Lock()
def with_alembic_lock(fn):
"""
Decorator that prevents alembic commands from running concurrently.
This is necessary because alembic uses a global configuration object
that is ... | from functools import wraps
from pathlib import Path
from threading import Lock
import prefect.server
ALEMBIC_LOCK = Lock()
def with_alembic_lock(fn):
"""
Decorator that prevents alembic commands from running concurrently.
This is necessary because alembic uses a global configuration object
that is ... | # lazy import for performance
import alembic.command
alembic.command.revision(
alembic_config(), message=message, autogenerate=autogenerate, **kwargs
)
| """
Create a new revision file for the database.
Args:
message: string message to apply to the revision.
autogenerate: whether or not to autogenerate the script from the database.
"""
# lazy import for performance
import alembic.command
alembic.command.revision(
ale... | 13 | 861 | 64 | 925 | from functools import wraps
from pathlib import Path
from threading import Lock
import prefect.server
ALEMBIC_LOCK = Lock()
def with_alembic_lock(fn):
"""
Decorator that prevents alembic commands from running concurrently.
This is necessary because alembic uses a global configuration object
that is ... | from functools import wraps
from pathlib import Path
from threading import Lock
import prefect.server
ALEMBIC_LOCK = Lock()
def with_alembic_lock(fn):
"""
Decorator that prevents alembic commands from running concurrently.
This is necessary because alembic uses a global configuration object
that is ... | |
5,758 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/configurations.py | 172,173 | 171,295 | engine | AsyncPostgresConfiguration | 186,237 | 173,237 | class AsyncPostgresConfiguration(BaseDatabaseConfiguration):
async def engine(self) -> AsyncEngine:
FILL_FUNC_BODY async def schedule_engine_disposal(self, cache_key):
"""
Dispose of an engine once the event loop is closing.
See caveats at `add_event_loop_shutdown_callback`.
We ... | class AsyncPostgresConfiguration(BaseDatabaseConfiguration):
async def engine(self) -> AsyncEngine:
"""Retrieves an async SQLAlchemy engine.
Args:
connection_url (str, optional): The database connection string.
Defaults to self.connection_url
echo (bool, opti... |
loop = get_running_loop()
cache_key = (
loop,
self.connection_url,
self.echo,
self.timeout,
)
if cache_key not in ENGINES:
# apply database timeout
kwargs = dict()
connect_args = dict()
if ... | """Retrieves an async SQLAlchemy engine.
Args:
connection_url (str, optional): The database connection string.
Defaults to self.connection_url
echo (bool, optional): Whether to echo SQL sent
to the database. Defaults to self.echo
timeo... | 136 | 687 | 501 | 1,188 | import sqlite3
import traceback
from abc import ABC, abstractmethod
from asyncio import AbstractEventLoop, get_running_loop
from contextlib import asynccontextmanager
from contextvars import ContextVar
from functools import partial
from typing import Dict, Hashable, Optional, Tuple
import sqlalchemy as sa
try:
fr... | import sqlite3
import traceback
from abc import ABC, abstractmethod
from asyncio import AbstractEventLoop, get_running_loop
from contextlib import asynccontextmanager
from contextvars import ContextVar
from functools import partial
from typing import Dict, Hashable, Optional, Tuple
import sqlalchemy as sa
try:
fr... |
5,759 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/configurations.py | 135,136 | 105,171 | _unique_key | BaseDatabaseConfiguration | 139,141 | 136,141 | class BaseDatabaseConfiguration(ABC):
"""
Abstract base class used to inject database connection configuration into Prefect.
This configuration is responsible for defining how Prefect REST API creates and manages
database connections and sessions.
"""
def __init__(
self,
connec... | class BaseDatabaseConfiguration(ABC):
"""
Abstract base class used to inject database connection configuration into Prefect.
This configuration is responsible for defining how Prefect REST API creates and manages
database connections and sessions.
"""
def __init__(
self,
connec... | return (self.__class__, self.connection_url)
| """
Returns a key used to determine whether to instantiate a new DB interface.
"""
return (self.__class__, self.connection_url)
| 3 | 601 | 18 | 619 | import sqlite3
import traceback
from abc import ABC, abstractmethod
from asyncio import AbstractEventLoop, get_running_loop
from contextlib import asynccontextmanager
from contextvars import ContextVar
from functools import partial
from typing import Dict, Hashable, Optional, Tuple
import sqlalchemy as sa
try:
fr... | import sqlite3
import traceback
from abc import ABC, abstractmethod
from asyncio import AbstractEventLoop, get_running_loop
from contextlib import asynccontextmanager
from contextvars import ContextVar
from functools import partial
from typing import Dict, Hashable, Optional, Tuple
import sqlalchemy as sa
try:
fr... |
5,760 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/configurations.py | 84,88 | 40,102 | on_close_detached | ConnectionTracker | 88,94 | 88,94 | class ConnectionTracker:
"""A test utility which tracks the connections given out by a connection pool, to
make it easy to see which connections are currently checked out and open."""
all_connections: Dict[AdaptedConnection, str]
open_connections: Dict[AdaptedConnection, str]
left_field_closes: Dic... | class ConnectionTracker:
"""A test utility which tracks the connections given out by a connection pool, to
make it easy to see which connections are currently checked out and open."""
all_connections: Dict[AdaptedConnection, str]
open_connections: Dict[AdaptedConnection, str]
left_field_closes: Dic... | try:
del self.open_connections[adapted_connection]
except KeyError:
self.left_field_closes[adapted_connection] = traceback.format_stack()
self.closes += 1
| try:
del self.open_connections[adapted_connection]
except KeyError:
self.left_field_closes[adapted_connection] = traceback.format_stack()
self.closes += 1
| 11 | 542 | 64 | 606 | import sqlite3
import traceback
from abc import ABC, abstractmethod
from asyncio import AbstractEventLoop, get_running_loop
from contextlib import asynccontextmanager
from contextvars import ContextVar
from functools import partial
from typing import Dict, Hashable, Optional, Tuple
import sqlalchemy as sa
try:
fr... | import sqlite3
import traceback
from abc import ABC, abstractmethod
from asyncio import AbstractEventLoop, get_running_loop
from contextlib import asynccontextmanager
from contextvars import ContextVar
from functools import partial
from typing import Dict, Hashable, Optional, Tuple
import sqlalchemy as sa
try:
fr... |
5,763 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/migrations/versions/postgresql/2022_02_19_205543_d9d98a9ebb6f_rename_block_data_table.py | 17,18 | 1,33 | upgrade | 18,26 | 18,26 | """Rename block data table
Revision ID: d9d98a9ebb6f
Revises:
Create Date: 2022-02-19 20:55:43.397189
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "d9d98a9ebb6f"
down_revision = "679e695af6ba"
branch_labels = None
depends_on = None
def upgrade():
FILL_FUNC_BODYdef downgrade():
... | """Rename block data table
Revision ID: d9d98a9ebb6f
Revises:
Create Date: 2022-02-19 20:55:43.397189
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "d9d98a9ebb6f"
down_revision = "679e695af6ba"
branch_labels = None
depends_on = None
def upgrade():
FILL_FUNC_BODYdef downgrade():
... | op.execute(
"""
ALTER TABLE block_data
RENAME TO block;
"""
)
| op.execute(
"""
ALTER TABLE block_data
RENAME TO block;
"""
)
| 10 | 184 | 41 | 225 | """Rename block data table
Revision ID: d9d98a9ebb6f
Revises:
Create Date: 2022-02-19 20:55:43.397189
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "d9d98a9ebb6f"
down_revision = "679e695af6ba"
branch_labels = None
depends_on = None
def upgrade():
FILL_FUNC_BODYdef downgrade():
... | """Rename block data table
Revision ID: d9d98a9ebb6f
Revises:
Create Date: 2022-02-19 20:55:43.397189
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "d9d98a9ebb6f"
down_revision = "679e695af6ba"
branch_labels = None
depends_on = None
def upgrade():
FILL_FUNC_BODYdef downgrade():
... | |
5,764 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/migrations/versions/postgresql/2022_02_21_111050_d115556a8ab6_index_flowrun_flow_runner_type.py | 26,27 | 1,28 | downgrade | 27,28 | 27,28 | """Index FlowRun.flow_runner_type
Revision ID: d115556a8ab6
Revises: 4799f657a6a1
Create Date: 2022-02-21 11:10:50.989062
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "d115556a8ab6"
down_revision = "4799f657a6a1"
branch_labels = None
depends_on = None
def upgrade():
op.create_... | """Index FlowRun.flow_runner_type
Revision ID: d115556a8ab6
Revises: 4799f657a6a1
Create Date: 2022-02-21 11:10:50.989062
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "d115556a8ab6"
down_revision = "4799f657a6a1"
branch_labels = None
depends_on = None
def upgrade():
op.create_... | op.drop_index(op.f("ix_flow_run__flow_runner_type"), table_name="flow_run")
| op.drop_index(op.f("ix_flow_run__flow_runner_type"), table_name="flow_run")
| 2 | 224 | 34 | 258 | """Index FlowRun.flow_runner_type
Revision ID: d115556a8ab6
Revises: 4799f657a6a1
Create Date: 2022-02-21 11:10:50.989062
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "d115556a8ab6"
down_revision = "4799f657a6a1"
branch_labels = None
depends_on = None
def upgrade():
op.create_... | """Index FlowRun.flow_runner_type
Revision ID: d115556a8ab6
Revises: 4799f657a6a1
Create Date: 2022-02-21 11:10:50.989062
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "d115556a8ab6"
down_revision = "4799f657a6a1"
branch_labels = None
depends_on = None
def upgrade():
op.create_... | |
5,765 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/migrations/versions/postgresql/2022_03_10_102713_2e7e1428ffce_index_flow_created.py | 17,18 | 1,25 | upgrade | 18,22 | 18,22 | """Index Flow.created
Revision ID: 2e7e1428ffce
Revises: b68b3cad6b8a
Create Date: 2022-03-10 10:27:13.015390
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "2e7e1428ffce"
down_revision = "b68b3cad6b8a"
branch_labels = None
depends_on = None
def upgrade():
FILL_FUNC_BODYdef downgrad... | """Index Flow.created
Revision ID: 2e7e1428ffce
Revises: b68b3cad6b8a
Create Date: 2022-03-10 10:27:13.015390
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "2e7e1428ffce"
down_revision = "b68b3cad6b8a"
branch_labels = None
depends_on = None
def upgrade():
FILL_FUNC_BODYdef downgrad... | with op.batch_alter_table("flow", schema=None) as batch_op:
batch_op.create_index("ix_flow__created", ["created"], unique=False)
| with op.batch_alter_table("flow", schema=None) as batch_op:
batch_op.create_index("ix_flow__created", ["created"], unique=False)
| 8 | 198 | 51 | 249 | """Index Flow.created
Revision ID: 2e7e1428ffce
Revises: b68b3cad6b8a
Create Date: 2022-03-10 10:27:13.015390
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "2e7e1428ffce"
down_revision = "b68b3cad6b8a"
branch_labels = None
depends_on = None
def upgrade():
FILL_FUNC_BODYdef downgrad... | """Index Flow.created
Revision ID: 2e7e1428ffce
Revises: b68b3cad6b8a
Create Date: 2022-03-10 10:27:13.015390
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "2e7e1428ffce"
down_revision = "b68b3cad6b8a"
branch_labels = None
depends_on = None
def upgrade():
FILL_FUNC_BODYdef downgrad... | |
5,766 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/migrations/versions/postgresql/2022_04_20_113011_605ebb4e9155_add_flow_run_state_name.py | 18,19 | 1,45 | upgrade | 19,39 | 19,39 | """Add flow_run.state_name
Revision ID: 605ebb4e9155
Revises: 2e7e1428ffce
Create Date: 2022-04-20 11:30:11.934795
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "605ebb4e9155"
down_revision = "2e7e1428ffce"
branch_labels = None
depends_on = None
def upgrade(... | """Add flow_run.state_name
Revision ID: 605ebb4e9155
Revises: 2e7e1428ffce
Create Date: 2022-04-20 11:30:11.934795
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "605ebb4e9155"
down_revision = "2e7e1428ffce"
branch_labels = None
depends_on = None
def upgrade(... | op.add_column("flow_run", sa.Column("state_name", sa.String(), nullable=True))
op.add_column("task_run", sa.Column("state_name", sa.String(), nullable=True))
with op.get_context().autocommit_block():
op.execute(
"""
CREATE INDEX CONCURRENTLY IF NOT EXISTS
ix_flow... | op.add_column("flow_run", sa.Column("state_name", sa.String(), nullable=True))
op.add_column("task_run", sa.Column("state_name", sa.String(), nullable=True))
with op.get_context().autocommit_block():
op.execute(
"""
CREATE INDEX CONCURRENTLY IF NOT EXISTS
ix_flow... | 36 | 278 | 198 | 476 | """Add flow_run.state_name
Revision ID: 605ebb4e9155
Revises: 2e7e1428ffce
Create Date: 2022-04-20 11:30:11.934795
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "605ebb4e9155"
down_revision = "2e7e1428ffce"
branch_labels = None
depends_on = None
def upgrade(... | """Add flow_run.state_name
Revision ID: 605ebb4e9155
Revises: 2e7e1428ffce
Create Date: 2022-04-20 11:30:11.934795
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "605ebb4e9155"
down_revision = "2e7e1428ffce"
branch_labels = None
depends_on = None
def upgrade(... | |
5,767 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/migrations/versions/postgresql/2022_04_21_095519_14dc68cc5853_backfill_state_name.py | 18,19 | 1,65 | upgrade | 25,61 | 19,61 | """Backfill state_name
Revision ID: 14dc68cc5853
Revises: 605ebb4e9155
Create Date: 2022-04-21 09:55:19.820177
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "14dc68cc5853"
down_revision = "605ebb4e9155"
branch_labels = None
depends_on = None
def upgrade():
F... | """Backfill state_name
Revision ID: 14dc68cc5853
Revises: 605ebb4e9155
Create Date: 2022-04-21 09:55:19.820177
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "14dc68cc5853"
down_revision = "605ebb4e9155"
branch_labels = None
depends_on = None
def upgrade():
... |
update_flow_run_state_name_in_batches = """
WITH null_flow_run_state_name_cte as (SELECT id from flow_run where state_name is null and state_id is not null limit 500)
UPDATE flow_run
SET state_name = flow_run_state.name
FROM flow_run_state, null_flow_run_state_name_cte
WHERE... | """
Backfills state_name column for task_run and flow_run tables.
This is a data only migration that can be run as many
times as desired.
"""
update_flow_run_state_name_in_batches = """
WITH null_flow_run_state_name_cte as (SELECT id from flow_run where state_name is null and state_id ... | 143 | 236 | 511 | 747 | """Backfill state_name
Revision ID: 14dc68cc5853
Revises: 605ebb4e9155
Create Date: 2022-04-21 09:55:19.820177
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "14dc68cc5853"
down_revision = "605ebb4e9155"
branch_labels = None
depends_on = None
def upgrade():
F... | """Backfill state_name
Revision ID: 14dc68cc5853
Revises: 605ebb4e9155
Create Date: 2022-04-21 09:55:19.820177
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "14dc68cc5853"
down_revision = "605ebb4e9155"
branch_labels = None
depends_on = None
def upgrade():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.