code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
from __future__ import annotations
from typing import Any, Optional, Union, cast
from typing_extensions import Annotated, get_args, get_origin
from strawberry.type import StrawberryType
from .annotation import StrawberryAnnotation
class StrawberryAutoMeta(type):
"""Metaclass for StrawberryAuto.
This is used to make sure StrawberryAuto is a singleton and also to
override the behavior of `isinstance` so that it consider the following
cases:
>> isinstance(StrawberryAuto(), StrawberryAuto)
True
>> isinstance(StrawberryAnnotation(StrawberryAuto()), StrawberryAuto)
True
>> isinstance(Annotated[StrawberryAuto(), object()), StrawberryAuto)
True
"""
def __init__(self, *args, **kwargs):
self._instance: Optional[StrawberryAuto] = None
super().__init__(*args, **kwargs)
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
def __instancecheck__(
self,
instance: Union[StrawberryAuto, StrawberryAnnotation, StrawberryType, type],
):
if isinstance(instance, StrawberryAnnotation):
resolved = instance.annotation
if isinstance(resolved, str):
namespace = instance.namespace
resolved = namespace and namespace.get(resolved)
if resolved is not None:
instance = cast(type, resolved)
if instance is auto:
return True
# Support uses of Annotated[auto, something()]
if get_origin(instance) is Annotated:
args = get_args(instance)
if args[0] is Any:
return any(isinstance(arg, StrawberryAuto) for arg in args[1:])
# StrawberryType's `__eq__` tries to find the string passed in the global
# namespace, which will fail with a `NameError` if "strawberry.auto" hasn't
# been imported. So we can't use `instance == "strawberry.auto"` here.
# Instead, we'll use `isinstance(instance, str)` to check if the instance
# is a StrawberryType, in that case we can return False since we know it
# won't be a StrawberryAuto.
if isinstance(instance, StrawberryType):
return False
return instance == "strawberry.auto"
class StrawberryAuto(metaclass=StrawberryAutoMeta):
def __str__(self):
return "auto"
def __repr__(self):
return "<auto>"
auto = Annotated[Any, StrawberryAuto()]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/auto.py | auto.py |
import dataclasses
import inspect
import sys
import types
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Sequence,
Type,
TypeVar,
Union,
cast,
overload,
)
from .exceptions import (
MissingFieldAnnotationError,
MissingReturnAnnotationError,
ObjectIsNotClassError,
)
from .field import StrawberryField, field
from .types.type_resolver import _get_fields
from .types.types import TypeDefinition
from .utils.dataclasses import add_custom_init_fn
from .utils.str_converters import to_camel_case
from .utils.typing import __dataclass_transform__
T = TypeVar("T", bound=Type)
def _get_interfaces(cls: Type[Any]) -> List[TypeDefinition]:
interfaces: List[TypeDefinition] = []
for base in cls.__mro__[1:]: # Exclude current class
type_definition = cast(
Optional[TypeDefinition], getattr(base, "_type_definition", None)
)
if type_definition and type_definition.is_interface:
interfaces.append(type_definition)
return interfaces
def _check_field_annotations(cls: Type[Any]):
"""Are any of the dataclass Fields missing type annotations?
This is similar to the check that dataclasses do during creation, but allows us to
manually add fields to cls' __annotations__ or raise proper Strawberry exceptions if
necessary
https://github.com/python/cpython/blob/6fed3c85402c5ca704eb3f3189ca3f5c67a08d19/Lib/dataclasses.py#L881-L884
"""
cls_annotations = cls.__dict__.get("__annotations__", {})
cls.__annotations__ = cls_annotations
for field_name, field_ in cls.__dict__.items():
if not isinstance(field_, (StrawberryField, dataclasses.Field)):
# Not a dataclasses.Field, nor a StrawberryField. Ignore
continue
# If the field is a StrawberryField we need to do a bit of extra work
# to make sure dataclasses.dataclass is ready for it
if isinstance(field_, StrawberryField):
# If the field has a type override then use that instead of using
# the class annotations or resolver annotation
if field_.type_annotation is not None:
cls_annotations[field_name] = field_.type_annotation.annotation
continue
# Make sure the cls has an annotation
if field_name not in cls_annotations:
# If the field uses the default resolver, the field _must_ be
# annotated
if not field_.base_resolver:
raise MissingFieldAnnotationError(field_name, cls)
# The resolver _must_ have a return type annotation
# TODO: Maybe check this immediately when adding resolver to
# field
if field_.base_resolver.type_annotation is None:
raise MissingReturnAnnotationError(
field_name, resolver=field_.base_resolver
)
cls_annotations[field_name] = field_.base_resolver.type_annotation
# TODO: Make sure the cls annotation agrees with the field's type
# >>> if cls_annotations[field_name] != field.base_resolver.type:
# >>> # TODO: Proper error
# >>> raise Exception
# If somehow a non-StrawberryField field is added to the cls without annotations
# it raises an exception. This would occur if someone manually uses
# dataclasses.field
if field_name not in cls_annotations:
# Field object exists but did not get an annotation
raise MissingFieldAnnotationError(field_name, cls)
def _wrap_dataclass(cls: Type[Any]):
"""Wrap a strawberry.type class with a dataclass and check for any issues
before doing so"""
# Ensure all Fields have been properly type-annotated
_check_field_annotations(cls)
dclass_kwargs: Dict[str, bool] = {}
# Python 3.10 introduces the kw_only param. If we're on an older version
# then generate our own custom init function
if sys.version_info >= (3, 10):
dclass_kwargs["kw_only"] = True
else:
dclass_kwargs["init"] = False
dclass = dataclasses.dataclass(cls, **dclass_kwargs)
if sys.version_info < (3, 10):
add_custom_init_fn(dclass)
return dclass
def _process_type(
cls,
*,
name: Optional[str] = None,
is_input: bool = False,
is_interface: bool = False,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
extend: bool = False,
):
name = name or to_camel_case(cls.__name__)
interfaces = _get_interfaces(cls)
fields = _get_fields(cls)
is_type_of = getattr(cls, "is_type_of", None)
cls._type_definition = TypeDefinition(
name=name,
is_input=is_input,
is_interface=is_interface,
interfaces=interfaces,
description=description,
directives=directives,
origin=cls,
extend=extend,
_fields=fields,
is_type_of=is_type_of,
)
# dataclasses removes attributes from the class here:
# https://github.com/python/cpython/blob/577d7c4e/Lib/dataclasses.py#L873-L880
# so we need to restore them, this will change in future, but for now this
# solution should suffice
for field_ in fields:
if field_.base_resolver and field_.python_name:
wrapped_func = field_.base_resolver.wrapped_func
# Bind the functions to the class object. This is necessary because when
# the @strawberry.field decorator is used on @staticmethod/@classmethods,
# we get the raw staticmethod/classmethod objects before class evaluation
# binds them to the class. We need to do this manually.
if isinstance(wrapped_func, staticmethod):
bound_method = wrapped_func.__get__(cls)
field_.base_resolver.wrapped_func = bound_method
elif isinstance(wrapped_func, classmethod):
bound_method = types.MethodType(wrapped_func.__func__, cls)
field_.base_resolver.wrapped_func = bound_method
setattr(cls, field_.python_name, wrapped_func)
return cls
@overload
@__dataclass_transform__(
order_default=True, kw_only_default=True, field_descriptors=(field, StrawberryField)
)
def type(
cls: T,
*,
name: Optional[str] = None,
is_input: bool = False,
is_interface: bool = False,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
extend: bool = False,
) -> T:
...
@overload
@__dataclass_transform__(
order_default=True, kw_only_default=True, field_descriptors=(field, StrawberryField)
)
def type(
*,
name: Optional[str] = None,
is_input: bool = False,
is_interface: bool = False,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
extend: bool = False,
) -> Callable[[T], T]:
...
def type(
cls: Optional[T] = None,
*,
name: Optional[str] = None,
is_input: bool = False,
is_interface: bool = False,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
extend: bool = False,
) -> Union[T, Callable[[T], T]]:
"""Annotates a class as a GraphQL type.
Example usage:
>>> @strawberry.type:
>>> class X:
>>> field_abc: str = "ABC"
"""
def wrap(cls):
if not inspect.isclass(cls):
if is_input:
exc = ObjectIsNotClassError.input
elif is_interface:
exc = ObjectIsNotClassError.interface
else:
exc = ObjectIsNotClassError.type
raise exc(cls)
wrapped = _wrap_dataclass(cls)
return _process_type(
wrapped,
name=name,
is_input=is_input,
is_interface=is_interface,
description=description,
directives=directives,
extend=extend,
)
if cls is None:
return wrap
return wrap(cls)
@overload
@__dataclass_transform__(
order_default=True, kw_only_default=True, field_descriptors=(field, StrawberryField)
)
def input(
cls: T,
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
) -> T:
...
@overload
@__dataclass_transform__(
order_default=True, kw_only_default=True, field_descriptors=(field, StrawberryField)
)
def input(
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
) -> Callable[[T], T]:
...
def input(
cls: Optional[T] = None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
):
"""Annotates a class as a GraphQL Input type.
Example usage:
>>> @strawberry.input:
>>> class X:
>>> field_abc: str = "ABC"
"""
return type( # type: ignore # not sure why mypy complains here
cls,
name=name,
description=description,
directives=directives,
is_input=True,
)
@overload
@__dataclass_transform__(
order_default=True, kw_only_default=True, field_descriptors=(field, StrawberryField)
)
def interface(
cls: T,
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
) -> T:
...
@overload
@__dataclass_transform__(
order_default=True, kw_only_default=True, field_descriptors=(field, StrawberryField)
)
def interface(
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
) -> Callable[[T], T]:
...
@__dataclass_transform__(
order_default=True, kw_only_default=True, field_descriptors=(field, StrawberryField)
)
def interface(
cls: Optional[T] = None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
):
"""Annotates a class as a GraphQL Interface.
Example usage:
>>> @strawberry.interface:
>>> class X:
>>> field_abc: str
"""
return type( # type: ignore # not sure why mypy complains here
cls,
name=name,
description=description,
directives=directives,
is_interface=True,
)
def asdict(obj: object) -> Dict[str, object]:
"""Convert a strawberry object into a dictionary.
This wraps the dataclasses.asdict function to strawberry.
Example usage:
>>> @strawberry.type
>>> class User:
>>> name: str
>>> age: int
>>> # should be {"name": "Lorem", "age": 25}
>>> user_dict = strawberry.asdict(User(name="Lorem", age=25))
"""
return dataclasses.asdict(obj) # type: ignore
__all__ = [
"TypeDefinition",
"input",
"interface",
"type",
"asdict",
]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/object_type.py | object_type.py |
import warnings
from typing import Any, Dict, Optional, Type
DEPRECATED_NAMES: Dict[str, str] = {
"is_unset": "`is_unset` is deprecated use `value is UNSET` instead",
}
class UnsetType:
__instance: Optional["UnsetType"] = None
def __new__(cls: Type["UnsetType"]) -> "UnsetType":
if cls.__instance is None:
ret = super().__new__(cls)
cls.__instance = ret
return ret
else:
return cls.__instance
def __str__(self):
return ""
def __repr__(self) -> str:
return "UNSET"
def __bool__(self):
return False
UNSET: Any = UnsetType()
def _deprecated_is_unset(value: Any) -> bool:
warnings.warn(DEPRECATED_NAMES["is_unset"], DeprecationWarning, stacklevel=2)
return value is UNSET
def __getattr__(name: str) -> Any:
if name in DEPRECATED_NAMES:
warnings.warn(DEPRECATED_NAMES[name], DeprecationWarning, stacklevel=2)
return globals()[f"_deprecated_{name}"]
raise AttributeError(f"module {__name__} has no attribute {name}")
__all__ = [
"UNSET",
]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/unset.py | unset.py |
from __future__ import annotations
import sys
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Callable,
Iterable,
Mapping,
NewType,
Optional,
Type,
TypeVar,
Union,
overload,
)
from strawberry.exceptions import InvalidUnionTypeError
from strawberry.type import StrawberryOptional, StrawberryType
from .utils.str_converters import to_camel_case
if TYPE_CHECKING:
from graphql import GraphQLScalarType
# in python 3.10+ NewType is a class
if sys.version_info >= (3, 10):
_T = TypeVar("_T", bound=Union[type, NewType])
else:
_T = TypeVar("_T", bound=type)
def identity(x: _T) -> _T:
return x
@dataclass
class ScalarDefinition(StrawberryType):
name: str
description: Optional[str]
specified_by_url: Optional[str]
serialize: Optional[Callable]
parse_value: Optional[Callable]
parse_literal: Optional[Callable]
directives: Iterable[object] = ()
# Optionally store the GraphQLScalarType instance so that we don't get
# duplicates
implementation: Optional[GraphQLScalarType] = None
# used for better error messages
_source_file: Optional[str] = None
_source_line: Optional[int] = None
def copy_with(
self, type_var_map: Mapping[TypeVar, Union[StrawberryType, type]]
) -> Union[StrawberryType, type]:
return super().copy_with(type_var_map) # type: ignore[safe-super]
@property
def is_generic(self) -> bool:
return False
class ScalarWrapper:
_scalar_definition: ScalarDefinition
def __init__(self, wrap: Callable[[Any], Any]):
self.wrap = wrap
def __call__(self, *args, **kwargs):
return self.wrap(*args, **kwargs)
def __or__(self, other: Union[StrawberryType, type]) -> StrawberryType:
if other is None:
# Return the correct notation when using `StrawberryUnion | None`.
return StrawberryOptional(of_type=self)
# Raise an error in any other case.
# There is Work in progress to deal with more merging cases, see:
# https://github.com/strawberry-graphql/strawberry/pull/1455
raise InvalidUnionTypeError(str(other), self.wrap)
def _process_scalar(
cls: Type[_T],
*,
name: Optional[str] = None,
description: Optional[str] = None,
specified_by_url: Optional[str] = None,
serialize: Optional[Callable] = None,
parse_value: Optional[Callable] = None,
parse_literal: Optional[Callable] = None,
directives: Iterable[object] = (),
):
from strawberry.exceptions.handler import should_use_rich_exceptions
name = name or to_camel_case(cls.__name__)
_source_file = None
_source_line = None
if should_use_rich_exceptions():
frame = sys._getframe(3)
_source_file = frame.f_code.co_filename
_source_line = frame.f_lineno
wrapper = ScalarWrapper(cls)
wrapper._scalar_definition = ScalarDefinition(
name=name,
description=description,
specified_by_url=specified_by_url,
serialize=serialize,
parse_literal=parse_literal,
parse_value=parse_value,
directives=directives,
_source_file=_source_file,
_source_line=_source_line,
)
return wrapper
@overload
def scalar(
*,
name: Optional[str] = None,
description: Optional[str] = None,
specified_by_url: Optional[str] = None,
serialize: Callable = identity,
parse_value: Optional[Callable] = None,
parse_literal: Optional[Callable] = None,
directives: Iterable[object] = (),
) -> Callable[[_T], _T]:
...
@overload
def scalar(
cls: _T,
*,
name: Optional[str] = None,
description: Optional[str] = None,
specified_by_url: Optional[str] = None,
serialize: Callable = identity,
parse_value: Optional[Callable] = None,
parse_literal: Optional[Callable] = None,
directives: Iterable[object] = (),
) -> _T:
...
# FIXME: We are tricking pyright into thinking that we are returning the given type
# here or else it won't let us use any custom scalar to annotate attributes in
# dataclasses/types. This should be properly solved when implementing StrawberryScalar
def scalar(
cls=None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
specified_by_url: Optional[str] = None,
serialize: Callable = identity,
parse_value: Optional[Callable] = None,
parse_literal: Optional[Callable] = None,
directives: Iterable[object] = (),
) -> Any:
"""Annotates a class or type as a GraphQL custom scalar.
Example usages:
>>> strawberry.scalar(
>>> datetime.date,
>>> serialize=lambda value: value.isoformat(),
>>> parse_value=datetime.parse_date
>>> )
>>> Base64Encoded = strawberry.scalar(
>>> NewType("Base64Encoded", bytes),
>>> serialize=base64.b64encode,
>>> parse_value=base64.b64decode
>>> )
>>> @strawberry.scalar(
>>> serialize=lambda value: ",".join(value.items),
>>> parse_value=lambda value: CustomList(value.split(","))
>>> )
>>> class CustomList:
>>> def __init__(self, items):
>>> self.items = items
"""
if parse_value is None:
parse_value = cls
def wrap(cls):
return _process_scalar(
cls,
name=name,
description=description,
specified_by_url=specified_by_url,
serialize=serialize,
parse_value=parse_value,
parse_literal=parse_literal,
directives=directives,
)
if cls is None:
return wrap
return wrap(cls)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/custom_scalar.py | custom_scalar.py |
from __future__ import annotations
import base64
from typing import TYPE_CHECKING, Any, Dict, NewType, Union
from .custom_scalar import scalar
if TYPE_CHECKING:
from .custom_scalar import ScalarDefinition, ScalarWrapper
ID = NewType("ID", str)
JSON = scalar(
NewType("JSON", object), # mypy doesn't like `NewType("name", Any)`
description=(
"The `JSON` scalar type represents JSON values as specified by "
"[ECMA-404]"
"(http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf)."
),
specified_by_url=(
"http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf"
),
serialize=lambda v: v,
parse_value=lambda v: v,
)
Base16 = scalar(
NewType("Base16", bytes),
description="Represents binary data as Base16-encoded (hexadecimal) strings.",
specified_by_url="https://datatracker.ietf.org/doc/html/rfc4648.html#section-8",
serialize=lambda v: base64.b16encode(v).decode("utf-8"),
parse_value=lambda v: base64.b16decode(v.encode("utf-8"), casefold=True),
)
Base32 = scalar(
NewType("Base32", bytes),
description=(
"Represents binary data as Base32-encoded strings, using the standard alphabet."
),
specified_by_url=("https://datatracker.ietf.org/doc/html/rfc4648.html#section-6"),
serialize=lambda v: base64.b32encode(v).decode("utf-8"),
parse_value=lambda v: base64.b32decode(v.encode("utf-8"), casefold=True),
)
Base64 = scalar(
NewType("Base64", bytes),
description=(
"Represents binary data as Base64-encoded strings, using the standard alphabet."
),
specified_by_url="https://datatracker.ietf.org/doc/html/rfc4648.html#section-4",
serialize=lambda v: base64.b64encode(v).decode("utf-8"),
parse_value=lambda v: base64.b64decode(v.encode("utf-8")),
)
def is_scalar(
annotation: Any,
scalar_registry: Dict[object, Union[ScalarWrapper, ScalarDefinition]],
) -> bool:
if annotation in scalar_registry:
return True
return hasattr(annotation, "_scalar_definition")
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/scalars.py | scalars.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Awaitable, Optional, Union
if TYPE_CHECKING:
from strawberry.types.info import Info
class BasePermission:
"""
Base class for creating permissions
"""
message: Optional[str] = None
def has_permission(
self, source: Any, info: Info, **kwargs
) -> Union[bool, Awaitable[bool]]:
raise NotImplementedError(
"Permission classes should override has_permission method"
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/permission.py | permission.py |
from . import experimental, federation
from .arguments import argument
from .auto import auto
from .custom_scalar import scalar
from .directive import directive, directive_field
from .enum import enum, enum_value
from .field import field
from .lazy_type import LazyType, lazy
from .mutation import mutation, subscription
from .object_type import asdict, input, interface, type
from .permission import BasePermission
from .private import Private
from .scalars import ID
from .schema import Schema
from .schema_directive import schema_directive
from .union import union
from .unset import UNSET
__all__ = [
"BasePermission",
"experimental",
"ID",
"UNSET",
"lazy",
"LazyType",
"Private",
"Schema",
"argument",
"directive",
"directive_field",
"schema_directive",
"enum",
"enum_value",
"federation",
"field",
"input",
"interface",
"mutation",
"scalar",
"subscription",
"type",
"union",
"auto",
"asdict",
]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/__init__.py | __init__.py |
from __future__ import annotations
import itertools
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
Collection,
Iterable,
List,
Mapping,
NoReturn,
Optional,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from typing_extensions import Annotated, get_origin
from graphql import GraphQLNamedType, GraphQLUnionType
from strawberry.annotation import StrawberryAnnotation
from strawberry.exceptions import (
InvalidTypeForUnionMergeError,
InvalidUnionTypeError,
UnallowedReturnTypeForUnion,
WrongReturnTypeForUnion,
)
from strawberry.lazy_type import LazyType
from strawberry.type import StrawberryOptional, StrawberryType
if TYPE_CHECKING:
from graphql import (
GraphQLAbstractType,
GraphQLResolveInfo,
GraphQLType,
GraphQLTypeResolver,
)
from strawberry.schema.types.concrete_type import TypeMap
from strawberry.types.types import TypeDefinition
class StrawberryUnion(StrawberryType):
def __init__(
self,
name: Optional[str] = None,
type_annotations: Tuple[StrawberryAnnotation, ...] = tuple(),
description: Optional[str] = None,
directives: Iterable[object] = (),
):
self.graphql_name = name
self.type_annotations = type_annotations
self.description = description
self.directives = directives
def __eq__(self, other: object) -> bool:
if isinstance(other, StrawberryType):
if isinstance(other, StrawberryUnion):
return (
self.graphql_name == other.graphql_name
and self.type_annotations == other.type_annotations
and self.description == other.description
)
return False
return super().__eq__(other)
def __hash__(self) -> int:
# TODO: Is this a bad idea? __eq__ objects are supposed to have the same hash
return id(self)
def __or__(self, other: Union[StrawberryType, type]) -> StrawberryType:
if other is None:
# Return the correct notation when using `StrawberryUnion | None`.
return StrawberryOptional(of_type=self)
# Raise an error in any other case.
# There is Work in progress to deal with more merging cases, see:
# https://github.com/strawberry-graphql/strawberry/pull/1455
raise InvalidTypeForUnionMergeError(self, other)
@property
def types(self) -> Tuple[StrawberryType, ...]:
return tuple(
cast(StrawberryType, annotation.resolve())
for annotation in self.type_annotations
)
@property
def type_params(self) -> List[TypeVar]:
def _get_type_params(type_: StrawberryType):
if isinstance(type_, LazyType):
type_ = cast("StrawberryType", type_.resolve_type())
if hasattr(type_, "_type_definition"):
parameters = getattr(type_, "__parameters__", None)
return list(parameters) if parameters else []
return type_.type_params
# TODO: check if order is important:
# https://github.com/strawberry-graphql/strawberry/issues/445
return list(
set(itertools.chain(*(_get_type_params(type_) for type_ in self.types)))
)
@property
def is_generic(self) -> bool:
def _is_generic(type_: object) -> bool:
if hasattr(type_, "_type_definition"):
type_ = type_._type_definition
if isinstance(type_, StrawberryType):
return type_.is_generic
return False
return any(map(_is_generic, self.types))
def copy_with(
self, type_var_map: Mapping[TypeVar, Union[StrawberryType, type]]
) -> StrawberryType:
if not self.is_generic:
return self
new_types = []
for type_ in self.types:
new_type: Union[StrawberryType, type]
if hasattr(type_, "_type_definition"):
type_definition: TypeDefinition = type_._type_definition
if type_definition.is_generic:
new_type = type_definition.copy_with(type_var_map)
if isinstance(type_, StrawberryType) and type_.is_generic:
new_type = type_.copy_with(type_var_map)
else:
new_type = type_
new_types.append(new_type)
return StrawberryUnion(
type_annotations=tuple(map(StrawberryAnnotation, new_types)),
description=self.description,
)
def __call__(self, *_args, **_kwargs) -> NoReturn:
"""Do not use.
Used to bypass
https://github.com/python/cpython/blob/5efb1a77e75648012f8b52960c8637fc296a5c6d/Lib/typing.py#L148-L149
"""
raise ValueError("Cannot use union type directly")
def get_type_resolver(self, type_map: TypeMap) -> GraphQLTypeResolver:
def _resolve_union_type(
root: Any, info: GraphQLResolveInfo, type_: GraphQLAbstractType
) -> str:
assert isinstance(type_, GraphQLUnionType)
from strawberry.types.types import TypeDefinition
# If the type given is not an Object type, try resolving using `is_type_of`
# defined on the union's inner types
if not hasattr(root, "_type_definition"):
for inner_type in type_.types:
if inner_type.is_type_of is not None and inner_type.is_type_of(
root, info
):
return inner_type.name
# Couldn't resolve using `is_type_of`
raise WrongReturnTypeForUnion(info.field_name, str(type(root)))
return_type: Optional[GraphQLType]
# Iterate over all of our known types and find the first concrete
# type that implements the type. We prioritise checking types named in the
# Union in case a nested generic object matches against more than one type.
concrete_types_for_union = (type_map[x.name] for x in type_.types)
# TODO: do we still need to iterate over all types in `type_map`?
for possible_concrete_type in chain(
concrete_types_for_union, type_map.values()
):
possible_type = possible_concrete_type.definition
if not isinstance(possible_type, TypeDefinition):
continue
if possible_type.is_implemented_by(root):
return_type = possible_concrete_type.implementation
break
else:
return_type = None
# Make sure the found type is expected by the Union
if return_type is None or return_type not in type_.types:
raise UnallowedReturnTypeForUnion(
info.field_name, str(type(root)), set(type_.types)
)
# Return the name of the type. Returning the actual type is now deprecated
if isinstance(return_type, GraphQLNamedType):
# TODO: Can return_type ever _not_ be a GraphQLNamedType?
return return_type.name
else:
# todo: check if this is correct
return return_type.__name__ # type: ignore
return _resolve_union_type
@staticmethod
def is_valid_union_type(type_: object) -> bool:
# Usual case: Union made of @strawberry.types
if hasattr(type_, "_type_definition"):
return True
# Can't confidently assert that these types are valid/invalid within Unions
# until full type resolving stage is complete
ignored_types = (LazyType, TypeVar)
if isinstance(type_, ignored_types):
return True
if get_origin(type_) is Annotated:
return True
return False
Types = TypeVar("Types", bound=Type)
# We return a Union type here in order to allow to use the union type as type
# annotation.
# For the `types` argument we'd ideally use a TypeVarTuple, but that's not
# yet supported in any python implementation (or in typing_extensions).
# See https://www.python.org/dev/peps/pep-0646/ for more information
def union(
name: str,
types: Collection[Types],
*,
description: Optional[str] = None,
directives: Iterable[object] = (),
) -> Union[Types]:
"""Creates a new named Union type.
Example usages:
>>> @strawberry.type
... class A: ...
>>> @strawberry.type
... class B: ...
>>> strawberry.union("Name", (A, Optional[B]))
"""
# Validate types
if not types:
raise TypeError("No types passed to `union`")
for type_ in types:
# Due to TypeVars, Annotations, LazyTypes, etc., this does not perfectly detect
# issues. This check also occurs in the Schema conversion stage as a backup.
if not StrawberryUnion.is_valid_union_type(type_):
raise InvalidUnionTypeError(union_name=name, invalid_type=type_)
union_definition = StrawberryUnion(
name=name,
type_annotations=tuple(StrawberryAnnotation(type_) for type_ in types),
description=description,
directives=directives,
)
return union_definition # type: ignore
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/union.py | union.py |
from __future__ import annotations
import asyncio
import json
from datetime import timedelta
from typing import TYPE_CHECKING, Iterable
from aiohttp import web
from strawberry.aiohttp.handlers import (
GraphQLTransportWSHandler,
GraphQLWSHandler,
HTTPHandler,
)
from strawberry.http import process_result
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL
if TYPE_CHECKING:
from strawberry.http import GraphQLHTTPResponse
from strawberry.schema import BaseSchema
from strawberry.types import ExecutionResult
class GraphQLView:
# Mark the view as coroutine so that AIOHTTP does not confuse it with a deprecated
# bare handler function.
_is_coroutine = asyncio.coroutines._is_coroutine # type: ignore[attr-defined]
graphql_transport_ws_handler_class = GraphQLTransportWSHandler
graphql_ws_handler_class = GraphQLWSHandler
http_handler_class = HTTPHandler
def __init__(
self,
schema: BaseSchema,
graphiql: bool = True,
allow_queries_via_get: bool = True,
keep_alive: bool = True,
keep_alive_interval: float = 1,
debug: bool = False,
subscription_protocols: Iterable[str] = (
GRAPHQL_TRANSPORT_WS_PROTOCOL,
GRAPHQL_WS_PROTOCOL,
),
connection_init_wait_timeout: timedelta = timedelta(minutes=1),
):
self.schema = schema
self.graphiql = graphiql
self.allow_queries_via_get = allow_queries_via_get
self.keep_alive = keep_alive
self.keep_alive_interval = keep_alive_interval
self.debug = debug
self.subscription_protocols = subscription_protocols
self.connection_init_wait_timeout = connection_init_wait_timeout
async def __call__(self, request: web.Request) -> web.StreamResponse:
ws = web.WebSocketResponse(protocols=self.subscription_protocols)
ws_test = ws.can_prepare(request)
if ws_test.ok:
if ws_test.protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
return await self.graphql_transport_ws_handler_class(
schema=self.schema,
debug=self.debug,
connection_init_wait_timeout=self.connection_init_wait_timeout,
get_context=self.get_context, # type: ignore
get_root_value=self.get_root_value,
request=request,
).handle()
elif ws_test.protocol == GRAPHQL_WS_PROTOCOL:
return await self.graphql_ws_handler_class(
schema=self.schema,
debug=self.debug,
keep_alive=self.keep_alive,
keep_alive_interval=self.keep_alive_interval,
get_context=self.get_context,
get_root_value=self.get_root_value,
request=request,
).handle()
else:
await ws.prepare(request)
await ws.close(code=4406, message=b"Subprotocol not acceptable")
return ws
else:
return await self.http_handler_class(
schema=self.schema,
graphiql=self.graphiql,
allow_queries_via_get=self.allow_queries_via_get,
get_context=self.get_context,
get_root_value=self.get_root_value,
encode_json=self.encode_json,
process_result=self.process_result,
request=request,
).handle()
async def get_root_value(self, request: web.Request) -> object:
return None
async def get_context(
self, request: web.Request, response: web.StreamResponse
) -> object:
return {"request": request, "response": response}
async def process_result(
self, request: web.Request, result: ExecutionResult
) -> GraphQLHTTPResponse:
return process_result(result)
def encode_json(self, response_data: GraphQLHTTPResponse) -> str:
return json.dumps(response_data)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/aiohttp/views.py | views.py |
from __future__ import annotations
from contextlib import suppress
from typing import TYPE_CHECKING, Any, Optional
from aiohttp import http, web
from strawberry.subscriptions import GRAPHQL_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_ws.handlers import BaseGraphQLWSHandler
if TYPE_CHECKING:
from strawberry.schema import BaseSchema
from strawberry.subscriptions.protocols.graphql_ws.types import OperationMessage
class GraphQLWSHandler(BaseGraphQLWSHandler):
def __init__(
self,
schema: BaseSchema,
debug: bool,
keep_alive: bool,
keep_alive_interval: float,
get_context,
get_root_value,
request: web.Request,
):
super().__init__(schema, debug, keep_alive, keep_alive_interval)
self._get_context = get_context
self._get_root_value = get_root_value
self._request = request
self._ws = web.WebSocketResponse(protocols=[GRAPHQL_WS_PROTOCOL])
async def get_context(self) -> Any:
return await self._get_context(request=self._request, response=self._ws)
async def get_root_value(self) -> Any:
return await self._get_root_value(request=self._request)
async def send_json(self, data: OperationMessage) -> None:
await self._ws.send_json(data)
async def close(self, code: int = 1000, reason: Optional[str] = None) -> None:
message = reason.encode() if reason else b""
await self._ws.close(code=code, message=message)
async def handle_request(self) -> Any:
await self._ws.prepare(self._request)
try:
async for ws_message in self._ws: # type: http.WSMessage
if ws_message.type == http.WSMsgType.TEXT:
message: OperationMessage = ws_message.json()
await self.handle_message(message)
finally:
if self.keep_alive_task:
self.keep_alive_task.cancel()
with suppress(BaseException):
await self.keep_alive_task
for operation_id in list(self.subscriptions.keys()):
await self.cleanup_operation(operation_id)
return self._ws
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/aiohttp/handlers/graphql_ws_handler.py | graphql_ws_handler.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Dict
from aiohttp import http, web
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_transport_ws.handlers import (
BaseGraphQLTransportWSHandler,
)
if TYPE_CHECKING:
from datetime import timedelta
from strawberry.schema import BaseSchema
class GraphQLTransportWSHandler(BaseGraphQLTransportWSHandler):
def __init__(
self,
schema: BaseSchema,
debug: bool,
connection_init_wait_timeout: timedelta,
get_context: Callable[..., Dict[str, Any]],
get_root_value: Any,
request: web.Request,
):
super().__init__(schema, debug, connection_init_wait_timeout)
self._get_context = get_context
self._get_root_value = get_root_value
self._request = request
self._ws = web.WebSocketResponse(protocols=[GRAPHQL_TRANSPORT_WS_PROTOCOL])
async def get_context(self) -> Any:
return await self._get_context(request=self._request, response=self._ws) # type: ignore # noqa: E501
async def get_root_value(self) -> Any:
return await self._get_root_value(request=self._request)
async def send_json(self, data: dict) -> None:
await self._ws.send_json(data)
async def close(self, code: int, reason: str) -> None:
await self._ws.close(code=code, message=reason.encode())
async def handle_request(self) -> web.StreamResponse:
await self._ws.prepare(self._request)
try:
async for ws_message in self._ws: # type: http.WSMessage
if ws_message.type == http.WSMsgType.TEXT:
await self.handle_message(ws_message.json())
else:
error_message = "WebSocket message type must be text"
await self.handle_invalid_message(error_message)
finally:
for operation_id in list(self.subscriptions.keys()):
await self.cleanup_operation(operation_id)
await self.reap_completed_tasks()
return self._ws
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/aiohttp/handlers/graphql_transport_ws_handler.py | graphql_transport_ws_handler.py |
from strawberry.aiohttp.handlers.graphql_transport_ws_handler import (
GraphQLTransportWSHandler,
)
from strawberry.aiohttp.handlers.graphql_ws_handler import GraphQLWSHandler
from strawberry.aiohttp.handlers.http_handler import HTTPHandler
__all__ = ["GraphQLTransportWSHandler", "GraphQLWSHandler", "HTTPHandler"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/aiohttp/handlers/__init__.py | __init__.py |
from __future__ import annotations
import json
from io import BytesIO
from typing import TYPE_CHECKING, Any, Dict, Union
from aiohttp import web
from strawberry.exceptions import MissingQueryError
from strawberry.file_uploads.utils import replace_placeholders_with_files
from strawberry.http import parse_query_params, parse_request_data
from strawberry.schema.exceptions import InvalidOperationTypeError
from strawberry.types.graphql import OperationType
from strawberry.utils.graphiql import get_graphiql_html
if TYPE_CHECKING:
from typing_extensions import Literal
from strawberry.http import GraphQLRequestData
from strawberry.schema import BaseSchema
class HTTPHandler:
def __init__(
self,
schema: BaseSchema,
graphiql: bool,
allow_queries_via_get: bool,
get_context,
get_root_value,
encode_json,
process_result,
request: web.Request,
):
self.schema = schema
self.graphiql = graphiql
self.allow_queries_via_get = allow_queries_via_get
self.get_context = get_context
self.get_root_value = get_root_value
self.encode_json = encode_json
self.process_result = process_result
self.request = request
async def handle(self) -> web.StreamResponse:
if self.request.method == "GET":
return await self.get(self.request)
if self.request.method == "POST":
return await self.post(self.request)
raise web.HTTPMethodNotAllowed(self.request.method, ["GET", "POST"])
async def get(self, request: web.Request) -> web.StreamResponse:
if request.query:
try:
query_params = {
key: request.query.getone(key) for key in set(request.query.keys())
}
query_data = parse_query_params(query_params)
request_data = parse_request_data(query_data)
except json.JSONDecodeError:
raise web.HTTPBadRequest(reason="Unable to parse request body as JSON")
return await self.execute_request(
request=request, request_data=request_data, method="GET"
)
elif self.should_render_graphiql(request):
return self.render_graphiql()
raise web.HTTPNotFound()
async def post(self, request: web.Request) -> web.StreamResponse:
request_data = await self.get_request_data(request)
return await self.execute_request(
request=request, request_data=request_data, method="POST"
)
async def execute_request(
self,
request: web.Request,
request_data: GraphQLRequestData,
method: Union[Literal["GET"], Literal["POST"]],
) -> web.StreamResponse:
response = web.Response()
context = await self.get_context(request, response)
root_value = await self.get_root_value(request)
allowed_operation_types = OperationType.from_http(method)
if not self.allow_queries_via_get and method == "GET":
allowed_operation_types = allowed_operation_types - {OperationType.QUERY}
try:
result = await self.schema.execute(
query=request_data.query,
root_value=root_value,
variable_values=request_data.variables,
context_value=context,
operation_name=request_data.operation_name,
allowed_operation_types=allowed_operation_types,
)
except InvalidOperationTypeError as e:
raise web.HTTPBadRequest(
reason=e.as_http_error_reason(method=method)
) from e
except MissingQueryError:
raise web.HTTPBadRequest(reason="No GraphQL query found in the request")
response_data = await self.process_result(request, result)
response.text = self.encode_json(response_data)
response.content_type = "application/json"
return response
async def get_request_data(self, request: web.Request) -> GraphQLRequestData:
data = await self.parse_body(request)
return parse_request_data(data)
async def parse_body(self, request: web.Request) -> dict:
if request.content_type.startswith("multipart/form-data"):
return await self.parse_multipart_body(request)
try:
return await request.json()
except json.JSONDecodeError as e:
raise web.HTTPBadRequest(
reason="Unable to parse request body as JSON"
) from e
async def parse_multipart_body(self, request: web.Request) -> dict:
reader = await request.multipart()
operations: Dict[str, Any] = {}
files_map: Dict[str, Any] = {}
files: Dict[str, Any] = {}
try:
async for field in reader:
if field.name == "operations":
operations = (await field.json()) or {}
elif field.name == "map":
files_map = (await field.json()) or {}
elif field.filename:
assert field.name
files[field.name] = BytesIO(await field.read(decode=False))
except ValueError:
raise web.HTTPBadRequest(reason="Unable to parse the multipart body")
try:
return replace_placeholders_with_files(operations, files_map, files)
except KeyError:
raise web.HTTPBadRequest(reason="File(s) missing in form data")
def render_graphiql(self) -> web.StreamResponse:
html_string = get_graphiql_html()
return web.Response(text=html_string, content_type="text/html")
def should_render_graphiql(self, request: web.Request) -> bool:
if not self.graphiql:
return False
return any(
supported_header in request.headers.get("Accept", "")
for supported_header in ("text/html", "*/*")
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/aiohttp/handlers/http_handler.py | http_handler.py |
from __future__ import annotations
from typing import (
Any,
Dict,
Mapping,
Optional,
)
from strawberry.test.client import BaseGraphQLTestClient, Response
class GraphQLTestClient(BaseGraphQLTestClient):
async def query(
self,
query: str,
variables: Optional[Dict[str, Mapping]] = None,
headers: Optional[Dict[str, object]] = None,
asserts_errors: Optional[bool] = True,
files: Optional[Dict[str, object]] = None,
) -> Response:
body = self._build_body(query, variables, files)
resp = await self.request(body, headers, files)
data = await resp.json()
response = Response(
errors=data.get("errors"),
data=data.get("data"),
extensions=data.get("extensions"),
)
if asserts_errors:
assert resp.status == 200
assert response.errors is None
return response
async def request(
self,
body: Dict[str, object],
headers: Optional[Dict[str, object]] = None,
files: Optional[Dict[str, object]] = None,
) -> Any:
response = await self._client.post(
self.url,
json=body if not files else None,
data=body if files else None,
)
return response
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/aiohttp/test/client.py | client.py |
from .client import GraphQLTestClient
__all__ = ["GraphQLTestClient"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/aiohttp/test/__init__.py | __init__.py |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, List, Optional, Type, Union
if TYPE_CHECKING:
from enum import EnumMeta
from typing_extensions import Literal
@dataclass
class GraphQLOptional:
of_type: GraphQLType
@dataclass
class GraphQLList:
of_type: GraphQLType
@dataclass
class GraphQLUnion:
name: str
types: List[GraphQLObjectType]
@dataclass
class GraphQLField:
name: str
alias: Optional[str]
type: GraphQLType
@dataclass
class GraphQLObjectType:
name: str
fields: List[GraphQLField]
@dataclass
class GraphQLEnum:
name: str
values: List[str]
python_type: EnumMeta
@dataclass
class GraphQLScalar:
name: str
python_type: Optional[Type]
GraphQLType = Union[
GraphQLObjectType,
GraphQLEnum,
GraphQLScalar,
GraphQLOptional,
GraphQLList,
GraphQLUnion,
]
@dataclass
class GraphQLFieldSelection:
field: str
alias: Optional[str]
selections: List[GraphQLSelection]
directives: List[GraphQLDirective]
arguments: List[GraphQLArgument]
@dataclass
class GraphQLInlineFragment:
type_condition: str
selections: List[GraphQLSelection]
GraphQLSelection = Union[GraphQLFieldSelection, GraphQLInlineFragment]
@dataclass
class GraphQLStringValue:
value: str
@dataclass
class GraphQLIntValue:
value: int
@dataclass
class GraphQLEnumValue:
name: str
@dataclass
class GraphQLBoolValue:
value: bool
@dataclass
class GraphQLListValue:
values: List[GraphQLArgumentValue]
@dataclass
class GraphQLVariableReference:
value: str
GraphQLArgumentValue = Union[
GraphQLStringValue,
GraphQLIntValue,
GraphQLVariableReference,
GraphQLListValue,
GraphQLEnumValue,
GraphQLBoolValue,
]
@dataclass
class GraphQLArgument:
name: str
value: GraphQLArgumentValue
@dataclass
class GraphQLDirective:
name: str
arguments: List[GraphQLArgument]
@dataclass
class GraphQLVariable:
name: str
type: GraphQLType
@dataclass
class GraphQLOperation:
name: str
kind: Literal["query", "mutation", "subscription"]
selections: List[GraphQLSelection]
directives: List[GraphQLDirective]
variables: List[GraphQLVariable]
type: GraphQLObjectType
variables_type: Optional[GraphQLObjectType]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/codegen/types.py | types.py |
from __future__ import annotations
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Callable,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from typing_extensions import Literal, Protocol
from graphql import (
BooleanValueNode,
EnumValueNode,
FieldNode,
InlineFragmentNode,
IntValueNode,
ListTypeNode,
ListValueNode,
NamedTypeNode,
NonNullTypeNode,
OperationDefinitionNode,
StringValueNode,
VariableNode,
parse,
)
from strawberry.custom_scalar import ScalarDefinition, ScalarWrapper
from strawberry.enum import EnumDefinition
from strawberry.lazy_type import LazyType
from strawberry.type import StrawberryList, StrawberryOptional, StrawberryType
from strawberry.types.types import TypeDefinition
from strawberry.union import StrawberryUnion
from strawberry.utils.str_converters import capitalize_first, to_camel_case
from .exceptions import (
MultipleOperationsProvidedError,
NoOperationNameProvidedError,
NoOperationProvidedError,
)
from .types import (
GraphQLArgument,
GraphQLBoolValue,
GraphQLDirective,
GraphQLEnum,
GraphQLEnumValue,
GraphQLField,
GraphQLFieldSelection,
GraphQLInlineFragment,
GraphQLIntValue,
GraphQLList,
GraphQLListValue,
GraphQLObjectType,
GraphQLOperation,
GraphQLOptional,
GraphQLScalar,
GraphQLStringValue,
GraphQLUnion,
GraphQLVariable,
GraphQLVariableReference,
)
if TYPE_CHECKING:
from pathlib import Path
from graphql import (
ArgumentNode,
DirectiveNode,
DocumentNode,
SelectionNode,
SelectionSetNode,
TypeNode,
ValueNode,
VariableDefinitionNode,
)
from strawberry.schema import Schema
from .types import GraphQLArgumentValue, GraphQLSelection, GraphQLType
@dataclass
class CodegenFile:
path: str
content: str
@dataclass
class CodegenResult:
files: List[CodegenFile]
def to_string(self) -> str:
return "\n".join(f.content for f in self.files) + "\n"
def write(self, folder: Path) -> None:
for file in self.files:
destination = folder / file.path
destination.write_text(file.content)
class HasSelectionSet(Protocol):
selection_set: Optional[SelectionSetNode]
class QueryCodegenPlugin:
def on_start(self) -> None:
...
def on_end(self, result: CodegenResult) -> None:
...
def generate_code(
self, types: List[GraphQLType], operation: GraphQLOperation
) -> List[CodegenFile]:
return []
class QueryCodegenPluginManager:
def __init__(self, plugins: List[QueryCodegenPlugin]) -> None:
self.plugins = plugins
def generate_code(
self, types: List[GraphQLType], operation: GraphQLOperation
) -> CodegenResult:
result = CodegenResult(files=[])
for plugin in self.plugins:
files = plugin.generate_code(types, operation)
result.files.extend(files)
return result
def on_start(self) -> None:
for plugin in self.plugins:
plugin.on_start()
def on_end(self, result: CodegenResult) -> None:
for plugin in self.plugins:
plugin.on_end(result)
class QueryCodegen:
def __init__(self, schema: Schema, plugins: List[QueryCodegenPlugin]):
self.schema = schema
self.plugin_manager = QueryCodegenPluginManager(plugins)
self.types: List[GraphQLType] = []
def run(self, query: str) -> CodegenResult:
self.plugin_manager.on_start()
ast = parse(query)
operations = self._get_operations(ast)
if not operations:
raise NoOperationProvidedError()
if len(operations) > 1:
raise MultipleOperationsProvidedError()
operation = operations[0]
if operation.name is None:
raise NoOperationNameProvidedError()
self.operation = self._convert_operation(operation)
result = self.generate_code()
self.plugin_manager.on_end(result)
return result
def _collect_type(self, type_: GraphQLType) -> None:
if type_ in self.types:
return
self.types.append(type_)
def _convert_selection(self, selection: SelectionNode) -> GraphQLSelection:
if isinstance(selection, FieldNode):
return GraphQLFieldSelection(
selection.name.value,
selection.alias.value if selection.alias else None,
selections=self._convert_selection_set(selection.selection_set),
directives=self._convert_directives(selection.directives),
arguments=self._convert_arguments(selection.arguments),
)
if isinstance(selection, InlineFragmentNode):
return GraphQLInlineFragment(
selection.type_condition.name.value,
self._convert_selection_set(selection.selection_set),
)
raise ValueError(f"Unsupported type: {type(selection)}") # pragma: no cover
def _convert_selection_set(
self, selection_set: Optional[SelectionSetNode]
) -> List[GraphQLSelection]:
if selection_set is None:
return []
return [
self._convert_selection(selection) for selection in selection_set.selections
]
def _convert_value(self, value: ValueNode) -> GraphQLArgumentValue:
if isinstance(value, StringValueNode):
return GraphQLStringValue(value.value)
if isinstance(value, IntValueNode):
return GraphQLIntValue(int(value.value))
if isinstance(value, VariableNode):
return GraphQLVariableReference(value.name.value)
if isinstance(value, ListValueNode):
return GraphQLListValue(
[self._convert_value(item) for item in value.values]
)
if isinstance(value, EnumValueNode):
return GraphQLEnumValue(value.value)
if isinstance(value, BooleanValueNode):
return GraphQLBoolValue(value.value)
raise ValueError(f"Unsupported type: {type(value)}") # pragma: no cover
def _convert_arguments(
self, arguments: Iterable[ArgumentNode]
) -> List[GraphQLArgument]:
return [
GraphQLArgument(argument.name.value, self._convert_value(argument.value))
for argument in arguments
]
def _convert_directives(
self, directives: Iterable[DirectiveNode]
) -> List[GraphQLDirective]:
return [
GraphQLDirective(
directive.name.value,
self._convert_arguments(directive.arguments),
)
for directive in directives
]
def _convert_operation(
self, operation_definition: OperationDefinitionNode
) -> GraphQLOperation:
query_type = self.schema.get_type_by_name("Query")
assert isinstance(query_type, TypeDefinition)
assert operation_definition.name is not None
operation_name = operation_definition.name.value
result_class_name = f"{operation_name}Result"
operation_type = self._collect_types(
cast(HasSelectionSet, operation_definition),
parent_type=query_type,
class_name=result_class_name,
)
operation_kind = cast(
Literal["query", "mutation", "subscription"],
operation_definition.operation.value,
)
variables, variables_type = self._convert_variable_definitions(
operation_definition.variable_definitions, operation_name=operation_name
)
return GraphQLOperation(
operation_definition.name.value,
kind=operation_kind,
selections=self._convert_selection_set(operation_definition.selection_set),
directives=self._convert_directives(operation_definition.directives),
variables=variables,
type=cast("GraphQLObjectType", operation_type),
variables_type=variables_type,
)
def _convert_variable_definitions(
self,
variable_definitions: Optional[Iterable[VariableDefinitionNode]],
operation_name: str,
) -> Tuple[List[GraphQLVariable], Optional[GraphQLObjectType]]:
if not variable_definitions:
return [], None
type_ = GraphQLObjectType(f"{operation_name}Variables", [])
self._collect_type(type_)
variables: List[GraphQLVariable] = []
for variable_definition in variable_definitions:
variable_type = self._collect_type_from_variable(variable_definition.type)
variable = GraphQLVariable(
variable_definition.variable.name.value,
variable_type,
)
type_.fields.append(GraphQLField(variable.name, None, variable_type))
variables.append(variable)
return variables, type_
def _get_operations(self, ast: DocumentNode) -> List[OperationDefinitionNode]:
return [
definition
for definition in ast.definitions
if isinstance(definition, OperationDefinitionNode)
]
def _get_field_type(
self,
field_type: Union[StrawberryType, type],
) -> GraphQLType:
if isinstance(field_type, StrawberryOptional):
return GraphQLOptional(self._get_field_type(field_type.of_type))
if isinstance(field_type, StrawberryList):
return GraphQLList(self._get_field_type(field_type.of_type))
if (
not isinstance(field_type, StrawberryType)
and field_type in self.schema.schema_converter.scalar_registry
):
field_type = self.schema.schema_converter.scalar_registry[field_type] # type: ignore # noqa: E501
if isinstance(field_type, ScalarWrapper):
python_type = field_type.wrap
if hasattr(python_type, "__supertype__"):
python_type = python_type.__supertype__
return self._collect_scalar(field_type._scalar_definition, python_type) # type: ignore # noqa: E501
if isinstance(field_type, ScalarDefinition):
return self._collect_scalar(field_type, None)
elif isinstance(field_type, EnumDefinition):
return self._collect_enum(field_type)
raise ValueError(f"Unsupported type: {field_type}") # pragma: no cover
def _collect_type_from_strawberry_type(
self, strawberry_type: Union[type, StrawberryType]
) -> GraphQLType:
type_: GraphQLType
if isinstance(strawberry_type, StrawberryOptional):
return GraphQLOptional(
self._collect_type_from_strawberry_type(strawberry_type.of_type)
)
if isinstance(strawberry_type, StrawberryList):
return GraphQLOptional(
self._collect_type_from_strawberry_type(strawberry_type.of_type)
)
if hasattr(strawberry_type, "_type_definition"):
strawberry_type = strawberry_type._type_definition
if isinstance(strawberry_type, TypeDefinition):
type_ = GraphQLObjectType(
strawberry_type.name,
[],
)
for field in strawberry_type.fields:
field_type = self._collect_type_from_strawberry_type(field.type)
type_.fields.append(GraphQLField(field.name, None, field_type))
self._collect_type(type_)
else:
type_ = self._get_field_type(strawberry_type)
return type_
def _collect_type_from_variable(
self, variable_type: TypeNode, parent_type: Optional[TypeNode] = None
) -> GraphQLType:
type_: Optional[GraphQLType] = None
if isinstance(variable_type, ListTypeNode):
type_ = GraphQLList(
self._collect_type_from_variable(variable_type.type, variable_type)
)
elif isinstance(variable_type, NonNullTypeNode):
return self._collect_type_from_variable(variable_type.type, variable_type)
elif isinstance(variable_type, NamedTypeNode):
strawberry_type = self.schema.get_type_by_name(variable_type.name.value)
assert strawberry_type
type_ = self._collect_type_from_strawberry_type(strawberry_type)
assert type_
if parent_type is not None and isinstance(parent_type, NonNullTypeNode):
return type_
return GraphQLOptional(type_)
def _field_from_selection(
self, selection: FieldNode, parent_type: TypeDefinition
) -> GraphQLField:
field = self.schema.get_field_for_type(selection.name.value, parent_type.name)
assert field
field_type = self._get_field_type(field.type)
return GraphQLField(
field.name, selection.alias.value if selection.alias else None, field_type
)
def _unwrap_type(
self, type_: Union[type, StrawberryType]
) -> Tuple[
Union[type, StrawberryType], Optional[Callable[[GraphQLType], GraphQLType]]
]:
wrapper = None
if isinstance(type_, StrawberryOptional):
type_, wrapper = self._unwrap_type(type_.of_type)
wrapper = (
GraphQLOptional
if wrapper is None
else lambda t: GraphQLOptional(wrapper(t)) # type: ignore[misc]
)
elif isinstance(type_, StrawberryList):
type_, wrapper = self._unwrap_type(type_.of_type)
wrapper = (
GraphQLList
if wrapper is None
else lambda t: GraphQLList(wrapper(t)) # type: ignore[misc]
)
elif isinstance(type_, LazyType):
return self._unwrap_type(type_.resolve_type())
return type_, wrapper
def _field_from_selection_set(
self, selection: FieldNode, class_name: str, parent_type: TypeDefinition
) -> GraphQLField:
assert selection.selection_set is not None
selected_field = self.schema.get_field_for_type(
selection.name.value, parent_type.name
)
assert selected_field
selected_field_type, wrapper = self._unwrap_type(selected_field.type)
name = capitalize_first(to_camel_case(selection.name.value))
class_name = f"{class_name}{(name)}"
field_type: GraphQLType
if isinstance(selected_field_type, StrawberryUnion):
field_type = self._collect_types_with_inline_fragments(
selection, parent_type, class_name
)
else:
parent_type = cast(
TypeDefinition, selected_field_type._type_definition # type: ignore
)
field_type = self._collect_types(selection, parent_type, class_name)
if wrapper:
field_type = wrapper(field_type)
return GraphQLField(
selected_field.name,
selection.alias.value if selection.alias else None,
field_type,
)
def _get_field(
self, selection: FieldNode, class_name: str, parent_type: TypeDefinition
) -> GraphQLField:
if selection.selection_set:
return self._field_from_selection_set(selection, class_name, parent_type)
return self._field_from_selection(selection, parent_type)
def _collect_types_with_inline_fragments(
self,
selection: HasSelectionSet,
parent_type: TypeDefinition,
class_name: str,
) -> Union[GraphQLObjectType, GraphQLUnion]:
sub_types = self._collect_types_using_fragments(
selection, parent_type, class_name
)
if len(sub_types) == 1:
return sub_types[0]
union = GraphQLUnion(class_name, sub_types)
self._collect_type(union)
return union
def _collect_types(
self,
selection: HasSelectionSet,
parent_type: TypeDefinition,
class_name: str,
) -> GraphQLType:
assert selection.selection_set is not None
selection_set = selection.selection_set
if any(
isinstance(selection, InlineFragmentNode)
for selection in selection_set.selections
):
return self._collect_types_with_inline_fragments(
selection, parent_type, class_name
)
current_type = GraphQLObjectType(class_name, [])
for sub_selection in selection_set.selections:
assert isinstance(sub_selection, FieldNode)
field = self._get_field(sub_selection, class_name, parent_type)
current_type.fields.append(field)
self._collect_type(current_type)
return current_type
def generate_code(self) -> CodegenResult:
return self.plugin_manager.generate_code(
types=self.types, operation=self.operation
)
def _collect_types_using_fragments(
self,
selection: HasSelectionSet,
parent_type: TypeDefinition,
class_name: str,
) -> List[GraphQLObjectType]:
assert selection.selection_set
common_fields: List[GraphQLField] = []
fragments: List[InlineFragmentNode] = []
sub_types: List[GraphQLObjectType] = []
for sub_selection in selection.selection_set.selections:
if isinstance(sub_selection, FieldNode):
common_fields.append(
self._get_field(sub_selection, class_name, parent_type)
)
if isinstance(sub_selection, InlineFragmentNode):
fragments.append(sub_selection)
for fragment in fragments:
fragment_class_name = class_name + fragment.type_condition.name.value
current_type = GraphQLObjectType(fragment_class_name, [])
for sub_selection in fragment.selection_set.selections:
# TODO: recurse, use existing method ?
assert isinstance(sub_selection, FieldNode)
current_type.fields = list(common_fields)
parent_type = cast(
TypeDefinition,
self.schema.get_type_by_name(fragment.type_condition.name.value),
)
assert parent_type
current_type.fields.append(
self._get_field(
selection=sub_selection,
class_name=fragment_class_name,
parent_type=parent_type,
)
)
sub_types.append(current_type)
self.types.extend(sub_types)
return sub_types
def _collect_scalar(
self, scalar_definition: ScalarDefinition, python_type: Optional[Type]
) -> GraphQLScalar:
graphql_scalar = GraphQLScalar(scalar_definition.name, python_type=python_type)
self._collect_type(graphql_scalar)
return graphql_scalar
def _collect_enum(self, enum: EnumDefinition) -> GraphQLEnum:
graphql_enum = GraphQLEnum(
enum.name,
[value.name for value in enum.values],
python_type=enum.wrapped_cls,
)
self._collect_type(graphql_enum)
return graphql_enum
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/codegen/query_codegen.py | query_codegen.py |
from .query_codegen import CodegenFile, CodegenResult, QueryCodegen, QueryCodegenPlugin
__all__ = ["QueryCodegen", "QueryCodegenPlugin", "CodegenFile", "CodegenResult"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/codegen/__init__.py | __init__.py |
class CodegenError(Exception):
pass
class NoOperationProvidedError(CodegenError):
pass
class NoOperationNameProvidedError(CodegenError):
pass
class MultipleOperationsProvidedError(CodegenError):
pass
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/codegen/exceptions.py | exceptions.py |
from __future__ import annotations
import textwrap
from typing import TYPE_CHECKING, List
from strawberry.codegen import CodegenFile, QueryCodegenPlugin
from strawberry.codegen.types import (
GraphQLEnum,
GraphQLList,
GraphQLObjectType,
GraphQLOptional,
GraphQLScalar,
GraphQLUnion,
)
if TYPE_CHECKING:
from strawberry.codegen.types import GraphQLField, GraphQLOperation, GraphQLType
class TypeScriptPlugin(QueryCodegenPlugin):
SCALARS_TO_TS_TYPE = {
"ID": "string",
"Int": "number",
"String": "string",
"Float": "number",
"Boolean": "boolean",
"UUID": "string",
"Date": "string",
"DateTime": "string",
"Time": "string",
"Decimal": "string",
str: "string",
float: "number",
}
def generate_code(
self, types: List[GraphQLType], operation: GraphQLOperation
) -> List[CodegenFile]:
printed_types = list(filter(None, (self._print_type(type) for type in types)))
return [CodegenFile("types.ts", "\n\n".join(printed_types))]
def _get_type_name(self, type_: GraphQLType) -> str:
if isinstance(type_, GraphQLOptional):
return f"{self._get_type_name(type_.of_type)} | undefined"
if isinstance(type_, GraphQLList):
child_type = self._get_type_name(type_.of_type)
if "|" in child_type:
child_type = f"({child_type})"
return f"{child_type}[]"
if isinstance(type_, GraphQLUnion):
return type_.name
if isinstance(type_, (GraphQLObjectType, GraphQLEnum)):
return type_.name
if isinstance(type_, GraphQLScalar) and type_.name in self.SCALARS_TO_TS_TYPE:
return self.SCALARS_TO_TS_TYPE[type_.name]
return type_.name
def _print_field(self, field: GraphQLField) -> str:
name = field.name
if field.alias:
name = f"// alias for {field.name}\n{field.alias}"
return f"{name}: {self._get_type_name(field.type)}"
def _print_enum_value(self, value: str) -> str:
return f'{value} = "{value}",'
def _print_object_type(self, type_: GraphQLObjectType) -> str:
fields = "\n".join(self._print_field(field) for field in type_.fields)
return "\n".join(
[f"type {type_.name} = {{", textwrap.indent(fields, " " * 4), "}"],
)
def _print_enum_type(self, type_: GraphQLEnum) -> str:
values = "\n".join(self._print_enum_value(value) for value in type_.values)
return "\n".join(
[
f"enum {type_.name} {{",
textwrap.indent(values, " " * 4),
"}",
]
)
def _print_scalar_type(self, type_: GraphQLScalar) -> str:
if type_.name in self.SCALARS_TO_TS_TYPE:
return ""
return f"type {type_.name} = {self.SCALARS_TO_TS_TYPE[type_.python_type]}"
def _print_union_type(self, type_: GraphQLUnion) -> str:
return f"type {type_.name} = {' | '.join([t.name for t in type_.types])}"
def _print_type(self, type_: GraphQLType) -> str:
if isinstance(type_, GraphQLUnion):
return self._print_union_type(type_)
if isinstance(type_, GraphQLObjectType):
return self._print_object_type(type_)
if isinstance(type_, GraphQLEnum):
return self._print_enum_type(type_)
if isinstance(type_, GraphQLScalar):
return self._print_scalar_type(type_)
raise ValueError(f"Unknown type: {type}") # pragma: no cover
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/codegen/plugins/typescript.py | typescript.py |
from __future__ import annotations
import textwrap
from collections import defaultdict
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Set
from strawberry.codegen import CodegenFile, QueryCodegenPlugin
from strawberry.codegen.types import (
GraphQLEnum,
GraphQLList,
GraphQLObjectType,
GraphQLOptional,
GraphQLScalar,
GraphQLUnion,
)
if TYPE_CHECKING:
from strawberry.codegen.types import GraphQLField, GraphQLOperation, GraphQLType
@dataclass
class PythonType:
type: str
module: Optional[str] = None
class PythonPlugin(QueryCodegenPlugin):
SCALARS_TO_PYTHON_TYPES = {
"ID": PythonType("str"),
"Int": PythonType("int"),
"String": PythonType("str"),
"Float": PythonType("float"),
"Boolean": PythonType("bool"),
"UUID": PythonType("UUID", "uuid"),
"Date": PythonType("date", "datetime"),
"DateTime": PythonType("datetime", "datetime"),
"Time": PythonType("time", "datetime"),
"Decimal": PythonType("Decimal", "decimal"),
}
def __init__(self) -> None:
self.imports: Dict[str, Set[str]] = defaultdict(set)
def generate_code(
self, types: List[GraphQLType], operation: GraphQLOperation
) -> List[CodegenFile]:
printed_types = list(filter(None, (self._print_type(type) for type in types)))
imports = self._print_imports()
code = imports + "\n\n" + "\n\n".join(printed_types)
return [CodegenFile("types.py", code.strip())]
def _print_imports(self) -> str:
imports = [
f'from {import_} import {", ".join(sorted(types))}'
for import_, types in self.imports.items()
]
return "\n".join(imports)
def _get_type_name(self, type_: GraphQLType) -> str:
if isinstance(type_, GraphQLOptional):
self.imports["typing"].add("Optional")
return f"Optional[{self._get_type_name(type_.of_type)}]"
if isinstance(type_, GraphQLList):
self.imports["typing"].add("List")
return f"List[{self._get_type_name(type_.of_type)}]"
if isinstance(type_, GraphQLUnion):
# TODO: wrong place for this
self.imports["typing"].add("Union")
return type_.name
if isinstance(type_, (GraphQLObjectType, GraphQLEnum)):
if isinstance(type_, GraphQLEnum):
self.imports["enum"].add("Enum")
return type_.name
if (
isinstance(type_, GraphQLScalar)
and type_.name in self.SCALARS_TO_PYTHON_TYPES
):
python_type = self.SCALARS_TO_PYTHON_TYPES[type_.name]
if python_type.module is not None:
self.imports[python_type.module].add(python_type.type)
return python_type.type
self.imports["typing"].add("NewType")
return type_.name
def _print_field(self, field: GraphQLField) -> str:
name = field.name
if field.alias:
name = f"# alias for {field.name}\n{field.alias}"
return f"{name}: {self._get_type_name(field.type)}"
def _print_enum_value(self, value: str) -> str:
return f'{value} = "{value}"'
def _print_object_type(self, type_: GraphQLObjectType) -> str:
fields = "\n".join(self._print_field(field) for field in type_.fields)
return "\n".join(
[
f"class {type_.name}:",
textwrap.indent(fields, " " * 4),
]
)
def _print_enum_type(self, type_: GraphQLEnum) -> str:
values = "\n".join(self._print_enum_value(value) for value in type_.values)
return "\n".join(
[
f"class {type_.name}(Enum):",
textwrap.indent(values, " " * 4),
]
)
def _print_scalar_type(self, type_: GraphQLScalar) -> str:
if type_.name in self.SCALARS_TO_PYTHON_TYPES:
return ""
assert (
type_.python_type is not None
), f"Scalar type must have a python type: {type_.name}"
return f'{type_.name} = NewType("{type_.name}", {type_.python_type.__name__})'
def _print_union_type(self, type_: GraphQLUnion) -> str:
return f"{type_.name} = Union[{', '.join([t.name for t in type_.types])}]"
def _print_type(self, type_: GraphQLType) -> str:
if isinstance(type_, GraphQLUnion):
return self._print_union_type(type_)
if isinstance(type_, GraphQLObjectType):
return self._print_object_type(type_)
if isinstance(type_, GraphQLEnum):
return self._print_enum_type(type_)
if isinstance(type_, GraphQLScalar):
return self._print_scalar_type(type_)
raise ValueError(f"Unknown type: {type}") # pragma: no cover
__all__ = ["PythonPlugin"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/codegen/plugins/python.py | python.py |
from __future__ import annotations
import textwrap
from typing import TYPE_CHECKING, List, Optional
from strawberry.codegen import CodegenFile, QueryCodegenPlugin
from strawberry.codegen.types import (
GraphQLBoolValue,
GraphQLEnumValue,
GraphQLFieldSelection,
GraphQLInlineFragment,
GraphQLIntValue,
GraphQLList,
GraphQLListValue,
GraphQLOptional,
GraphQLStringValue,
GraphQLVariableReference,
)
if TYPE_CHECKING:
from strawberry.codegen.types import (
GraphQLArgument,
GraphQLArgumentValue,
GraphQLDirective,
GraphQLOperation,
GraphQLSelection,
GraphQLType,
)
class PrintOperationPlugin(QueryCodegenPlugin):
def generate_code(
self, types: List[GraphQLType], operation: GraphQLOperation
) -> List[CodegenFile]:
code = "\n".join(
[
(
f"{operation.kind} {operation.name}"
f"{self._print_operation_variables(operation)}"
f"{self._print_directives(operation.directives)} {{"
),
self._print_selections(operation.selections),
"}",
]
)
return [CodegenFile("query.graphql", code)]
def _print_operation_variables(self, operation: GraphQLOperation) -> str:
if not operation.variables:
return ""
variables = ", ".join(
f"${v.name}: {self._print_graphql_type(v.type)}"
for v in operation.variables
)
return f"({variables})"
def _print_graphql_type(
self, type: GraphQLType, parent_type: Optional[GraphQLType] = None
) -> str:
if isinstance(type, GraphQLOptional):
return self._print_graphql_type(type.of_type, type)
if isinstance(type, GraphQLList):
type_name = f"[{self._print_graphql_type(type.of_type, type)}]"
else:
type_name = type.name
if parent_type and isinstance(parent_type, GraphQLOptional):
return type_name
return f"{type_name}!"
def _print_argument_value(self, value: GraphQLArgumentValue) -> str:
if isinstance(value, GraphQLStringValue):
return f'"{value.value}"'
if isinstance(value, GraphQLIntValue):
return str(value.value)
if isinstance(value, GraphQLVariableReference):
return f"${value.value}"
if isinstance(value, GraphQLListValue):
return f"[{', '.join(self._print_argument_value(v) for v in value.values)}]"
if isinstance(value, GraphQLEnumValue):
return value.name
if isinstance(value, GraphQLBoolValue):
return str(value.value).lower()
raise ValueError(f"not supported: {type(value)}") # pragma: no cover
def _print_arguments(self, arguments: List[GraphQLArgument]) -> str:
if not arguments:
return ""
return (
"("
+ ", ".join(
[
f"{argument.name}: {self._print_argument_value(argument.value)}"
for argument in arguments
]
)
+ ")"
)
def _print_directives(self, directives: List[GraphQLDirective]) -> str:
if not directives:
return ""
return " " + " ".join(
[
f"@{directive.name}{self._print_arguments(directive.arguments)}"
for directive in directives
]
)
def _print_field_selection(self, selection: GraphQLFieldSelection) -> str:
field = (
f"{selection.field}"
f"{self._print_arguments(selection.arguments)}"
f"{self._print_directives(selection.directives)}"
)
if selection.alias:
field = f"{selection.alias}: {field}"
if selection.selections:
return field + f" {{\n{self._print_selections(selection.selections)}\n}}"
return field
def _print_inline_fragment(self, fragment: GraphQLInlineFragment) -> str:
return "\n".join(
[
f"... on {fragment.type_condition} {{",
self._print_selections(fragment.selections),
"}",
]
)
def _print_selection(self, selection: GraphQLSelection) -> str:
if isinstance(selection, GraphQLFieldSelection):
return self._print_field_selection(selection)
if isinstance(selection, GraphQLInlineFragment):
return self._print_inline_fragment(selection)
raise ValueError(f"Unsupported selection: {selection}") # pragma: no cover
def _print_selections(self, selections: List[GraphQLSelection]) -> str:
selections_text = "\n".join(
[self._print_selection(selection) for selection in selections]
)
return textwrap.indent(selections_text, " " * 2)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/codegen/plugins/print_operation.py | print_operation.py |
try:
from . import pydantic
except ImportError:
pass
else:
__all__ = ["pydantic"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/experimental/__init__.py | __init__.py |
from __future__ import annotations
import dataclasses
import warnings
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
cast,
)
from pydantic import BaseModel
from pydantic.utils import lenient_issubclass
from strawberry.auto import StrawberryAuto
from strawberry.experimental.pydantic.utils import (
get_private_fields,
get_strawberry_type_from_model,
normalize_type,
)
from strawberry.object_type import _process_type, _wrap_dataclass
from strawberry.types.type_resolver import _get_fields
from strawberry.utils.typing import get_list_annotation, is_list
from .exceptions import MissingFieldsListError
if TYPE_CHECKING:
from pydantic.fields import ModelField
def get_type_for_field(field: ModelField) -> Union[Any, Type[None], Type[List]]:
type_ = field.outer_type_
type_ = normalize_type(type_)
return field_type_to_type(type_)
def field_type_to_type(type_) -> Union[Any, List[Any], None]:
error_class: Any = str
strawberry_type: Any = error_class
if is_list(type_):
child_type = get_list_annotation(type_)
if is_list(child_type):
strawberry_type = field_type_to_type(child_type)
elif lenient_issubclass(child_type, BaseModel):
strawberry_type = get_strawberry_type_from_model(child_type)
else:
strawberry_type = List[error_class]
strawberry_type = Optional[strawberry_type]
elif lenient_issubclass(type_, BaseModel):
strawberry_type = get_strawberry_type_from_model(type_)
return Optional[strawberry_type]
return Optional[List[strawberry_type]]
def error_type(
model: Type[BaseModel],
*,
fields: Optional[List[str]] = None,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
all_fields: bool = False,
) -> Callable[..., Type]:
def wrap(cls):
model_fields = model.__fields__
fields_set = set(fields) if fields else set()
if fields:
warnings.warn(
"`fields` is deprecated, use `auto` type annotations instead",
DeprecationWarning,
stacklevel=2,
)
existing_fields = getattr(cls, "__annotations__", {})
fields_set = fields_set.union(
{
name
for name, type_ in existing_fields.items()
if isinstance(type_, StrawberryAuto)
}
)
if all_fields:
if fields_set:
warnings.warn(
"Using all_fields overrides any explicitly defined fields "
"in the model, using both is likely a bug",
stacklevel=2,
)
fields_set = set(model_fields.keys())
if not fields_set:
raise MissingFieldsListError(cls)
all_model_fields: List[Tuple[str, Any, dataclasses.Field]] = [
(
name,
get_type_for_field(field),
dataclasses.field(default=None), # type: ignore[arg-type]
)
for name, field in model_fields.items()
if name in fields_set
]
wrapped = _wrap_dataclass(cls)
extra_fields = cast(List[dataclasses.Field], _get_fields(wrapped))
private_fields = get_private_fields(wrapped)
all_model_fields.extend(
(
field.name,
field.type,
field,
)
for field in extra_fields + private_fields
if not isinstance(field.type, StrawberryAuto)
)
cls = dataclasses.make_dataclass(
cls.__name__,
all_model_fields,
bases=cls.__bases__,
)
_process_type(
cls,
name=name,
is_input=False,
is_interface=False,
description=description,
directives=directives,
)
model._strawberry_type = cls # type: ignore[attr-defined]
cls._pydantic_type = model
return cls
return wrap
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/experimental/pydantic/error_type.py | error_type.py |
from __future__ import annotations
import dataclasses
import sys
import warnings
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Sequence,
Set,
Type,
cast,
)
from strawberry.annotation import StrawberryAnnotation
from strawberry.auto import StrawberryAuto
from strawberry.experimental.pydantic.conversion import (
convert_pydantic_model_to_strawberry_class,
convert_strawberry_class_to_pydantic_model,
)
from strawberry.experimental.pydantic.exceptions import MissingFieldsListError
from strawberry.experimental.pydantic.fields import replace_types_recursively
from strawberry.experimental.pydantic.utils import (
DataclassCreationFields,
ensure_all_auto_fields_in_pydantic,
get_default_factory_for_field,
get_private_fields,
)
from strawberry.field import StrawberryField
from strawberry.object_type import _process_type, _wrap_dataclass
from strawberry.types.type_resolver import _get_fields
from strawberry.utils.dataclasses import add_custom_init_fn
if TYPE_CHECKING:
from graphql import GraphQLResolveInfo
from pydantic.fields import ModelField
def get_type_for_field(field: ModelField, is_input: bool): # noqa: ANN201
outer_type = field.outer_type_
replaced_type = replace_types_recursively(outer_type, is_input)
default_defined: bool = (
field.default_factory is not None or field.default is not None
)
should_add_optional: bool = not (field.required or default_defined)
if should_add_optional:
return Optional[replaced_type]
else:
return replaced_type
def _build_dataclass_creation_fields(
field: ModelField,
is_input: bool,
existing_fields: Dict[str, StrawberryField],
auto_fields_set: Set[str],
use_pydantic_alias: bool,
) -> DataclassCreationFields:
field_type = (
get_type_for_field(field, is_input)
if field.name in auto_fields_set
else existing_fields[field.name].type
)
if (
field.name in existing_fields
and existing_fields[field.name].base_resolver is not None
):
# if the user has defined a resolver for this field, always use it
strawberry_field = existing_fields[field.name]
else:
# otherwise we build an appropriate strawberry field that resolves it
existing_field = existing_fields.get(field.name)
graphql_name = None
if existing_field and existing_field.graphql_name:
graphql_name = existing_field.graphql_name
elif field.has_alias and use_pydantic_alias:
graphql_name = field.alias
strawberry_field = StrawberryField(
python_name=field.name,
graphql_name=graphql_name,
# always unset because we use default_factory instead
default=dataclasses.MISSING,
default_factory=get_default_factory_for_field(field),
type_annotation=StrawberryAnnotation.from_annotation(field_type),
description=field.field_info.description,
deprecation_reason=(
existing_field.deprecation_reason if existing_field else None
),
permission_classes=(
existing_field.permission_classes if existing_field else []
),
directives=existing_field.directives if existing_field else (),
metadata=existing_field.metadata if existing_field else {},
)
return DataclassCreationFields(
name=field.name,
field_type=field_type,
field=strawberry_field,
)
if TYPE_CHECKING:
from strawberry.experimental.pydantic.conversion_types import (
PydanticModel,
StrawberryTypeFromPydantic,
)
def type(
model: Type[PydanticModel],
*,
fields: Optional[List[str]] = None,
name: Optional[str] = None,
is_input: bool = False,
is_interface: bool = False,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
all_fields: bool = False,
use_pydantic_alias: bool = True,
) -> Callable[..., Type[StrawberryTypeFromPydantic[PydanticModel]]]:
def wrap(cls: Any) -> Type[StrawberryTypeFromPydantic[PydanticModel]]:
model_fields = model.__fields__
original_fields_set = set(fields) if fields else set()
if fields:
warnings.warn(
"`fields` is deprecated, use `auto` type annotations instead",
DeprecationWarning,
stacklevel=2,
)
existing_fields = getattr(cls, "__annotations__", {})
# these are the fields that matched a field name in the pydantic model
# and should copy their alias from the pydantic model
fields_set = original_fields_set.union(
{name for name, _ in existing_fields.items() if name in model_fields}
)
# these are the fields that were marked with strawberry.auto and
# should copy their type from the pydantic model
auto_fields_set = original_fields_set.union(
{
name
for name, type_ in existing_fields.items()
if isinstance(type_, StrawberryAuto)
}
)
if all_fields:
if fields_set:
warnings.warn(
"Using all_fields overrides any explicitly defined fields "
"in the model, using both is likely a bug",
stacklevel=2,
)
fields_set = set(model_fields.keys())
auto_fields_set = set(model_fields.keys())
if not fields_set:
raise MissingFieldsListError(cls)
ensure_all_auto_fields_in_pydantic(
model=model, auto_fields=auto_fields_set, cls_name=cls.__name__
)
wrapped = _wrap_dataclass(cls)
extra_strawberry_fields = _get_fields(wrapped)
extra_fields = cast(List[dataclasses.Field], extra_strawberry_fields)
private_fields = get_private_fields(wrapped)
extra_fields_dict = {field.name: field for field in extra_strawberry_fields}
all_model_fields: List[DataclassCreationFields] = [
_build_dataclass_creation_fields(
field, is_input, extra_fields_dict, auto_fields_set, use_pydantic_alias
)
for field_name, field in model_fields.items()
if field_name in fields_set
]
all_model_fields = [
DataclassCreationFields(
name=field.name,
field_type=field.type,
field=field,
)
for field in extra_fields + private_fields
if field.name not in fields_set
] + all_model_fields
# Implicitly define `is_type_of` to support interfaces/unions that use
# pydantic objects (not the corresponding strawberry type)
@classmethod # type: ignore
def is_type_of(cls: Type, obj: Any, _info: GraphQLResolveInfo) -> bool:
return isinstance(obj, (cls, model))
namespace = {"is_type_of": is_type_of}
# We need to tell the difference between a from_pydantic method that is
# inherited from a base class and one that is defined by the user in the
# decorated class. We want to override the method only if it is
# inherited. To tell the difference, we compare the class name to the
# fully qualified name of the method, which will end in <class>.from_pydantic
has_custom_from_pydantic = hasattr(
cls, "from_pydantic"
) and cls.from_pydantic.__qualname__.endswith(f"{cls.__name__}.from_pydantic")
has_custom_to_pydantic = hasattr(
cls, "to_pydantic"
) and cls.to_pydantic.__qualname__.endswith(f"{cls.__name__}.to_pydantic")
if has_custom_from_pydantic:
namespace["from_pydantic"] = cls.from_pydantic
if has_custom_to_pydantic:
namespace["to_pydantic"] = cls.to_pydantic
if hasattr(cls, "resolve_reference"):
namespace["resolve_reference"] = cls.resolve_reference
kwargs: Dict[str, object] = {}
# Python 3.10.1 introduces the kw_only param to `make_dataclass`.
# If we're on an older version then generate our own custom init function
# Note: Python 3.10.0 added the `kw_only` param to dataclasses, it was
# just missed from the `make_dataclass` function:
# https://github.com/python/cpython/issues/89961
if sys.version_info >= (3, 10, 1):
kwargs["kw_only"] = dataclasses.MISSING
else:
kwargs["init"] = False
cls = dataclasses.make_dataclass(
cls.__name__,
[field.to_tuple() for field in all_model_fields],
bases=cls.__bases__,
namespace=namespace,
**kwargs, # type: ignore
)
if sys.version_info < (3, 10, 1):
add_custom_init_fn(cls)
_process_type(
cls,
name=name,
is_input=is_input,
is_interface=is_interface,
description=description,
directives=directives,
)
if is_input:
model._strawberry_input_type = cls # type: ignore
else:
model._strawberry_type = cls # type: ignore
cls._pydantic_type = model
def from_pydantic_default(
instance: PydanticModel, extra: Optional[Dict[str, Any]] = None
) -> StrawberryTypeFromPydantic[PydanticModel]:
return convert_pydantic_model_to_strawberry_class(
cls=cls, model_instance=instance, extra=extra
)
def to_pydantic_default(self, **kwargs) -> PydanticModel:
instance_kwargs = {
f.name: convert_strawberry_class_to_pydantic_model(
getattr(self, f.name)
)
for f in dataclasses.fields(self)
}
instance_kwargs.update(kwargs)
return model(**instance_kwargs)
if not has_custom_from_pydantic:
cls.from_pydantic = staticmethod(from_pydantic_default)
if not has_custom_to_pydantic:
cls.to_pydantic = to_pydantic_default
return cls
return wrap
def input(
model: Type[PydanticModel],
*,
fields: Optional[List[str]] = None,
name: Optional[str] = None,
is_interface: bool = False,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
all_fields: bool = False,
use_pydantic_alias: bool = True,
) -> Callable[..., Type[StrawberryTypeFromPydantic[PydanticModel]]]:
"""Convenience decorator for creating an input type from a Pydantic model.
Equal to partial(type, is_input=True)
See https://github.com/strawberry-graphql/strawberry/issues/1830
"""
return type(
model=model,
fields=fields,
name=name,
is_input=True,
is_interface=is_interface,
description=description,
directives=directives,
all_fields=all_fields,
use_pydantic_alias=use_pydantic_alias,
)
def interface(
model: Type[PydanticModel],
*,
fields: Optional[List[str]] = None,
name: Optional[str] = None,
is_input: bool = False,
description: Optional[str] = None,
directives: Optional[Sequence[object]] = (),
all_fields: bool = False,
use_pydantic_alias: bool = True,
) -> Callable[..., Type[StrawberryTypeFromPydantic[PydanticModel]]]:
"""Convenience decorator for creating an interface type from a Pydantic model.
Equal to partial(type, is_interface=True)
See https://github.com/strawberry-graphql/strawberry/issues/1830
"""
return type(
model=model,
fields=fields,
name=name,
is_input=is_input,
is_interface=True,
description=description,
directives=directives,
all_fields=all_fields,
use_pydantic_alias=use_pydantic_alias,
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/experimental/pydantic/object_type.py | object_type.py |
from __future__ import annotations
import dataclasses
from typing import (
TYPE_CHECKING,
Any,
List,
NamedTuple,
NoReturn,
Set,
Tuple,
Type,
Union,
cast,
)
from pydantic.utils import smart_deepcopy
from strawberry.experimental.pydantic.exceptions import (
AutoFieldsNotInBaseModelError,
BothDefaultAndDefaultFactoryDefinedError,
UnregisteredTypeException,
)
from strawberry.private import is_private
from strawberry.unset import UNSET
from strawberry.utils.typing import (
get_list_annotation,
get_optional_annotation,
is_list,
is_optional,
)
if TYPE_CHECKING:
from pydantic import BaseModel
from pydantic.fields import ModelField
from pydantic.typing import NoArgAnyCallable
def normalize_type(type_) -> Any:
if is_list(type_):
return List[normalize_type(get_list_annotation(type_))] # type: ignore
if is_optional(type_):
return get_optional_annotation(type_)
return type_
def get_strawberry_type_from_model(type_: Any) -> Any:
if hasattr(type_, "_strawberry_type"):
return type_._strawberry_type
else:
raise UnregisteredTypeException(type_)
def get_private_fields(cls: Type) -> List[dataclasses.Field]:
private_fields: List[dataclasses.Field] = []
for field in dataclasses.fields(cls):
if is_private(field.type):
private_fields.append(field)
return private_fields
class DataclassCreationFields(NamedTuple):
"""Fields required for the fields parameter of make_dataclass"""
name: str
field_type: Type
field: dataclasses.Field
def to_tuple(self) -> Tuple[str, Type, dataclasses.Field]:
# fields parameter wants (name, type, Field)
return self.name, self.field_type, self.field
def get_default_factory_for_field(
field: ModelField,
) -> Union[NoArgAnyCallable, dataclasses._MISSING_TYPE]:
"""
Gets the default factory for a pydantic field.
Handles mutable defaults when making the dataclass by
using pydantic's smart_deepcopy
Returns optionally a NoArgAnyCallable representing a default_factory parameter
"""
# replace dataclasses.MISSING with our own UNSET to make comparisons easier
default_factory = (
field.default_factory
if field.default_factory is not dataclasses.MISSING
else UNSET
)
default = field.default if field.default is not dataclasses.MISSING else UNSET
has_factory = default_factory is not None and default_factory is not UNSET
has_default = default is not None and default is not UNSET
# defining both default and default_factory is not supported
if has_factory and has_default:
default_factory = cast("NoArgAnyCallable", default_factory)
raise BothDefaultAndDefaultFactoryDefinedError(
default=default, default_factory=default_factory
)
# if we have a default_factory, we should return it
if has_factory:
default_factory = cast("NoArgAnyCallable", default_factory)
return default_factory
# if we have a default, we should return it
if has_default:
return lambda: smart_deepcopy(default)
# if we don't have default or default_factory, but the field is not required,
# we should return a factory that returns None
if not field.required:
return lambda: None
return dataclasses.MISSING
def ensure_all_auto_fields_in_pydantic(
model: Type[BaseModel], auto_fields: Set[str], cls_name: str
) -> Union[NoReturn, None]:
# Raise error if user defined a strawberry.auto field not present in the model
non_existing_fields = list(auto_fields - model.__fields__.keys())
if non_existing_fields:
raise AutoFieldsNotInBaseModelError(
fields=non_existing_fields, cls_name=cls_name, model=model
)
else:
return None
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/experimental/pydantic/utils.py | utils.py |
from __future__ import annotations
import copy
import dataclasses
from typing import TYPE_CHECKING, Any, Union, cast
from strawberry.enum import EnumDefinition
from strawberry.type import StrawberryList, StrawberryOptional
from strawberry.union import StrawberryUnion
if TYPE_CHECKING:
from strawberry.field import StrawberryField
from strawberry.type import StrawberryType
def _convert_from_pydantic_to_strawberry_type(
type_: Union[StrawberryType, type], data_from_model=None, extra=None
):
data = data_from_model if data_from_model is not None else extra
if isinstance(type_, StrawberryOptional):
if data is None:
return data
return _convert_from_pydantic_to_strawberry_type(
type_.of_type, data_from_model=data, extra=extra
)
if isinstance(type_, StrawberryUnion):
for option_type in type_.types:
if hasattr(option_type, "_pydantic_type"):
source_type = option_type._pydantic_type
else:
source_type = cast(type, option_type)
if isinstance(data, source_type):
return _convert_from_pydantic_to_strawberry_type(
option_type, data_from_model=data, extra=extra
)
if isinstance(type_, EnumDefinition):
return data
if isinstance(type_, StrawberryList):
items = []
for index, item in enumerate(data):
items.append(
_convert_from_pydantic_to_strawberry_type(
type_.of_type,
data_from_model=item,
extra=extra[index] if extra else None,
)
)
return items
if hasattr(type_, "_type_definition"):
# in the case of an interface, the concrete type may be more specific
# than the type in the field definition
# don't check _strawberry_input_type because inputs can't be interfaces
if hasattr(type(data), "_strawberry_type"):
type_ = type(data)._strawberry_type
if hasattr(type_, "from_pydantic"):
return type_.from_pydantic(data_from_model, extra)
return convert_pydantic_model_to_strawberry_class(
type_, model_instance=data_from_model, extra=extra
)
return data
def convert_pydantic_model_to_strawberry_class(
cls, *, model_instance=None, extra=None
) -> Any:
extra = extra or {}
kwargs = {}
for field_ in cls._type_definition.fields:
field = cast("StrawberryField", field_)
python_name = field.python_name
data_from_extra = extra.get(python_name, None)
data_from_model = (
getattr(model_instance, python_name, None) if model_instance else None
)
# only convert and add fields to kwargs if they are present in the `__init__`
# method of the class
if field.init:
kwargs[python_name] = _convert_from_pydantic_to_strawberry_type(
field.type, data_from_model, extra=data_from_extra
)
return cls(**kwargs)
def convert_strawberry_class_to_pydantic_model(obj) -> Any:
if hasattr(obj, "to_pydantic"):
return obj.to_pydantic()
elif dataclasses.is_dataclass(obj):
result = []
for f in dataclasses.fields(obj):
value = convert_strawberry_class_to_pydantic_model(getattr(obj, f.name))
result.append((f.name, value))
return dict(result)
elif isinstance(obj, (list, tuple)):
# Assume we can create an object of this type by passing in a
# generator (which is not true for namedtuples, not supported).
return type(obj)(convert_strawberry_class_to_pydantic_model(v) for v in obj)
elif isinstance(obj, dict):
return type(obj)(
(
convert_strawberry_class_to_pydantic_model(k),
convert_strawberry_class_to_pydantic_model(v),
)
for k, v in obj.items()
)
else:
return copy.deepcopy(obj)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/experimental/pydantic/conversion.py | conversion.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Optional, TypeVar
from typing_extensions import Protocol
from pydantic import BaseModel
if TYPE_CHECKING:
from strawberry.types.types import TypeDefinition
PydanticModel = TypeVar("PydanticModel", bound=BaseModel)
class StrawberryTypeFromPydantic(Protocol[PydanticModel]):
"""This class does not exist in runtime.
It only makes the methods below visible for IDEs"""
def __init__(self, **kwargs):
...
@staticmethod
def from_pydantic(
instance: PydanticModel, extra: Optional[Dict[str, Any]] = None
) -> StrawberryTypeFromPydantic[PydanticModel]:
...
def to_pydantic(self, **kwargs) -> PydanticModel:
...
@property
def _type_definition(self) -> TypeDefinition:
...
@property
def _pydantic_type(self) -> PydanticModel:
...
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/experimental/pydantic/conversion_types.py | conversion_types.py |
from .error_type import error_type
from .exceptions import UnregisteredTypeException
from .object_type import input, interface, type
__all__ = [
"error_type",
"UnregisteredTypeException",
"input",
"type",
"interface",
]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/experimental/pydantic/__init__.py | __init__.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Type
if TYPE_CHECKING:
from pydantic import BaseModel
from pydantic.typing import NoArgAnyCallable
class MissingFieldsListError(Exception):
def __init__(self, type: Type[BaseModel]):
message = (
f"List of fields to copy from {type} is empty. Add fields with the "
f"`auto` type annotation"
)
super().__init__(message)
class UnsupportedTypeError(Exception):
pass
class UnregisteredTypeException(Exception):
def __init__(self, type: Type[BaseModel]):
message = (
f"Cannot find a Strawberry Type for {type} did you forget to register it?"
)
super().__init__(message)
class BothDefaultAndDefaultFactoryDefinedError(Exception):
def __init__(self, default: Any, default_factory: NoArgAnyCallable):
message = (
f"Not allowed to specify both default and default_factory. "
f"default:{default} default_factory:{default_factory}"
)
super().__init__(message)
class AutoFieldsNotInBaseModelError(Exception):
def __init__(self, fields: List[str], cls_name: str, model: Type[BaseModel]):
message = (
f"{cls_name} defines {fields} with strawberry.auto. "
f"Field(s) not present in {model.__name__} BaseModel."
)
super().__init__(message)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/experimental/pydantic/exceptions.py | exceptions.py |
import builtins
from decimal import Decimal
from typing import Any, List, Optional, Type
from uuid import UUID
import pydantic
from pydantic import BaseModel
from pydantic.typing import get_args, get_origin, is_new_type, new_type_supertype
from pydantic.utils import lenient_issubclass
from strawberry.experimental.pydantic.exceptions import (
UnregisteredTypeException,
UnsupportedTypeError,
)
from strawberry.types.types import TypeDefinition
try:
from typing import GenericAlias as TypingGenericAlias # type: ignore
except ImportError:
# python < 3.9 does not have GenericAlias (list[int], tuple[str, ...] and so on)
TypingGenericAlias = ()
ATTR_TO_TYPE_MAP = {
"NoneStr": Optional[str],
"NoneBytes": Optional[bytes],
"StrBytes": None,
"NoneStrBytes": None,
"StrictStr": str,
"ConstrainedBytes": bytes,
"conbytes": bytes,
"ConstrainedStr": str,
"constr": str,
"EmailStr": str,
"PyObject": None,
"ConstrainedInt": int,
"conint": int,
"PositiveInt": int,
"NegativeInt": int,
"ConstrainedFloat": float,
"confloat": float,
"PositiveFloat": float,
"NegativeFloat": float,
"ConstrainedDecimal": Decimal,
"condecimal": Decimal,
"UUID1": UUID,
"UUID3": UUID,
"UUID4": UUID,
"UUID5": UUID,
"FilePath": None,
"DirectoryPath": None,
"Json": None,
"JsonWrapper": None,
"SecretStr": str,
"SecretBytes": bytes,
"StrictBool": bool,
"StrictInt": int,
"StrictFloat": float,
"PaymentCardNumber": None,
"ByteSize": None,
"AnyUrl": str,
"AnyHttpUrl": str,
"HttpUrl": str,
"PostgresDsn": str,
"RedisDsn": str,
}
FIELDS_MAP = {
getattr(pydantic, field_name): type
for field_name, type in ATTR_TO_TYPE_MAP.items()
if hasattr(pydantic, field_name)
}
def get_basic_type(type_) -> Type[Any]:
if lenient_issubclass(type_, pydantic.ConstrainedInt):
return int
if lenient_issubclass(type_, pydantic.ConstrainedFloat):
return float
if lenient_issubclass(type_, pydantic.ConstrainedStr):
return str
if lenient_issubclass(type_, pydantic.ConstrainedList):
return List[get_basic_type(type_.item_type)] # type: ignore
if type_ in FIELDS_MAP:
type_ = FIELDS_MAP.get(type_)
if type_ is None:
raise UnsupportedTypeError()
if is_new_type(type_):
return new_type_supertype(type_)
return type_
def replace_pydantic_types(type_: Any, is_input: bool) -> Any:
if lenient_issubclass(type_, BaseModel):
attr = "_strawberry_input_type" if is_input else "_strawberry_type"
if hasattr(type_, attr):
return getattr(type_, attr)
else:
raise UnregisteredTypeException(type_)
return type_
def replace_types_recursively(type_: Any, is_input: bool) -> Any:
"""Runs the conversions recursively into the arguments of generic types if any"""
basic_type = get_basic_type(type_)
replaced_type = replace_pydantic_types(basic_type, is_input)
origin = get_origin(type_)
if not origin or not hasattr(type_, "__args__"):
return replaced_type
converted = tuple(
replace_types_recursively(t, is_input=is_input) for t in get_args(replaced_type)
)
if isinstance(replaced_type, TypingGenericAlias):
return TypingGenericAlias(origin, converted)
replaced_type = replaced_type.copy_with(converted)
if isinstance(replaced_type, TypeDefinition):
# TODO: Not sure if this is necessary. No coverage in tests
# TODO: Unnecessary with StrawberryObject
replaced_type = builtins.type(
replaced_type.name,
(),
{"_type_definition": replaced_type},
)
return replaced_type
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/experimental/pydantic/fields.py | fields.py |
from functools import lru_cache
from typing import Iterator, Optional
from strawberry.extensions.base_extension import SchemaExtension
from strawberry.schema.execute import parse_document
class ParserCache(SchemaExtension):
"""
Add LRU caching the parsing step during execution to improve performance.
Example:
>>> import strawberry
>>> from strawberry.extensions import ParserCache
>>>
>>> schema = strawberry.Schema(
... Query,
... extensions=[
... ParserCache(maxsize=100),
... ]
... )
Arguments:
`maxsize: Optional[int]`
Set the maxsize of the cache. If `maxsize` is set to `None` then the
cache will grow without bound.
More info: https://docs.python.org/3/library/functools.html#functools.lru_cache
"""
def __init__(self, maxsize: Optional[int] = None):
self.cached_parse_document = lru_cache(maxsize=maxsize)(parse_document)
def on_parse(self) -> Iterator[None]:
execution_context = self.execution_context
execution_context.graphql_document = self.cached_parse_document(
execution_context.query,
)
yield
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/parser_cache.py | parser_cache.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Iterator, List, Type
from strawberry.extensions.base_extension import SchemaExtension
if TYPE_CHECKING:
from graphql import ASTValidationRule
class AddValidationRules(SchemaExtension):
"""
Add graphql-core validation rules
Example:
>>> import strawberry
>>> from strawberry.extensions import AddValidationRules
>>> from graphql import ValidationRule, GraphQLError
>>>
>>> class MyCustomRule(ValidationRule):
... def enter_field(self, node, *args) -> None:
... if node.name.value == "secret_field":
... self.report_error(
... GraphQLError("Can't query field 'secret_field'")
... )
>>>
>>> schema = strawberry.Schema(
... Query,
... extensions=[
... AddValidationRules([
... MyCustomRule,
... ]),
... ]
... )
"""
validation_rules: List[Type[ASTValidationRule]]
def __init__(self, validation_rules: List[Type[ASTValidationRule]]):
self.validation_rules = validation_rules
def on_operation(self) -> Iterator[None]:
self.execution_context.validation_rules = (
self.execution_context.validation_rules + tuple(self.validation_rules)
)
yield
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/add_validation_rules.py | add_validation_rules.py |
from __future__ import annotations
import contextlib
import inspect
import warnings
from asyncio import iscoroutinefunction
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Callable,
Iterator,
List,
NamedTuple,
Optional,
Type,
Union,
)
from strawberry.extensions import SchemaExtension
from strawberry.utils.await_maybe import AwaitableOrValue, await_maybe
if TYPE_CHECKING:
from types import TracebackType
from strawberry.extensions.base_extension import Hook
class WrappedHook(NamedTuple):
extension: SchemaExtension
initialized_hook: Union[AsyncIterator[None], Iterator[None]]
is_async: bool
class ExtensionContextManagerBase:
__slots__ = ("hooks", "deprecation_message", "default_hook")
def __init_subclass__(cls):
cls.DEPRECATION_MESSAGE = (
f"Event driven styled extensions for "
f"{cls.LEGACY_ENTER} or {cls.LEGACY_EXIT}"
f" are deprecated, use {cls.HOOK_NAME} instead"
)
HOOK_NAME: str
DEPRECATION_MESSAGE: str
LEGACY_ENTER: str
LEGACY_EXIT: str
def __init__(self, extensions: List[SchemaExtension]):
self.hooks: List[WrappedHook] = []
self.default_hook: Hook = getattr(SchemaExtension, self.HOOK_NAME)
for extension in extensions:
hook = self.get_hook(extension)
if hook:
self.hooks.append(hook)
def get_hook(self, extension: SchemaExtension) -> Optional[WrappedHook]:
on_start = getattr(extension, self.LEGACY_ENTER, None)
on_end = getattr(extension, self.LEGACY_EXIT, None)
is_legacy = on_start is not None or on_end is not None
hook_fn: Optional[Hook] = getattr(type(extension), self.HOOK_NAME)
hook_fn = hook_fn if hook_fn is not self.default_hook else None
if is_legacy and hook_fn is not None:
raise ValueError(
f"{extension} defines both legacy and new style extension hooks for "
"{self.HOOK_NAME}"
)
elif is_legacy:
warnings.warn(self.DEPRECATION_MESSAGE, DeprecationWarning, stacklevel=3)
return self.from_legacy(extension, on_start, on_end)
if hook_fn:
if inspect.isgeneratorfunction(hook_fn):
return WrappedHook(extension, hook_fn(extension), False)
if inspect.isasyncgenfunction(hook_fn):
return WrappedHook(extension, hook_fn(extension), True)
if callable(hook_fn):
return self.from_callable(extension, hook_fn)
raise ValueError(
f"Hook {self.HOOK_NAME} on {extension} "
f"must be callable, received {hook_fn!r}"
)
return None # Current extension does not define a hook for this lifecycle stage
@staticmethod
def from_legacy(
extension: SchemaExtension,
on_start: Optional[Callable[[], None]] = None,
on_end: Optional[Callable[[], None]] = None,
) -> WrappedHook:
if iscoroutinefunction(on_start) or iscoroutinefunction(on_end):
async def iterator():
if on_start:
await await_maybe(on_start())
yield
if on_end:
await await_maybe(on_end())
hook = iterator()
return WrappedHook(extension, hook, True)
else:
def iterator():
if on_start:
on_start()
yield
if on_end:
on_end()
hook = iterator()
return WrappedHook(extension, hook, False)
@staticmethod
def from_callable(
extension: SchemaExtension,
func: Callable[[SchemaExtension], AwaitableOrValue[Any]],
) -> WrappedHook:
if iscoroutinefunction(func):
async def async_iterator():
await func(extension)
yield
hook = async_iterator()
return WrappedHook(extension, hook, True)
else:
def iterator():
func(extension)
yield
hook = iterator()
return WrappedHook(extension, hook, False)
def run_hooks_sync(self, is_exit: bool = False) -> None:
"""Run extensions synchronously."""
ctx = (
contextlib.suppress(StopIteration, StopAsyncIteration)
if is_exit
else contextlib.nullcontext()
)
for hook in self.hooks:
with ctx:
if hook.is_async:
raise RuntimeError(
f"SchemaExtension hook {hook.extension}.{self.HOOK_NAME} "
"failed to complete synchronously."
)
else:
hook.initialized_hook.__next__() # type: ignore[union-attr]
async def run_hooks_async(self, is_exit: bool = False) -> None:
"""Run extensions asynchronously with support for sync lifecycle hooks.
The ``is_exit`` flag is required as a `StopIteration` cannot be raised from
within a coroutine.
"""
ctx = (
contextlib.suppress(StopIteration, StopAsyncIteration)
if is_exit
else contextlib.nullcontext()
)
for hook in self.hooks:
with ctx:
if hook.is_async:
await hook.initialized_hook.__anext__() # type: ignore[union-attr]
else:
hook.initialized_hook.__next__() # type: ignore[union-attr]
def __enter__(self):
self.run_hooks_sync()
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
):
self.run_hooks_sync(is_exit=True)
async def __aenter__(self):
await self.run_hooks_async()
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
):
await self.run_hooks_async(is_exit=True)
class OperationContextManager(ExtensionContextManagerBase):
HOOK_NAME = SchemaExtension.on_operation.__name__
LEGACY_ENTER = "on_request_start"
LEGACY_EXIT = "on_request_end"
class ValidationContextManager(ExtensionContextManagerBase):
HOOK_NAME = SchemaExtension.on_validate.__name__
LEGACY_ENTER = "on_validation_start"
LEGACY_EXIT = "on_validation_end"
class ParsingContextManager(ExtensionContextManagerBase):
HOOK_NAME = SchemaExtension.on_parse.__name__
LEGACY_ENTER = "on_parsing_start"
LEGACY_EXIT = "on_parsing_end"
class ExecutingContextManager(ExtensionContextManagerBase):
HOOK_NAME = SchemaExtension.on_execute.__name__
LEGACY_ENTER = "on_executing_start"
LEGACY_EXIT = "on_executing_end"
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/context.py | context.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Dict, Set
from strawberry.utils.await_maybe import AsyncIteratorOrIterator, AwaitableOrValue
if TYPE_CHECKING:
from graphql import GraphQLResolveInfo
from strawberry.types import ExecutionContext
class SchemaExtension:
execution_context: ExecutionContext
def __init__(self, *, execution_context: ExecutionContext):
self.execution_context = execution_context
def on_operation(
self,
) -> AsyncIteratorOrIterator[None]: # pragma: no cover # pyright: ignore
"""Called before and after a GraphQL operation (query / mutation) starts"""
yield None
def on_validate(
self,
) -> AsyncIteratorOrIterator[None]: # pragma: no cover # pyright: ignore
"""Called before and after the validation step"""
yield None
def on_parse(
self,
) -> AsyncIteratorOrIterator[None]: # pragma: no cover # pyright: ignore
"""Called before and after the parsing step"""
yield None
def on_execute(
self,
) -> AsyncIteratorOrIterator[None]: # pragma: no cover # pyright: ignore
"""Called before and after the execution step"""
yield None
def resolve(
self, _next, root, info: GraphQLResolveInfo, *args, **kwargs
) -> AwaitableOrValue[object]:
return _next(root, info, *args, **kwargs)
def get_results(self) -> AwaitableOrValue[Dict[str, Any]]:
return {}
Hook = Callable[[SchemaExtension], AsyncIteratorOrIterator[None]]
HOOK_METHODS: Set[str] = {
SchemaExtension.on_operation.__name__,
SchemaExtension.on_validate.__name__,
SchemaExtension.on_parse.__name__,
SchemaExtension.on_execute.__name__,
}
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/base_extension.py | base_extension.py |
from functools import lru_cache
from typing import Iterator, Optional
from strawberry.extensions.base_extension import SchemaExtension
from strawberry.schema.execute import validate_document
class ValidationCache(SchemaExtension):
"""
Add LRU caching the validation step during execution to improve performance.
Example:
>>> import strawberry
>>> from strawberry.extensions import ValidationCache
>>>
>>> schema = strawberry.Schema(
... Query,
... extensions=[
... ValidationCache(maxsize=100),
... ]
... )
Arguments:
`maxsize: Optional[int]`
Set the maxsize of the cache. If `maxsize` is set to `None` then the
cache will grow without bound.
More info: https://docs.python.org/3/library/functools.html#functools.lru_cache
"""
def __init__(self, maxsize: Optional[int] = None):
self.cached_validate_document = lru_cache(maxsize=maxsize)(validate_document)
def on_validate(self) -> Iterator[None]:
execution_context = self.execution_context
errors = self.cached_validate_document(
execution_context.schema._schema,
execution_context.graphql_document,
execution_context.validation_rules,
)
execution_context.errors = errors
yield
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/validation_cache.py | validation_cache.py |
from __future__ import annotations
import inspect
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union
from graphql import MiddlewareManager
from strawberry.extensions.context import (
ExecutingContextManager,
OperationContextManager,
ParsingContextManager,
ValidationContextManager,
)
from strawberry.utils.await_maybe import await_maybe
from . import SchemaExtension
if TYPE_CHECKING:
from strawberry.types import ExecutionContext
class SchemaExtensionsRunner:
extensions: List[SchemaExtension]
def __init__(
self,
execution_context: ExecutionContext,
extensions: Optional[
List[Union[Type[SchemaExtension], SchemaExtension]]
] = None,
):
self.execution_context = execution_context
if not extensions:
extensions = []
init_extensions: List[SchemaExtension] = []
for extension in extensions:
# If the extension has already been instantiated then set the
# `execution_context` attribute
if isinstance(extension, SchemaExtension):
extension.execution_context = execution_context
init_extensions.append(extension)
else:
init_extensions.append(extension(execution_context=execution_context))
self.extensions = init_extensions
def operation(self) -> OperationContextManager:
return OperationContextManager(self.extensions)
def validation(self) -> ValidationContextManager:
return ValidationContextManager(self.extensions)
def parsing(self) -> ParsingContextManager:
return ParsingContextManager(self.extensions)
def executing(self) -> ExecutingContextManager:
return ExecutingContextManager(self.extensions)
def get_extensions_results_sync(self) -> Dict[str, Any]:
data: Dict[str, Any] = {}
for extension in self.extensions:
if inspect.iscoroutinefunction(extension.get_results):
msg = "Cannot use async extension hook during sync execution"
raise RuntimeError(msg)
data.update(extension.get_results()) # type: ignore
return data
async def get_extensions_results(self) -> Dict[str, Any]:
data: Dict[str, Any] = {}
for extension in self.extensions:
results = await await_maybe(extension.get_results())
data.update(results)
return data
def as_middleware_manager(self, *additional_middlewares) -> MiddlewareManager:
middlewares = tuple(self.extensions) + additional_middlewares
return MiddlewareManager(*middlewares)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/runner.py | runner.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Tuple
from strawberry.extensions import SchemaExtension
from strawberry.types import Info
from strawberry.types.nodes import convert_arguments
from strawberry.utils.await_maybe import await_maybe
if TYPE_CHECKING:
from graphql import DirectiveNode, GraphQLResolveInfo
from strawberry.directive import StrawberryDirective
from strawberry.field import StrawberryField
from strawberry.schema.schema import Schema
from strawberry.utils.await_maybe import AwaitableOrValue
SPECIFIED_DIRECTIVES = {"include", "skip"}
class DirectivesExtension(SchemaExtension):
async def resolve(
self, _next, root, info: GraphQLResolveInfo, *args, **kwargs
) -> AwaitableOrValue[Any]:
value = await await_maybe(_next(root, info, *args, **kwargs))
for directive in info.field_nodes[0].directives:
if directive.name.value in SPECIFIED_DIRECTIVES:
continue
strawberry_directive, arguments = process_directive(directive, value, info)
value = await await_maybe(strawberry_directive.resolver(**arguments))
return value
class DirectivesExtensionSync(SchemaExtension):
def resolve(
self, _next, root, info: GraphQLResolveInfo, *args, **kwargs
) -> AwaitableOrValue[Any]:
value = _next(root, info, *args, **kwargs)
for directive in info.field_nodes[0].directives:
if directive.name.value in SPECIFIED_DIRECTIVES:
continue
strawberry_directive, arguments = process_directive(directive, value, info)
value = strawberry_directive.resolver(**arguments)
return value
def process_directive(
directive: DirectiveNode,
value: Any,
info: GraphQLResolveInfo,
) -> Tuple[StrawberryDirective, Dict[str, Any]]:
"""Get a `StrawberryDirective` from ``directive` and prepare its arguments."""
directive_name = directive.name.value
schema: Schema = info.schema._strawberry_schema # type: ignore
strawberry_directive = schema.get_directive_by_name(directive_name)
assert strawberry_directive is not None, f"Directive {directive_name} not found"
arguments = convert_arguments(info=info, nodes=directive.arguments)
resolver = strawberry_directive.resolver
info_parameter = resolver.info_parameter
value_parameter = resolver.value_parameter
if info_parameter:
field: StrawberryField = schema.get_field_for_type( # type: ignore
field_name=info.field_name,
type_name=info.parent_type.name,
)
arguments[info_parameter.name] = Info(_raw_info=info, _field=field)
if value_parameter:
arguments[value_parameter.name] = value
return strawberry_directive, arguments
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/directives.py | directives.py |
from typing import Callable, Iterator
from graphql.error import GraphQLError
from strawberry.extensions.base_extension import SchemaExtension
def default_should_mask_error(_) -> bool:
# Mask all errors
return True
class MaskErrors(SchemaExtension):
should_mask_error: Callable[[GraphQLError], bool]
error_message: str
def __init__(
self,
should_mask_error: Callable[[GraphQLError], bool] = default_should_mask_error,
error_message: str = "Unexpected error.",
):
self.should_mask_error = should_mask_error
self.error_message = error_message
def anonymise_error(self, error: GraphQLError) -> GraphQLError:
return GraphQLError(
message=self.error_message,
nodes=error.nodes,
source=error.source,
positions=error.positions,
path=error.path,
original_error=None,
)
def on_operation(self) -> Iterator[None]:
yield
result = self.execution_context.result
if result and result.errors:
processed_errors = []
for error in result.errors:
if self.should_mask_error(error):
processed_errors.append(self.anonymise_error(error))
else:
processed_errors.append(error)
result.errors = processed_errors
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/mask_errors.py | mask_errors.py |
from __future__ import annotations
from typing import TYPE_CHECKING, List, Union
if TYPE_CHECKING:
from graphql import GraphQLResolveInfo
def is_introspection_key(key: Union[str, int]) -> bool:
# from: https://spec.graphql.org/June2018/#sec-Schema
# > All types and directives defined within a schema must not have a name which
# > begins with "__" (two underscores), as this is used exclusively
# > by GraphQL`s introspection system.
return str(key).startswith("__")
def is_introspection_field(info: GraphQLResolveInfo) -> bool:
path = info.path
while path:
if is_introspection_key(path.key):
return True
path = path.prev
return False
def get_path_from_info(info: GraphQLResolveInfo) -> List[str]:
path = info.path
elements = []
while path:
elements.append(path.key)
path = path.prev
return elements[::-1]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/utils.py | utils.py |
from __future__ import annotations
import itertools
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Union
from strawberry.utils.cached_property import cached_property
if TYPE_CHECKING:
from strawberry.field import StrawberryField
from strawberry.types import Info
SyncExtensionResolver = Callable[..., Any]
AsyncExtensionResolver = Callable[..., Awaitable[Any]]
class FieldExtension:
def apply(self, field: StrawberryField) -> None: # pragma: no cover
pass
def resolve(
self, next_: SyncExtensionResolver, source: Any, info: Info, **kwargs
) -> Any: # pragma: no cover
raise NotImplementedError(
"Sync Resolve is not supported for this Field Extension"
)
async def resolve_async(
self, next_: AsyncExtensionResolver, source: Any, info: Info, **kwargs
) -> Any: # pragma: no cover
raise NotImplementedError(
"Async Resolve is not supported for this Field Extension"
)
@cached_property
def supports_sync(self) -> bool:
return type(self).resolve is not FieldExtension.resolve
@cached_property
def supports_async(self) -> bool:
return type(self).resolve_async is not FieldExtension.resolve_async
class SyncToAsyncExtension(FieldExtension):
"""Helper class for mixing async extensions with sync resolvers.
Applied automatically"""
async def resolve_async(
self, next_: AsyncExtensionResolver, source: Any, info: Info, **kwargs
) -> Any:
return next_(source, info, **kwargs)
def _get_sync_resolvers(
extensions: list[FieldExtension],
) -> list[SyncExtensionResolver]:
return [extension.resolve for extension in extensions]
def _get_async_resolvers(
extensions: list[FieldExtension],
) -> list[AsyncExtensionResolver]:
return [extension.resolve_async for extension in extensions]
def build_field_extension_resolvers(
field: StrawberryField,
) -> list[Union[SyncExtensionResolver, AsyncExtensionResolver]]:
"""
Verifies that all of the field extensions for a given field support
sync or async depending on the field resolver.
Inserts a SyncToAsyncExtension to be able to
use Async extensions on sync resolvers
Throws a TypeError otherwise.
Returns True if resolving should be async, False on sync resolving
based on the resolver and extensions
"""
if not field.extensions:
return [] # pragma: no cover
non_async_extensions = [
extension for extension in field.extensions if not extension.supports_async
]
non_async_extension_names = ",".join(
[extension.__class__.__name__ for extension in non_async_extensions]
)
if field.is_async:
if len(non_async_extensions) > 0:
raise TypeError(
f"Cannot add sync-only extension(s) {non_async_extension_names} "
f"to the async resolver of Field {field.name}. "
f"Please add a resolve_async method to the extension(s)."
)
return _get_async_resolvers(field.extensions)
else:
# Try to wrap all sync resolvers in async so that we can use async extensions
# on sync fields. This is not possible the other way around since
# the result of an async resolver would have to be awaited before calling
# the sync extension, making it impossible for the extension to modify
# any arguments.
non_sync_extensions = [
extension for extension in field.extensions if not extension.supports_sync
]
if len(non_sync_extensions) == 0:
# Resolve everything sync
return _get_sync_resolvers(field.extensions)
# We have async-only extensions and need to wrap the resolver
# That means we can't have sync-only extensions after the first async one
# Check if we have a chain of sync-compatible
# extensions before the async extensions
# -> S-S-S-S-A-A-A-A
found_sync_extensions = 0
# All sync only extensions must be found before the first async-only one
found_sync_only_extensions = 0
for extension in field.extensions:
# ...A, abort
if extension in non_sync_extensions:
break
# ...S
if extension in non_async_extensions:
found_sync_only_extensions += 1
found_sync_extensions += 1
# Length of the chain equals length of non async extensions
# All sync extensions run first
if len(non_async_extensions) == found_sync_only_extensions:
# Prepend sync to async extension to field extensions
return list(
itertools.chain(
_get_sync_resolvers(field.extensions[:found_sync_extensions]),
[SyncToAsyncExtension().resolve_async],
_get_async_resolvers(field.extensions[found_sync_extensions:]),
)
)
# Some sync extensions follow the first async-only extension. Error case
async_extension_names = ",".join(
[extension.__class__.__name__ for extension in non_sync_extensions]
)
raise TypeError(
f"Cannot mix async-only extension(s) {async_extension_names} "
f"with sync-only extension(s) {non_async_extension_names} "
f"on Field {field.name}. "
f"If possible try to change the execution order so that all sync-only "
f"extensions are executed first."
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/field_extension.py | field_extension.py |
import warnings
from .add_validation_rules import AddValidationRules
from .base_extension import SchemaExtension
from .disable_validation import DisableValidation
from .field_extension import FieldExtension
from .mask_errors import MaskErrors
from .parser_cache import ParserCache
from .query_depth_limiter import QueryDepthLimiter
from .validation_cache import ValidationCache
def __getattr__(name: str):
if name == "Extension":
warnings.warn(
(
"importing `Extension` from `strawberry.extensions` "
"is deprecated, import `SchemaExtension` instead."
),
DeprecationWarning,
stacklevel=2,
)
return SchemaExtension
raise AttributeError(f"module {__name__} has no attribute {name}")
__all__ = [
"FieldExtension",
"SchemaExtension",
"AddValidationRules",
"DisableValidation",
"ParserCache",
"QueryDepthLimiter",
"ValidationCache",
"MaskErrors",
]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/__init__.py | __init__.py |
# This is a Python port of https://github.com/stems/graphql-depth-limit
# which is licensed under the terms of the MIT license, reproduced below.
#
# -----------
#
# MIT License
#
# Copyright (c) 2017 Stem
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import re
from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Type, Union
from graphql import GraphQLError
from graphql.language import (
FieldNode,
FragmentDefinitionNode,
FragmentSpreadNode,
InlineFragmentNode,
OperationDefinitionNode,
)
from graphql.validation import ValidationRule
from strawberry.extensions import AddValidationRules
from strawberry.extensions.utils import is_introspection_key
if TYPE_CHECKING:
from graphql.language import DefinitionNode, Node
from graphql.validation import ValidationContext
IgnoreType = Union[Callable[[str], bool], re.Pattern, str]
class QueryDepthLimiter(AddValidationRules):
"""
Add a validator to limit the query depth of GraphQL operations
Example:
>>> import strawberry
>>> from strawberry.extensions import QueryDepthLimiter
>>>
>>> schema = strawberry.Schema(
... Query,
... extensions=[
... QueryDepthLimiter(max_depth=4)
... ]
... )
Arguments:
`max_depth: int`
The maximum allowed depth for any operation in a GraphQL document.
`ignore: Optional[List[IgnoreType]]`
Stops recursive depth checking based on a field name.
Either a string or regexp to match the name, or a function that returns
a boolean.
`callback: Optional[Callable[[Dict[str, int]], None]`
Called each time validation runs. Receives an Object which is a
map of the depths for each operation.
"""
def __init__(
self,
max_depth: int,
ignore: Optional[List[IgnoreType]] = None,
callback: Optional[Callable[[Dict[str, int]], None]] = None,
):
validator = create_validator(max_depth, ignore, callback)
super().__init__([validator])
def create_validator(
max_depth: int,
ignore: Optional[List[IgnoreType]] = None,
callback: Optional[Callable[[Dict[str, int]], None]] = None,
) -> Type[ValidationRule]:
class DepthLimitValidator(ValidationRule):
def __init__(self, validation_context: ValidationContext):
document = validation_context.document
definitions = document.definitions
fragments = get_fragments(definitions)
queries = get_queries_and_mutations(definitions)
query_depths = {}
for name in queries:
query_depths[name] = determine_depth(
node=queries[name],
fragments=fragments,
depth_so_far=0,
max_depth=max_depth,
context=validation_context,
operation_name=name,
ignore=ignore,
)
if callable(callback):
callback(query_depths)
super().__init__(validation_context)
return DepthLimitValidator
def get_fragments(
definitions: Iterable[DefinitionNode],
) -> Dict[str, FragmentDefinitionNode]:
fragments = {}
for definition in definitions:
if isinstance(definition, FragmentDefinitionNode):
fragments[definition.name.value] = definition
return fragments
# This will actually get both queries and mutations.
# We can basically treat those the same
def get_queries_and_mutations(
definitions: Iterable[DefinitionNode],
) -> Dict[str, OperationDefinitionNode]:
operations = {}
for definition in definitions:
if isinstance(definition, OperationDefinitionNode):
operation = definition.name.value if definition.name else "anonymous"
operations[operation] = definition
return operations
def determine_depth(
node: Node,
fragments: Dict[str, FragmentDefinitionNode],
depth_so_far: int,
max_depth: int,
context: ValidationContext,
operation_name: str,
ignore: Optional[List[IgnoreType]] = None,
) -> int:
if depth_so_far > max_depth:
context.report_error(
GraphQLError(
f"'{operation_name}' exceeds maximum operation depth of {max_depth}",
[node],
)
)
return depth_so_far
if isinstance(node, FieldNode):
# by default, ignore the introspection fields which begin
# with double underscores
should_ignore = is_introspection_key(node.name.value) or is_ignored(
node, ignore
)
if should_ignore or not node.selection_set:
return 0
return 1 + max(
map(
lambda selection: determine_depth(
node=selection,
fragments=fragments,
depth_so_far=depth_so_far + 1,
max_depth=max_depth,
context=context,
operation_name=operation_name,
ignore=ignore,
),
node.selection_set.selections,
)
)
elif isinstance(node, FragmentSpreadNode):
return determine_depth(
node=fragments[node.name.value],
fragments=fragments,
depth_so_far=depth_so_far,
max_depth=max_depth,
context=context,
operation_name=operation_name,
ignore=ignore,
)
elif isinstance(
node, (InlineFragmentNode, FragmentDefinitionNode, OperationDefinitionNode)
):
return max(
map(
lambda selection: determine_depth(
node=selection,
fragments=fragments,
depth_so_far=depth_so_far,
max_depth=max_depth,
context=context,
operation_name=operation_name,
ignore=ignore,
),
node.selection_set.selections,
)
)
else:
raise TypeError(f"Depth crawler cannot handle: {node.kind}") # pragma: no cover
def is_ignored(node: FieldNode, ignore: Optional[List[IgnoreType]] = None) -> bool:
if ignore is None:
return False
for rule in ignore:
field_name = node.name.value
if isinstance(rule, str):
if field_name == rule:
return True
elif isinstance(rule, re.Pattern):
if rule.match(field_name):
return True
elif callable(rule):
if rule(field_name):
return True
else:
raise TypeError(f"Invalid ignore option: {rule}")
return False
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/query_depth_limiter.py | query_depth_limiter.py |
from typing import Iterator
from strawberry.extensions.base_extension import SchemaExtension
class DisableValidation(SchemaExtension):
"""
Disable query validation
Example:
>>> import strawberry
>>> from strawberry.extensions import DisableValidation
>>>
>>> schema = strawberry.Schema(
... Query,
... extensions=[
... DisableValidation,
... ]
... )
"""
def __init__(self):
# There aren't any arguments to this extension yet but we might add
# some in the future
pass
def on_operation(self) -> Iterator[None]:
self.execution_context.validation_rules = () # remove all validation_rules
yield
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/disable_validation.py | disable_validation.py |
from __future__ import annotations
import hashlib
from inspect import isawaitable
from typing import TYPE_CHECKING, Any, Generator, Iterator, Optional
from ddtrace import tracer
from strawberry.extensions import SchemaExtension
from strawberry.extensions.tracing.utils import should_skip_tracing
from strawberry.utils.cached_property import cached_property
if TYPE_CHECKING:
from strawberry.types.execution import ExecutionContext
class DatadogTracingExtension(SchemaExtension):
def __init__(
self,
*,
execution_context: Optional[ExecutionContext] = None,
):
if execution_context:
self.execution_context = execution_context
@cached_property
def _resource_name(self):
assert self.execution_context.query
query_hash = self.hash_query(self.execution_context.query)
if self.execution_context.operation_name:
return f"{self.execution_context.operation_name}:{query_hash}"
return query_hash
def hash_query(self, query: str) -> str:
return hashlib.md5(query.encode("utf-8")).hexdigest()
def on_operation(self) -> Iterator[None]:
self._operation_name = self.execution_context.operation_name
span_name = (
f"{self._operation_name}" if self._operation_name else "Anonymous Query"
)
self.request_span = tracer.trace(
span_name,
resource=self._resource_name,
span_type="graphql",
service="strawberry",
)
self.request_span.set_tag("graphql.operation_name", self._operation_name)
operation_type = "query"
assert self.execution_context.query
if self.execution_context.query.strip().startswith("mutation"):
operation_type = "mutation"
if self.execution_context.query.strip().startswith("subscription"):
operation_type = "subscription"
self.request_span.set_tag("graphql.operation_type", operation_type)
yield
self.request_span.finish()
def on_validate(self) -> Generator[None, None, None]:
self.validation_span = tracer.trace("Validation", span_type="graphql")
yield
self.validation_span.finish()
def on_parse(self) -> Generator[None, None, None]:
self.parsing_span = tracer.trace("Parsing", span_type="graphql")
yield
self.parsing_span.finish()
async def resolve(self, _next, root, info, *args, **kwargs) -> Any:
if should_skip_tracing(_next, info):
result = _next(root, info, *args, **kwargs)
if isawaitable(result): # pragma: no cover
result = await result
return result
field_path = f"{info.parent_type}.{info.field_name}"
with tracer.trace(f"Resolving: {field_path}", span_type="graphql") as span:
span.set_tag("graphql.field_name", info.field_name)
span.set_tag("graphql.parent_type", info.parent_type.name)
span.set_tag("graphql.field_path", field_path)
span.set_tag("graphql.path", ".".join(map(str, info.path.as_list())))
result = _next(root, info, *args, **kwargs)
if isawaitable(result):
result = await result
return result
class DatadogTracingExtensionSync(DatadogTracingExtension):
def resolve(self, _next, root, info, *args, **kwargs) -> Any:
if should_skip_tracing(_next, info):
return _next(root, info, *args, **kwargs)
field_path = f"{info.parent_type}.{info.field_name}"
with tracer.trace(f"Resolving: {field_path}", span_type="graphql") as span:
span.set_tag("graphql.field_name", info.field_name)
span.set_tag("graphql.parent_type", info.parent_type.name)
span.set_tag("graphql.field_path", field_path)
span.set_tag("graphql.path", ".".join(map(str, info.path.as_list())))
return _next(root, info, *args, **kwargs)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/tracing/datadog.py | datadog.py |
from __future__ import annotations
import enum
from copy import deepcopy
from inspect import isawaitable
from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, Optional
from opentelemetry import trace
from opentelemetry.trace import SpanKind
from strawberry.extensions import SchemaExtension
from strawberry.extensions.utils import get_path_from_info
from .utils import should_skip_tracing
if TYPE_CHECKING:
from graphql import GraphQLResolveInfo
from opentelemetry.trace import Span, Tracer
from strawberry.types.execution import ExecutionContext
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
ArgFilter = Callable[[Dict[str, Any], "GraphQLResolveInfo"], Dict[str, Any]]
class RequestStage(enum.Enum):
REQUEST = enum.auto()
PARSING = enum.auto()
VALIDATION = enum.auto()
class OpenTelemetryExtension(SchemaExtension):
_arg_filter: Optional[ArgFilter]
_span_holder: Dict[RequestStage, Span] = dict()
_tracer: Tracer
def __init__(
self,
*,
execution_context: Optional[ExecutionContext] = None,
arg_filter: Optional[ArgFilter] = None,
):
self._arg_filter = arg_filter
self._tracer = trace.get_tracer("strawberry")
if execution_context:
self.execution_context = execution_context
def on_operation(self) -> Generator[None, None, None]:
self._operation_name = self.execution_context.operation_name
span_name = (
f"GraphQL Query: {self._operation_name}"
if self._operation_name
else "GraphQL Query"
)
self._span_holder[RequestStage.REQUEST] = self._tracer.start_span(
span_name, kind=SpanKind.SERVER
)
self._span_holder[RequestStage.REQUEST].set_attribute("component", "graphql")
if self.execution_context.query:
self._span_holder[RequestStage.REQUEST].set_attribute(
"query", self.execution_context.query
)
yield
# If the client doesn't provide an operation name then GraphQL will
# execute the first operation in the query string. This might be a named
# operation but we don't know until the parsing stage has finished. If
# that's the case we want to update the span name so that we have a more
# useful name in our trace.
if not self._operation_name and self.execution_context.operation_name:
span_name = f"GraphQL Query: {self.execution_context.operation_name}"
self._span_holder[RequestStage.REQUEST].update_name(span_name)
self._span_holder[RequestStage.REQUEST].end()
def on_validate(self) -> Generator[None, None, None]:
ctx = trace.set_span_in_context(self._span_holder[RequestStage.REQUEST])
self._span_holder[RequestStage.VALIDATION] = self._tracer.start_span(
"GraphQL Validation",
context=ctx,
)
yield
self._span_holder[RequestStage.VALIDATION].end()
def on_parse(self) -> Generator[None, None, None]:
ctx = trace.set_span_in_context(self._span_holder[RequestStage.REQUEST])
self._span_holder[RequestStage.PARSING] = self._tracer.start_span(
"GraphQL Parsing", context=ctx
)
yield
self._span_holder[RequestStage.PARSING].end()
def filter_resolver_args(
self, args: Dict[str, Any], info: GraphQLResolveInfo
) -> Dict[str, Any]:
if not self._arg_filter:
return args
return self._arg_filter(deepcopy(args), info)
def add_tags(
self, span: Span, info: GraphQLResolveInfo, kwargs: Dict[str, Any]
) -> None:
graphql_path = ".".join(map(str, get_path_from_info(info)))
span.set_attribute("component", "graphql")
span.set_attribute("graphql.parentType", info.parent_type.name)
span.set_attribute("graphql.path", graphql_path)
if kwargs:
filtered_kwargs = self.filter_resolver_args(kwargs, info)
for kwarg, value in filtered_kwargs.items():
span.set_attribute(f"graphql.param.{kwarg}", value)
async def resolve(self, _next, root, info, *args, **kwargs) -> Any:
if should_skip_tracing(_next, info):
result = _next(root, info, *args, **kwargs)
if isawaitable(result): # pragma: no cover
result = await result
return result
with self._tracer.start_as_current_span(
f"GraphQL Resolving: {info.field_name}",
context=trace.set_span_in_context(self._span_holder[RequestStage.REQUEST]),
) as span:
self.add_tags(span, info, kwargs)
result = _next(root, info, *args, **kwargs)
if isawaitable(result):
result = await result
return result
class OpenTelemetryExtensionSync(OpenTelemetryExtension):
def resolve(self, _next, root, info, *args, **kwargs) -> Any:
if should_skip_tracing(_next, info):
result = _next(root, info, *args, **kwargs)
return result
with self._tracer.start_as_current_span(
f"GraphQL Resolving: {info.field_name}",
context=trace.set_span_in_context(self._span_holder[RequestStage.REQUEST]),
) as span:
self.add_tags(span, info, kwargs)
result = _next(root, info, *args, **kwargs)
return result
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/tracing/opentelemetry.py | opentelemetry.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable
from strawberry.extensions.utils import is_introspection_field
from strawberry.resolvers import is_default_resolver
if TYPE_CHECKING:
from graphql import GraphQLResolveInfo
def should_skip_tracing(resolver: Callable[..., Any], info: GraphQLResolveInfo) -> bool:
if info.field_name not in info.parent_type.fields:
return True
resolver = info.parent_type.fields[info.field_name].resolve
return (
is_introspection_field(info)
or is_default_resolver(resolver)
or resolver is None
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/tracing/utils.py | utils.py |
from __future__ import annotations
import dataclasses
import time
from datetime import datetime
from inspect import isawaitable
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional
from strawberry.extensions import SchemaExtension
from strawberry.extensions.utils import get_path_from_info
from .utils import should_skip_tracing
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
if TYPE_CHECKING:
from strawberry.types.execution import ExecutionContext
@dataclasses.dataclass
class ApolloStepStats:
start_offset: int
duration: int
def to_json(self) -> Dict[str, Any]:
return {"startOffset": self.start_offset, "duration": self.duration}
@dataclasses.dataclass
class ApolloResolverStats:
path: List[str]
parent_type: Any
field_name: str
return_type: Any
start_offset: int
duration: Optional[int] = None
def to_json(self) -> Dict[str, Any]:
return {
"path": self.path,
"field_name": self.field_name,
"parentType": str(self.parent_type),
"returnType": str(self.return_type),
"startOffset": self.start_offset,
"duration": self.duration,
}
@dataclasses.dataclass
class ApolloExecutionStats:
resolvers: List[ApolloResolverStats]
def to_json(self) -> Dict[str, Any]:
return {"resolvers": [resolver.to_json() for resolver in self.resolvers]}
@dataclasses.dataclass
class ApolloTracingStats:
start_time: datetime
end_time: datetime
duration: int
execution: ApolloExecutionStats
validation: ApolloStepStats
parsing: ApolloStepStats
version: int = 1
def to_json(self) -> Dict[str, Any]:
return {
"version": self.version,
"startTime": self.start_time.strftime(DATETIME_FORMAT),
"endTime": self.end_time.strftime(DATETIME_FORMAT),
"duration": self.duration,
"execution": self.execution.to_json(),
"validation": self.validation.to_json(),
"parsing": self.parsing.to_json(),
}
class ApolloTracingExtension(SchemaExtension):
def __init__(self, execution_context: ExecutionContext):
self._resolver_stats: List[ApolloResolverStats] = []
self.execution_context = execution_context
def on_operation(self) -> Generator[None, None, None]:
self.start_timestamp = self.now()
self.start_time = datetime.utcnow()
yield
self.end_timestamp = self.now()
self.end_time = datetime.utcnow()
def on_parse(self) -> Generator[None, None, None]:
self._start_parsing = self.now()
yield
self._end_parsing = self.now()
def on_validate(self) -> Generator[None, None, None]:
self._start_validation = self.now()
yield
self._end_validation = self.now()
def now(self) -> int:
return time.perf_counter_ns()
@property
def stats(self) -> ApolloTracingStats:
return ApolloTracingStats(
start_time=self.start_time,
end_time=self.end_time,
duration=self.end_timestamp - self.start_timestamp,
execution=ApolloExecutionStats(self._resolver_stats),
validation=ApolloStepStats(
start_offset=self._start_validation - self.start_timestamp,
duration=self._end_validation - self._start_validation,
),
parsing=ApolloStepStats(
start_offset=self._start_parsing - self.start_timestamp,
duration=self._end_parsing - self._start_parsing,
),
)
def get_results(self) -> Dict[str, Dict[str, Any]]:
return {"tracing": self.stats.to_json()}
async def resolve(self, _next, root, info, *args, **kwargs) -> Any:
if should_skip_tracing(_next, info):
result = _next(root, info, *args, **kwargs)
if isawaitable(result):
result = await result # pragma: no cover
return result
start_timestamp = self.now()
resolver_stats = ApolloResolverStats(
path=get_path_from_info(info),
field_name=info.field_name,
parent_type=info.parent_type,
return_type=info.return_type,
start_offset=start_timestamp - self.start_timestamp,
)
try:
result = _next(root, info, *args, **kwargs)
if isawaitable(result):
result = await result
return result
finally:
end_timestamp = self.now()
resolver_stats.duration = end_timestamp - start_timestamp
self._resolver_stats.append(resolver_stats)
class ApolloTracingExtensionSync(ApolloTracingExtension):
def resolve(self, _next, root, info, *args, **kwargs) -> Any:
if should_skip_tracing(_next, info):
return _next(root, info, *args, **kwargs)
start_timestamp = self.now()
resolver_stats = ApolloResolverStats(
path=get_path_from_info(info),
field_name=info.field_name,
parent_type=info.parent_type,
return_type=info.return_type,
start_offset=start_timestamp - self.start_timestamp,
)
try:
return _next(root, info, *args, **kwargs)
finally:
end_timestamp = self.now()
resolver_stats.duration = end_timestamp - start_timestamp
self._resolver_stats.append(resolver_stats)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/tracing/apollo.py | apollo.py |
import importlib
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .apollo import ApolloTracingExtension, ApolloTracingExtensionSync
from .datadog import DatadogTracingExtension, DatadogTracingExtensionSync
from .opentelemetry import (
OpenTelemetryExtension,
OpenTelemetryExtensionSync,
)
__all__ = [
"ApolloTracingExtension",
"ApolloTracingExtensionSync",
"DatadogTracingExtension",
"DatadogTracingExtensionSync",
"OpenTelemetryExtension",
"OpenTelemetryExtensionSync",
]
def __getattr__(name: str):
if name in {"DatadogTracingExtension", "DatadogTracingExtensionSync"}:
return getattr(importlib.import_module(".datadog", __name__), name)
if name in {"ApolloTracingExtension", "ApolloTracingExtensionSync"}:
return getattr(importlib.import_module(".apollo", __name__), name)
if name in {"OpenTelemetryExtension", "OpenTelemetryExtensionSync"}:
return getattr(importlib.import_module(".opentelemetry", __name__), name)
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/extensions/tracing/__init__.py | __init__.py |
import warnings
from typing_extensions import TypedDict
from sanic.request import Request
from strawberry.http.temporal_response import TemporalResponse
class StrawberrySanicContext(TypedDict):
request: Request
response: TemporalResponse
# see https://github.com/python/mypy/issues/13066 for the type ignore
def __getattr__(self, key: str) -> object: # type: ignore
# a warning will be raised because this is not supported anymore
# but we need to keep it for backwards compatibility
warnings.warn(
"Accessing context attributes via the dot notation is deprecated, "
"please use context.get('key') or context['key'] instead",
DeprecationWarning,
stacklevel=2,
)
return super().__getitem__(key)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/sanic/context.py | context.py |
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from sanic.request import Request
def should_render_graphiql(graphiql: bool, request: Request) -> bool:
if not graphiql:
return False
return any(
supported_header in request.headers.get("accept", "")
for supported_header in ("text/html", "*/*")
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/sanic/graphiql.py | graphiql.py |
from __future__ import annotations
import json
import warnings
from typing import TYPE_CHECKING, Any, Dict, Optional, Type, Union
from sanic.exceptions import NotFound, SanicException, ServerError
from sanic.response import HTTPResponse, html
from sanic.views import HTTPMethodView
from strawberry.exceptions import MissingQueryError
from strawberry.file_uploads.utils import replace_placeholders_with_files
from strawberry.http import (
parse_query_params,
parse_request_data,
process_result,
)
from strawberry.http.temporal_response import TemporalResponse
from strawberry.sanic.graphiql import should_render_graphiql
from strawberry.sanic.utils import convert_request_to_files_dict
from strawberry.schema.exceptions import InvalidOperationTypeError
from strawberry.types.graphql import OperationType
from strawberry.utils.graphiql import get_graphiql_html
if TYPE_CHECKING:
from typing_extensions import Literal
from sanic.request import Request
from strawberry.http import GraphQLHTTPResponse, GraphQLRequestData
from strawberry.schema import BaseSchema
from strawberry.types import ExecutionResult
from .context import StrawberrySanicContext
class GraphQLView(HTTPMethodView):
"""
Class based view to handle GraphQL HTTP Requests
Args:
schema: strawberry.Schema
graphiql: bool, default is True
allow_queries_via_get: bool, default is True
Returns:
None
Example:
app.add_route(
GraphQLView.as_view(schema=schema, graphiql=True),
"/graphql"
)
"""
def __init__(
self,
schema: BaseSchema,
graphiql: bool = True,
allow_queries_via_get: bool = True,
json_encoder: Optional[Type[json.JSONEncoder]] = None,
json_dumps_params: Optional[Dict[str, Any]] = None,
):
self.schema = schema
self.graphiql = graphiql
self.allow_queries_via_get = allow_queries_via_get
self.json_encoder = json_encoder
self.json_dumps_params = json_dumps_params
if self.json_encoder is not None:
warnings.warn(
"json_encoder is deprecated, override encode_json instead",
DeprecationWarning,
stacklevel=2,
)
if self.json_dumps_params is not None:
warnings.warn(
"json_dumps_params is deprecated, override encode_json instead",
DeprecationWarning,
stacklevel=2,
)
self.json_encoder = json.JSONEncoder
def get_root_value(self) -> Any:
return None
async def get_context(
self, request: Request, response: TemporalResponse
) -> StrawberrySanicContext:
return {"request": request, "response": response}
def render_template(self, template: str) -> HTTPResponse:
return html(template)
async def process_result(
self, request: Request, result: ExecutionResult
) -> GraphQLHTTPResponse:
return process_result(result)
async def get(self, request: Request) -> HTTPResponse:
if request.args:
# Sanic request.args uses urllib.parse.parse_qs
# returns a dictionary where the keys are the unique variable names
# and the values are a list of values for each variable name
# Enforcing using the first value
query_data = {
variable_name: value[0] for variable_name, value in request.args.items()
}
try:
data = parse_query_params(query_data)
except json.JSONDecodeError:
raise ServerError(
"Unable to parse request body as JSON", status_code=400
)
request_data = parse_request_data(data)
return await self.execute_request(
request=request, request_data=request_data, method="GET"
)
elif should_render_graphiql(self.graphiql, request):
template = get_graphiql_html(False)
return self.render_template(template=template)
raise NotFound()
async def get_response(
self, response_data: GraphQLHTTPResponse, context: StrawberrySanicContext
) -> HTTPResponse:
status_code = 200
if "response" in context and context["response"]:
status_code = context["response"].status_code
data = self.encode_json(response_data)
return HTTPResponse(
data,
status=status_code,
content_type="application/json",
)
def encode_json(self, response_data: GraphQLHTTPResponse) -> str:
if self.json_dumps_params:
assert self.json_encoder
return json.dumps(
response_data, cls=self.json_encoder, **self.json_dumps_params
)
if self.json_encoder:
return json.dumps(response_data, cls=self.json_encoder)
return json.dumps(response_data)
async def post(self, request: Request) -> HTTPResponse:
request_data = self.get_request_data(request)
return await self.execute_request(
request=request, request_data=request_data, method="POST"
)
async def execute_request(
self,
request: Request,
request_data: GraphQLRequestData,
method: Union[Literal["GET"], Literal["POST"]],
) -> HTTPResponse:
context = await self.get_context(request, TemporalResponse())
root_value = self.get_root_value()
allowed_operation_types = OperationType.from_http(method)
if not self.allow_queries_via_get and method == "GET":
allowed_operation_types = allowed_operation_types - {OperationType.QUERY}
try:
result = await self.schema.execute(
query=request_data.query,
variable_values=request_data.variables,
context_value=context,
root_value=root_value,
operation_name=request_data.operation_name,
allowed_operation_types=allowed_operation_types,
)
except InvalidOperationTypeError as e:
raise ServerError(
e.as_http_error_reason(method=method), status_code=400
) from e
except MissingQueryError:
raise ServerError("No GraphQL query found in the request", status_code=400)
response_data = await self.process_result(request, result)
return await self.get_response(response_data, context)
def get_request_data(self, request: Request) -> GraphQLRequestData:
try:
data = self.parse_request(request)
except json.JSONDecodeError:
raise ServerError("Unable to parse request body as JSON", status_code=400)
return parse_request_data(data)
def parse_request(self, request: Request) -> Dict[str, Any]:
content_type = request.content_type or ""
if "application/json" in content_type:
return json.loads(request.body)
elif content_type.startswith("multipart/form-data"):
files = convert_request_to_files_dict(request)
operations = json.loads(request.form.get("operations", "{}"))
files_map = json.loads(request.form.get("map", "{}"))
try:
return replace_placeholders_with_files(operations, files_map, files)
except KeyError:
raise SanicException(
status_code=400, message="File(s) missing in form data"
)
raise ServerError("Unsupported Media Type", status_code=415)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/sanic/views.py | views.py |
from __future__ import annotations
from io import BytesIO
from typing import TYPE_CHECKING, Any, Dict, List, Union
if TYPE_CHECKING:
from sanic.request import Request
def convert_request_to_files_dict(request: Request) -> Dict[str, Any]:
"""
request.files has the following format, even if only a single file is uploaded:
{
'textFile': [
sanic.request.File(
type='text/plain',
body=b'strawberry',
name='textFile.txt'
)
]
}
Note that the dictionary entries are lists.
"""
request_files = request.files
files_dict: Dict[str, Union[BytesIO, List[BytesIO]]] = {}
for field_name, file_list in request_files.items():
assert len(file_list) == 1
files_dict[field_name] = BytesIO(file_list[0].body)
return files_dict
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/sanic/utils.py | utils.py |
from __future__ import annotations
import json
import warnings
from typing import TYPE_CHECKING, Dict, Mapping, Optional
from chalice.app import BadRequestError, Response
from strawberry.exceptions import MissingQueryError
from strawberry.http import (
parse_query_params,
parse_request_data,
process_result,
)
from strawberry.http.temporal_response import TemporalResponse
from strawberry.schema.exceptions import InvalidOperationTypeError
from strawberry.types.graphql import OperationType
from strawberry.utils.graphiql import get_graphiql_html
if TYPE_CHECKING:
from chalice.app import Request
from strawberry.http import GraphQLHTTPResponse
from strawberry.schema import BaseSchema
from strawberry.types import ExecutionResult
class GraphQLView:
def __init__(
self,
schema: BaseSchema,
graphiql: bool = True,
allow_queries_via_get: bool = True,
**kwargs,
):
if "render_graphiql" in kwargs:
self.graphiql = kwargs.pop("render_graphiql")
warnings.warn(
"The `render_graphiql` argument is deprecated. "
"Use `graphiql` instead.",
DeprecationWarning,
stacklevel=2,
)
else:
self.graphiql = graphiql
self.allow_queries_via_get = allow_queries_via_get
self._schema = schema
def get_root_value(self, request: Request) -> Optional[object]:
return None
@staticmethod
def render_graphiql() -> str:
"""
Returns a string containing the html for the graphiql webpage. It also caches
the result using lru cache.
This saves loading from disk each time it is invoked.
Returns:
The GraphiQL html page as a string
"""
return get_graphiql_html(subscription_enabled=False)
@staticmethod
def should_render_graphiql(graphiql: bool, request: Request) -> bool:
"""
Do the headers indicate that the invoker has requested html?
Args:
headers: A dictionary containing the headers in the request
Returns:
Whether html has been requested True for yes, False for no
"""
if not graphiql:
return False
return any(
supported_header in request.headers.get("accept", "")
for supported_header in {"text/html", "*/*"}
)
@staticmethod
def error_response(
message: str,
error_code: str,
http_status_code: int,
headers: Optional[Dict[str, str]] = None,
) -> Response:
"""
A wrapper for error responses
Returns:
An errors response
"""
body = {"Code": error_code, "Message": message}
return Response(body=body, status_code=http_status_code, headers=headers)
def get_context(
self, request: Request, response: TemporalResponse
) -> Mapping[str, object]:
return {"request": request, "response": response}
def process_result(
self, request: Request, result: ExecutionResult
) -> GraphQLHTTPResponse:
return process_result(result)
def execute_request(self, request: Request) -> Response:
"""
Parse the request process it with strawberry and return a response
Args:
request: The chalice request this contains the headers and body
Returns:
A chalice response
"""
method = request.method
if method not in {"POST", "GET"}:
return self.error_response(
error_code="MethodNotAllowedError",
message="Unsupported method, must be of request type POST or GET",
http_status_code=405,
)
content_type = request.headers.get("content-type", "")
if "application/json" in content_type:
try:
data = request.json_body
if not (isinstance(data, dict)):
return self.error_response(
error_code="BadRequestError",
message=(
"Provide a valid graphql query "
"in the body of your request"
),
http_status_code=400,
)
except BadRequestError:
return self.error_response(
error_code="BadRequestError",
message="Unable to parse request body as JSON",
http_status_code=400,
)
elif method == "GET" and request.query_params:
try:
data = parse_query_params(request.query_params) # type: ignore
except json.JSONDecodeError:
return self.error_response(
error_code="BadRequestError",
message="Unable to parse request body as JSON",
http_status_code=400,
)
elif method == "GET" and self.should_render_graphiql(self.graphiql, request):
return Response(
body=self.render_graphiql(),
headers={"content-type": "text/html"},
status_code=200,
)
else:
return self.error_response(
error_code="NotFoundError",
message="Not found",
http_status_code=404,
)
request_data = parse_request_data(data)
allowed_operation_types = OperationType.from_http(method)
if not self.allow_queries_via_get and method == "GET":
allowed_operation_types = allowed_operation_types - {OperationType.QUERY}
context = self.get_context(request, response=TemporalResponse())
try:
result: ExecutionResult = self._schema.execute_sync(
request_data.query,
variable_values=request_data.variables,
context_value=context,
operation_name=request_data.operation_name,
root_value=self.get_root_value(request),
allowed_operation_types=allowed_operation_types,
)
except InvalidOperationTypeError as e:
return self.error_response(
error_code="BadRequestError",
message=e.as_http_error_reason(method),
http_status_code=400,
)
except MissingQueryError:
return self.error_response(
error_code="BadRequestError",
message="No GraphQL query found in the request",
http_status_code=400,
)
http_result: GraphQLHTTPResponse = self.process_result(request, result)
status_code = 200
if "response" in context:
# TODO: we might want to use typed dict for context
status_code = context["response"].status_code # type: ignore[attr-defined]
return Response(body=self.encode_json(http_result), status_code=status_code)
def encode_json(self, response_data: GraphQLHTTPResponse) -> str:
return json.dumps(response_data)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/chalice/views.py | views.py |
from typing import Any
def should_render_graphiql(graphiql: bool, request: Any) -> bool:
if not graphiql:
return False
return any(
supported_header in request.environ.get("HTTP_ACCEPT", "")
for supported_header in ("text/html", "*/*")
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/flask/graphiql.py | graphiql.py |
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Dict
from flask import Response, render_template_string, request
if TYPE_CHECKING:
from flask.typing import ResponseReturnValue
from strawberry.http import GraphQLHTTPResponse
from strawberry.schema.base import BaseSchema
from strawberry.types import ExecutionResult
from flask.views import View
from strawberry.exceptions import MissingQueryError
from strawberry.file_uploads.utils import replace_placeholders_with_files
from strawberry.flask.graphiql import should_render_graphiql
from strawberry.http import (
parse_query_params,
parse_request_data,
process_result,
)
from strawberry.schema.exceptions import InvalidOperationTypeError
from strawberry.types.graphql import OperationType
from strawberry.utils.graphiql import get_graphiql_html
class BaseGraphQLView(View):
methods = ["GET", "POST"]
def __init__(
self,
schema: BaseSchema,
graphiql: bool = True,
allow_queries_via_get: bool = True,
):
self.schema = schema
self.graphiql = graphiql
self.allow_queries_via_get = allow_queries_via_get
def render_template(self, template: str) -> str:
return render_template_string(template)
def encode_json(self, response_data: GraphQLHTTPResponse) -> str:
return json.dumps(response_data)
class GraphQLView(BaseGraphQLView):
def get_root_value(self) -> object:
return None
def get_context(self, response: Response) -> Dict[str, object]:
return {"request": request, "response": response}
def process_result(self, result: ExecutionResult) -> GraphQLHTTPResponse:
return process_result(result)
def dispatch_request(self) -> ResponseReturnValue:
method = request.method
content_type = request.content_type or ""
if request.method not in {"POST", "GET"}:
return Response(
"Unsupported method, must be of request type POST or GET", 405
)
if "application/json" in content_type:
try:
data = json.loads(request.data)
except json.JSONDecodeError:
return Response(
status=400, response="Unable to parse request body as JSON"
)
elif content_type.startswith("multipart/form-data"):
try:
operations = json.loads(request.form.get("operations", "{}"))
files_map = json.loads(request.form.get("map", "{}"))
except json.JSONDecodeError:
return Response(
status=400, response="Unable to parse request body as JSON"
)
try:
data = replace_placeholders_with_files(
operations, files_map, request.files
)
except KeyError:
return Response(status=400, response="File(s) missing in form data")
elif method == "GET" and request.args:
try:
data = parse_query_params(request.args.to_dict())
except json.JSONDecodeError:
return Response(
status=400, response="Unable to parse request body as JSON"
)
elif method == "GET" and should_render_graphiql(self.graphiql, request):
template = get_graphiql_html(False)
return self.render_template(template=template)
elif method == "GET":
return Response(status=404)
else:
return Response("Unsupported Media Type", 415)
request_data = parse_request_data(data)
response = Response(status=200, content_type="application/json")
context = self.get_context(response)
allowed_operation_types = OperationType.from_http(method)
if not self.allow_queries_via_get and method == "GET":
allowed_operation_types = allowed_operation_types - {OperationType.QUERY}
try:
result = self.schema.execute_sync(
request_data.query,
variable_values=request_data.variables,
context_value=context,
operation_name=request_data.operation_name,
root_value=self.get_root_value(),
allowed_operation_types=allowed_operation_types,
)
except InvalidOperationTypeError as e:
return Response(e.as_http_error_reason(method), 400)
except MissingQueryError:
return Response("No GraphQL query found in the request", 400)
response_data = self.process_result(result)
response.set_data(self.encode_json(response_data))
return response
class AsyncGraphQLView(BaseGraphQLView):
methods = ["GET", "POST"]
async def get_root_value(self) -> object:
return None
async def get_context(self, response: Response) -> Dict[str, object]:
return {"request": request, "response": response}
async def process_result(self, result: ExecutionResult) -> GraphQLHTTPResponse:
return process_result(result)
async def dispatch_request(self) -> ResponseReturnValue: # type: ignore[override]
method = request.method
content_type = request.content_type or ""
if request.method not in {"POST", "GET"}:
return Response(
"Unsupported method, must be of request type POST or GET", 405
)
if "application/json" in content_type:
try:
data = json.loads(request.data)
except json.JSONDecodeError:
return Response(
status=400, response="Unable to parse request body as JSON"
)
elif content_type.startswith("multipart/form-data"):
try:
operations = json.loads(request.form.get("operations", "{}"))
files_map = json.loads(request.form.get("map", "{}"))
except json.JSONDecodeError:
return Response(
status=400, response="Unable to parse request body as JSON"
)
try:
data = replace_placeholders_with_files(
operations, files_map, request.files
)
except KeyError:
return Response(status=400, response="File(s) missing in form data")
elif method == "GET" and request.args:
try:
data = parse_query_params(request.args.to_dict())
except json.JSONDecodeError:
return Response(
status=400, response="Unable to parse request body as JSON"
)
elif method == "GET" and should_render_graphiql(self.graphiql, request):
template = get_graphiql_html(False)
return self.render_template(template=template)
elif method == "GET":
return Response(status=404)
else:
return Response("Unsupported Media Type", 415)
request_data = parse_request_data(data)
response = Response(status=200, content_type="application/json")
context = await self.get_context(response)
allowed_operation_types = OperationType.from_http(method)
if not self.allow_queries_via_get and method == "GET":
allowed_operation_types = allowed_operation_types - {OperationType.QUERY}
root_value = await self.get_root_value()
try:
result = await self.schema.execute(
request_data.query,
variable_values=request_data.variables,
context_value=context,
operation_name=request_data.operation_name,
root_value=root_value,
allowed_operation_types=allowed_operation_types,
)
except InvalidOperationTypeError as e:
return Response(e.as_http_error_reason(method), 400)
except MissingQueryError:
return Response("No GraphQL query found in the request", 400)
response_data = await self.process_result(result)
response.set_data(self.encode_json(response_data))
return response
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/flask/views.py | views.py |
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, Optional
if TYPE_CHECKING:
from strawberry.channels.handlers.base import ChannelsConsumer
@dataclass
class StrawberryChannelsContext:
"""
A Channels context for GraphQL
"""
request: "ChannelsConsumer"
connection_params: Optional[Dict[str, Any]] = None
@property
def ws(self) -> "ChannelsConsumer":
return self.request
def __getitem__(self, item: str) -> Any:
return getattr(self, item)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/channels/context.py | context.py |
from __future__ import annotations
import dataclasses
import uuid
from typing import TYPE_CHECKING, AsyncIterator, Dict, List, Optional, Tuple, Union
from graphql import GraphQLError
from channels.testing.websocket import WebsocketCommunicator
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_transport_ws.types import (
ConnectionAckMessage,
ConnectionInitMessage,
ErrorMessage,
NextMessage,
SubscribeMessage,
SubscribeMessagePayload,
)
from strawberry.subscriptions.protocols.graphql_ws import (
GQL_CONNECTION_ACK,
GQL_CONNECTION_INIT,
GQL_START,
)
from strawberry.types import ExecutionResult
if TYPE_CHECKING:
from asgiref.typing import ASGIApplication
class GraphQLWebsocketCommunicator(WebsocketCommunicator):
"""
Usage:
```python
import pytest
from strawberry.channels.testing import GraphQLWebsocketCommunicator
from myapp.asgi import application
@pytest.fixture
async def gql_communicator():
async with GraphQLWebsocketCommunicator(application, path="/graphql") as client:
yield client
async def test_subscribe_echo(gql_communicator):
async for res in gql_communicator.subscribe(
query='subscription { echo(message: "Hi") }'
):
assert res.data == {"echo": "Hi"}
```
"""
def __init__(
self,
application: ASGIApplication,
path: str,
headers: Optional[List[Tuple[bytes, bytes]]] = None,
protocol: str = GRAPHQL_TRANSPORT_WS_PROTOCOL,
**kwargs,
):
"""
Args:
application: Your asgi application that encapsulates the strawberry schema.
path: the url endpoint for the schema.
protocol: currently this supports `graphql-transport-ws` only.
"""
self.protocol = protocol
subprotocols = kwargs.get("subprotocols", [])
subprotocols.append(protocol)
super().__init__(application, path, headers, subprotocols=subprotocols)
async def __aenter__(self) -> GraphQLWebsocketCommunicator:
await self.gql_init()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
await self.disconnect()
async def gql_init(self) -> None:
res = await self.connect()
if self.protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
assert res == (True, GRAPHQL_TRANSPORT_WS_PROTOCOL)
await self.send_json_to(ConnectionInitMessage().as_dict())
response = await self.receive_json_from()
assert response == ConnectionAckMessage().as_dict()
else:
assert res == (True, GRAPHQL_WS_PROTOCOL)
await self.send_json_to({"type": GQL_CONNECTION_INIT})
response = await self.receive_json_from()
assert response["type"] == GQL_CONNECTION_ACK
async def subscribe(
self, query: str, variables: Optional[Dict] = None
) -> Union[ExecutionResult, AsyncIterator[ExecutionResult]]:
id_ = uuid.uuid4().hex
sub_payload = SubscribeMessagePayload(query=query, variables=variables)
if self.protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
await self.send_json_to(
SubscribeMessage(
id=id_,
payload=sub_payload,
).as_dict()
)
else:
await self.send_json_to(
{
"type": GQL_START,
"id": id_,
"payload": dataclasses.asdict(sub_payload),
}
)
while True:
response = await self.receive_json_from(timeout=5)
message_type = response["type"]
if message_type == NextMessage.type:
payload = NextMessage(**response).payload
ret = ExecutionResult(None, None)
for field in dataclasses.fields(ExecutionResult):
setattr(ret, field.name, payload.get(field.name, None))
yield ret
elif message_type == ErrorMessage.type:
error_payload = ErrorMessage(**response).payload
yield ExecutionResult(
data=None,
errors=[
GraphQLError(
message=message["message"],
extensions=message.get("extensions", None),
)
for message in error_payload
],
)
return # an error message is the last message for a subscription
else:
return
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/channels/testing.py | testing.py |
from .context import StrawberryChannelsContext
from .handlers.graphql_transport_ws_handler import GraphQLTransportWSHandler
from .handlers.graphql_ws_handler import GraphQLWSHandler
from .handlers.http_handler import GraphQLHTTPConsumer
from .handlers.ws_handler import GraphQLWSConsumer
from .router import GraphQLProtocolTypeRouter
__all__ = [
"GraphQLProtocolTypeRouter",
"GraphQLWSHandler",
"GraphQLTransportWSHandler",
"GraphQLHTTPConsumer",
"GraphQLWSConsumer",
"StrawberryChannelsContext",
]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/channels/__init__.py | __init__.py |
"""GraphQLWebSocketRouter
This is a simple router class that might be better placed as part of Channels itself.
It's a simple "SubProtocolRouter" that selects the websocket subprotocol based
on preferences and client support. Then it hands off to the appropriate consumer.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from django.urls import re_path
from channels.routing import ProtocolTypeRouter, URLRouter
from .handlers.http_handler import GraphQLHTTPConsumer
from .handlers.ws_handler import GraphQLWSConsumer
if TYPE_CHECKING:
from strawberry.schema import BaseSchema
class GraphQLProtocolTypeRouter(ProtocolTypeRouter):
"""
Convenience class to set up GraphQL on both HTTP and Websocket, optionally with a
Django application for all other HTTP routes:
```
from strawberry.channels import GraphQLProtocolTypeRouter
from django.core.asgi import get_asgi_application
django_asgi = get_asgi_application()
from myapi import schema
application = GraphQLProtocolTypeRouter(
schema,
django_application=django_asgi,
)
```
This will route all requests to /graphql on either HTTP or websockets to us,
and everything else to the Django application.
"""
def __init__(
self,
schema: BaseSchema,
django_application=None,
url_pattern="^graphql",
):
http_urls = [re_path(url_pattern, GraphQLHTTPConsumer.as_asgi(schema=schema))]
if django_application is not None:
http_urls.append(re_path("^", django_application))
super().__init__(
{
"http": URLRouter(http_urls),
"websocket": URLRouter(
[
re_path(url_pattern, GraphQLWSConsumer.as_asgi(schema=schema)),
]
),
}
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/channels/router.py | router.py |
from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, Optional, Sequence, Union
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL
from .base import ChannelsWSConsumer
from .graphql_transport_ws_handler import GraphQLTransportWSHandler
from .graphql_ws_handler import GraphQLWSHandler
if TYPE_CHECKING:
from strawberry.schema import BaseSchema
class GraphQLWSConsumer(ChannelsWSConsumer):
"""A channels websocket consumer for GraphQL
This handles the connections, then hands off to the appropriate
handler based on the subprotocol.
To use this, place it in your ProtocolTypeRouter for your channels project, e.g:
```
from strawberry.channels import GraphQLHttpRouter
from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application
application = ProtocolTypeRouter({
"http": URLRouter([
re_path("^graphql", GraphQLHTTPRouter(schema=schema)),
re_path("^", get_asgi_application()),
]),
"websocket": URLRouter([
re_path("^ws/graphql", GraphQLWebSocketRouter(schema=schema)),
]),
})
```
"""
graphql_transport_ws_handler_class = GraphQLTransportWSHandler
graphql_ws_handler_class = GraphQLWSHandler
_handler: Union[GraphQLWSHandler, GraphQLTransportWSHandler]
def __init__(
self,
schema: BaseSchema,
keep_alive: bool = False,
keep_alive_interval: float = 1,
debug: bool = False,
subscription_protocols=(GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL),
connection_init_wait_timeout: Optional[datetime.timedelta] = None,
):
if connection_init_wait_timeout is None:
connection_init_wait_timeout = datetime.timedelta(minutes=1)
self.connection_init_wait_timeout = connection_init_wait_timeout
self.schema = schema
self.keep_alive = keep_alive
self.keep_alive_interval = keep_alive_interval
self.debug = debug
self.protocols = subscription_protocols
super().__init__()
def pick_preferred_protocol(
self, accepted_subprotocols: Sequence[str]
) -> Optional[str]:
intersection = set(accepted_subprotocols) & set(self.protocols)
sorted_intersection = sorted(intersection, key=accepted_subprotocols.index)
return next(iter(sorted_intersection), None)
async def connect(self) -> None:
preferred_protocol = self.pick_preferred_protocol(self.scope["subprotocols"])
if preferred_protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
self._handler = self.graphql_transport_ws_handler_class(
schema=self.schema,
debug=self.debug,
connection_init_wait_timeout=self.connection_init_wait_timeout,
get_context=self.get_context,
get_root_value=self.get_root_value,
ws=self,
)
elif preferred_protocol == GRAPHQL_WS_PROTOCOL:
self._handler = self.graphql_ws_handler_class(
schema=self.schema,
debug=self.debug,
keep_alive=self.keep_alive,
keep_alive_interval=self.keep_alive_interval,
get_context=self.get_context,
get_root_value=self.get_root_value,
ws=self,
)
else:
# Subprotocol not acceptable
return await self.close(code=4406)
await self._handler.handle()
return None
async def receive(self, *args, **kwargs) -> None:
# Overriding this so that we can pass the errors to handle_invalid_message
try:
await super().receive(*args, **kwargs)
except ValueError as e:
await self._handler.handle_invalid_message(str(e))
async def receive_json(self, content, **kwargs) -> None:
await self._handler.handle_message(content)
async def disconnect(self, code) -> None:
await self._handler.handle_disconnect(code)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/channels/handlers/ws_handler.py | ws_handler.py |
from __future__ import annotations
from contextlib import suppress
from typing import TYPE_CHECKING, Any, Optional
from strawberry.subscriptions import GRAPHQL_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_ws.handlers import BaseGraphQLWSHandler
if TYPE_CHECKING:
from strawberry.channels.handlers.base import ChannelsWSConsumer
from strawberry.schema import BaseSchema
from strawberry.subscriptions.protocols.graphql_ws.types import OperationMessage
class GraphQLWSHandler(BaseGraphQLWSHandler):
def __init__(
self,
schema: BaseSchema,
debug: bool,
keep_alive: bool,
keep_alive_interval: float,
get_context,
get_root_value,
ws: ChannelsWSConsumer,
):
super().__init__(schema, debug, keep_alive, keep_alive_interval)
self._get_context = get_context
self._get_root_value = get_root_value
self._ws = ws
async def get_context(self) -> Any:
return await self._get_context(
request=self._ws, connection_params=self.connection_params
)
async def get_root_value(self) -> Any:
return await self._get_root_value(request=self._ws)
async def send_json(self, data: OperationMessage) -> None:
await self._ws.send_json(data)
async def close(self, code: int = 1000, reason: Optional[str] = None) -> None:
# Close messages are not part of the ASGI ref yet
await self._ws.close(code=code)
async def handle_request(self) -> Any:
await self._ws.accept(subprotocol=GRAPHQL_WS_PROTOCOL)
async def handle_disconnect(self, code) -> None:
if self.keep_alive_task:
self.keep_alive_task.cancel()
with suppress(BaseException):
await self.keep_alive_task
for operation_id in list(self.subscriptions.keys()):
await self.cleanup_operation(operation_id)
async def handle_invalid_message(self, error_message: str) -> None:
# This is not part of the BaseGraphQLWSHandler's interface, but the
# channels integration is a high level wrapper that forwards this to
# both us and the BaseGraphQLTransportWSHandler.
pass
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/channels/handlers/graphql_ws_handler.py | graphql_ws_handler.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_transport_ws.handlers import (
BaseGraphQLTransportWSHandler,
)
if TYPE_CHECKING:
from datetime import timedelta
from strawberry.channels.handlers.base import ChannelsWSConsumer
from strawberry.schema import BaseSchema
class GraphQLTransportWSHandler(BaseGraphQLTransportWSHandler):
def __init__(
self,
schema: BaseSchema,
debug: bool,
connection_init_wait_timeout: timedelta,
get_context,
get_root_value,
ws: ChannelsWSConsumer,
):
super().__init__(schema, debug, connection_init_wait_timeout)
self._get_context = get_context
self._get_root_value = get_root_value
self._ws = ws
async def get_context(self) -> Any:
return await self._get_context(
request=self._ws, connection_params=self.connection_params
)
async def get_root_value(self) -> Any:
return await self._get_root_value(request=self._ws)
async def send_json(self, data: dict) -> None:
await self._ws.send_json(data)
async def close(self, code: int = 1000, reason: Optional[str] = None) -> None:
# FIXME: We are using `self._ws.base_send` directly instead of `self._ws.close`
# because the later doesn't accept the `reason` argument.
await self._ws.base_send(
{
"type": "websocket.close",
"code": code,
"reason": reason or "",
}
)
async def handle_request(self) -> Any:
await self._ws.accept(subprotocol=GRAPHQL_TRANSPORT_WS_PROTOCOL)
async def handle_disconnect(self, code) -> None:
for operation_id in list(self.subscriptions.keys()):
await self.cleanup_operation(operation_id)
await self.reap_completed_tasks()
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/channels/handlers/graphql_transport_ws_handler.py | graphql_transport_ws_handler.py |
import asyncio
import contextlib
from collections import defaultdict
from typing import (
Any,
AsyncGenerator,
Awaitable,
Callable,
DefaultDict,
Dict,
List,
Optional,
Sequence,
)
from typing_extensions import Literal, Protocol, TypedDict
from weakref import WeakSet
from channels.consumer import AsyncConsumer
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from strawberry.channels.context import StrawberryChannelsContext
class ChannelsMessage(TypedDict, total=False):
type: str
class ChannelsLayer(Protocol): # pragma: no cover
"""Channels layer spec.
Based on: https://channels.readthedocs.io/en/stable/channel_layer_spec.html
"""
# Default channels API
extensions: List[Literal["groups", "flush"]]
async def send(self, channel: str, message: dict) -> None:
...
async def receive(self, channel: str) -> dict:
...
async def new_channel(self, prefix: str = ...) -> str:
...
# If groups extension is supported
group_expiry: int
async def group_add(self, group: str, channel: str) -> None:
...
async def group_discard(self, group: str, channel: str) -> None:
...
async def group_send(self, group: str, message: dict) -> None:
...
# If flush extension is supported
async def flush(self) -> None:
...
class ChannelsConsumer(AsyncConsumer):
"""Base channels async consumer."""
channel_name: str
channel_layer: Optional[ChannelsLayer]
channel_receive: Callable[[], Awaitable[dict]]
def __init__(self, *args, **kwargs):
self.listen_queues: DefaultDict[str, WeakSet[asyncio.Queue]] = defaultdict(
WeakSet
)
super().__init__(*args, **kwargs)
@property
def headers(self) -> Dict[str, str]:
return {
header_name.decode().lower(): header_value.decode()
for header_name, header_value in self.scope["headers"]
}
async def get_root_value(self, request: Optional["ChannelsConsumer"] = None) -> Any:
return None
async def get_context(
self,
request: Optional["ChannelsConsumer"] = None,
connection_params: Optional[Dict[str, Any]] = None,
) -> StrawberryChannelsContext:
return StrawberryChannelsContext(
request=request or self, connection_params=connection_params
)
async def dispatch(self, message: ChannelsMessage) -> None:
# AsyncConsumer will try to get a function for message["type"] to handle
# for both http/websocket types and also for layers communication.
# In case the type isn't one of those, pass it to the listen queue so
# that it can be consumed by self.channel_listen
type_ = message.get("type", "")
if type_ and not type_.startswith(("http.", "websocket.")):
for queue in self.listen_queues[type_]:
queue.put_nowait(message)
return
await super().dispatch(message)
async def channel_listen(
self,
type: str,
*,
timeout: Optional[float] = None,
groups: Sequence[str] = (),
) -> AsyncGenerator[Any, None]:
"""Listen for messages sent to this consumer.
Utility to listen for channels messages for this consumer inside
a resolver (usually inside a subscription).
Parameters:
type:
The type of the message to wait for.
timeout:
An optional timeout to wait for each subsequent message
groups:
An optional sequence of groups to receive messages from.
When passing this parameter, the groups will be registered
using `self.channel_layer.group_add` at the beggining of the
execution and then discarded using `self.channel_layer.group_discard`
at the end of the execution.
"""
if self.channel_layer is None:
raise RuntimeError(
"Layers integration is required listening for channels.\n"
"Check https://channels.readthedocs.io/en/stable/topics/channel_layers.html " # noqa:E501
"for more information"
)
added_groups = []
try:
# This queue will receive incoming messages for this generator instance
queue: asyncio.Queue = asyncio.Queue()
# Create a weak reference to the queue. Once we leave the current scope, it
# will be garbage collected
self.listen_queues[type].add(queue)
for group in groups:
await self.channel_layer.group_add(group, self.channel_name)
added_groups.append(group)
while True:
awaitable = queue.get()
if timeout is not None:
awaitable = asyncio.wait_for(awaitable, timeout)
try:
yield await awaitable
except asyncio.TimeoutError:
# TODO: shall we add log here and maybe in the suppress below?
return
finally:
for group in added_groups:
with contextlib.suppress(Exception):
await self.channel_layer.group_discard(group, self.channel_name)
class ChannelsWSConsumer(ChannelsConsumer, AsyncJsonWebsocketConsumer):
"""Base channels websocket async consumer."""
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/channels/handlers/base.py | base.py |
"""GraphQLHTTPHandler
A consumer to provide a graphql endpoint, and optionally graphiql.
"""
from __future__ import annotations
import dataclasses
import json
from typing import TYPE_CHECKING, Any, Optional
from urllib.parse import parse_qs
from channels.db import database_sync_to_async
from channels.generic.http import AsyncHttpConsumer
from strawberry.channels.context import StrawberryChannelsContext
from strawberry.exceptions import MissingQueryError
from strawberry.http import (
parse_query_params,
parse_request_data,
process_result,
)
from strawberry.schema.exceptions import InvalidOperationTypeError
from strawberry.types.graphql import OperationType
from strawberry.utils.graphiql import get_graphiql_html
from .base import ChannelsConsumer
if TYPE_CHECKING:
from strawberry.http import GraphQLHTTPResponse, GraphQLRequestData
from strawberry.schema import BaseSchema
from strawberry.types import ExecutionResult
class MethodNotAllowed(Exception):
...
class ExecutionError(Exception):
...
@dataclasses.dataclass
class Result:
response: bytes
status: int = 200
content_type: str = "application/json"
class GraphQLHTTPConsumer(ChannelsConsumer, AsyncHttpConsumer):
"""A consumer to provide a view for GraphQL over HTTP.
To use this, place it in your ProtocolTypeRouter for your channels project:
```
from strawberry.channels import GraphQLHttpRouter
from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application
application = ProtocolTypeRouter({
"http": URLRouter([
re_path("^graphql", GraphQLHTTPRouter(schema=schema)),
re_path("^", get_asgi_application()),
]),
"websocket": URLRouter([
re_path("^ws/graphql", GraphQLWebSocketRouter(schema=schema)),
]),
})
```
"""
def __init__(
self,
schema: BaseSchema,
graphiql: bool = True,
allow_queries_via_get: bool = True,
subscriptions_enabled: bool = True,
**kwargs,
):
self.schema = schema
self.graphiql = graphiql
self.allow_queries_via_get = allow_queries_via_get
self.subscriptions_enabled = subscriptions_enabled
super().__init__(**kwargs)
async def handle(self, body: bytes) -> None:
try:
if self.scope["method"] == "GET":
result = await self.get(body)
elif self.scope["method"] == "POST":
result = await self.post(body)
else:
raise MethodNotAllowed()
except MethodNotAllowed:
await self.send_response(
405,
b"Method not allowed",
headers=[(b"Allow", b"GET, POST")],
)
except InvalidOperationTypeError as e:
error_str = e.as_http_error_reason(self.scope["method"])
await self.send_response(
406,
error_str.encode(),
)
except ExecutionError as e:
await self.send_response(
500,
str(e).encode(),
)
else:
await self.send_response(
result.status,
result.response,
headers=[(b"Content-Type", result.content_type.encode())],
)
async def get(self, body: bytes) -> Result:
if self.should_render_graphiql():
return await self.render_graphiql(body)
elif self.scope.get("query_string"):
params = parse_query_params(
{
k: v[0]
for k, v in parse_qs(self.scope["query_string"].decode()).items()
}
)
try:
result = await self.execute(parse_request_data(params))
except MissingQueryError as e:
raise ExecutionError("No GraphQL query found in the request") from e
return Result(response=json.dumps(result).encode())
else:
raise MethodNotAllowed()
async def post(self, body: bytes) -> Result:
request_data = await self.parse_body(body)
try:
result = await self.execute(request_data)
except MissingQueryError as e:
raise ExecutionError("No GraphQL query found in the request") from e
return Result(response=json.dumps(result).encode())
async def parse_body(self, body: bytes) -> GraphQLRequestData:
if self.headers.get("content-type", "").startswith("multipart/form-data"):
return await self.parse_multipart_body(body)
try:
data = json.loads(body)
except json.JSONDecodeError as e:
raise ExecutionError("Unable to parse request body as JSON") from e
return parse_request_data(data)
async def parse_multipart_body(self, body: bytes) -> GraphQLRequestData:
raise ExecutionError("Unable to parse the multipart body")
async def execute(self, request_data: GraphQLRequestData) -> GraphQLHTTPResponse:
context = await self.get_context()
root_value = await self.get_root_value()
method = self.scope["method"]
allowed_operation_types = OperationType.from_http(method)
if not self.allow_queries_via_get and method == "GET":
allowed_operation_types = allowed_operation_types - {OperationType.QUERY}
result = await self.schema.execute(
query=request_data.query,
root_value=root_value,
variable_values=request_data.variables,
context_value=context,
operation_name=request_data.operation_name,
allowed_operation_types=allowed_operation_types,
)
return await self.process_result(result)
async def process_result(self, result: ExecutionResult) -> GraphQLHTTPResponse:
return process_result(result)
async def render_graphiql(self, body) -> Result:
html = get_graphiql_html(self.subscriptions_enabled)
return Result(response=html.encode(), content_type="text/html")
def should_render_graphiql(self) -> bool:
accept_list = self.headers.get("accept", "").split(",")
return self.graphiql and any(
accepted in accept_list for accepted in ["text/html", "*/*"]
)
class SyncGraphQLHTTPConsumer(GraphQLHTTPConsumer):
"""Synchronous version of the HTTPConsumer.
This is the same as `GraphQLHTTPConsumer`, but it can be used with
synchronous schemas (i.e. the schema's resolvers are espected to be
synchronous and not asynchronous).
"""
def get_root_value(self, request: Optional[ChannelsConsumer] = None) -> Any:
return None
def get_context( # type: ignore[override]
self,
request: Optional[ChannelsConsumer] = None,
) -> StrawberryChannelsContext:
return StrawberryChannelsContext(request=request or self)
def process_result( # type:ignore [override]
self, result: ExecutionResult
) -> GraphQLHTTPResponse:
return process_result(result)
# Sync channels is actually async, but it uses database_sync_to_async to call
# handlers in a threadpool. Check SyncConsumer's documentation for more info:
# https://github.com/django/channels/blob/main/channels/consumer.py#L104
@database_sync_to_async
def execute(self, request_data: GraphQLRequestData) -> GraphQLHTTPResponse:
context = self.get_context(self)
root_value = self.get_root_value(self)
method = self.scope["method"]
allowed_operation_types = OperationType.from_http(method)
if not self.allow_queries_via_get and method == "GET":
allowed_operation_types = allowed_operation_types - {OperationType.QUERY}
result = self.schema.execute_sync(
query=request_data.query,
root_value=root_value,
variable_values=request_data.variables,
context_value=context,
operation_name=request_data.operation_name,
allowed_operation_types=allowed_operation_types,
)
return self.process_result(result)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/channels/handlers/http_handler.py | http_handler.py |
from __future__ import annotations
import dataclasses
from typing import (
TYPE_CHECKING,
Any,
Callable,
Iterable,
List,
Optional,
Sequence,
Type,
TypeVar,
Union,
overload,
)
from strawberry.field import field as base_field
from strawberry.unset import UNSET
if TYPE_CHECKING:
from typing_extensions import Literal
from strawberry.field import _RESOLVER_TYPE, StrawberryField
from strawberry.permission import BasePermission
T = TypeVar("T")
@overload
def field(
*,
resolver: _RESOLVER_TYPE[T],
name: Optional[str] = None,
is_subscription: bool = False,
description: Optional[str] = None,
provides: Optional[List[str]] = None,
requires: Optional[List[str]] = None,
external: bool = False,
shareable: bool = False,
tags: Optional[Iterable[str]] = (),
override: Optional[str] = None,
inaccessible: bool = False,
init: Literal[False] = False,
permission_classes: Optional[List[Type[BasePermission]]] = None,
deprecation_reason: Optional[str] = None,
default: Any = UNSET,
default_factory: Union[Callable[..., object], object] = UNSET,
directives: Sequence[object] = (),
graphql_type: Optional[Any] = None,
) -> T:
...
@overload
def field(
*,
name: Optional[str] = None,
is_subscription: bool = False,
description: Optional[str] = None,
provides: Optional[List[str]] = None,
requires: Optional[List[str]] = None,
external: bool = False,
shareable: bool = False,
tags: Optional[Iterable[str]] = (),
override: Optional[str] = None,
inaccessible: bool = False,
init: Literal[True] = True,
permission_classes: Optional[List[Type[BasePermission]]] = None,
deprecation_reason: Optional[str] = None,
default: Any = UNSET,
default_factory: Union[Callable[..., object], object] = UNSET,
directives: Sequence[object] = (),
graphql_type: Optional[Any] = None,
) -> Any:
...
@overload
def field(
resolver: _RESOLVER_TYPE[T],
*,
name: Optional[str] = None,
is_subscription: bool = False,
description: Optional[str] = None,
provides: Optional[List[str]] = None,
requires: Optional[List[str]] = None,
external: bool = False,
shareable: bool = False,
tags: Optional[Iterable[str]] = (),
override: Optional[str] = None,
inaccessible: bool = False,
permission_classes: Optional[List[Type[BasePermission]]] = None,
deprecation_reason: Optional[str] = None,
default: Any = UNSET,
default_factory: Union[Callable[..., object], object] = UNSET,
directives: Sequence[object] = (),
graphql_type: Optional[Any] = None,
) -> StrawberryField:
...
def field(
resolver: Optional[_RESOLVER_TYPE[Any]] = None,
*,
name: Optional[str] = None,
is_subscription: bool = False,
description: Optional[str] = None,
provides: Optional[List[str]] = None,
requires: Optional[List[str]] = None,
external: bool = False,
shareable: bool = False,
tags: Optional[Iterable[str]] = (),
override: Optional[str] = None,
inaccessible: bool = False,
permission_classes: Optional[List[Type[BasePermission]]] = None,
deprecation_reason: Optional[str] = None,
default: Any = dataclasses.MISSING,
default_factory: Union[Callable[..., object], object] = dataclasses.MISSING,
directives: Sequence[object] = (),
graphql_type: Optional[Any] = None,
# This init parameter is used by PyRight to determine whether this field
# is added in the constructor or not. It is not used to change
# any behavior at the moment.
init: Literal[True, False, None] = None,
) -> Any:
from .schema_directives import (
External,
Inaccessible,
Override,
Provides,
Requires,
Shareable,
Tag,
)
directives = list(directives)
if provides:
directives.append(Provides(fields=" ".join(provides)))
if requires:
directives.append(Requires(fields=" ".join(requires)))
if external:
directives.append(External())
if shareable:
directives.append(Shareable())
if tags:
directives.extend(Tag(name=tag) for tag in tags)
if override:
directives.append(Override(override_from=override))
if inaccessible:
directives.append(Inaccessible())
return base_field( # type: ignore
resolver=resolver, # type: ignore
name=name,
is_subscription=is_subscription,
description=description,
permission_classes=permission_classes,
deprecation_reason=deprecation_reason,
default=default,
default_factory=default_factory,
init=init, # type: ignore
directives=directives,
graphql_type=graphql_type,
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/field.py | field.py |
import dataclasses
from typing import Callable, List, Optional, Type, TypeVar
from strawberry.directive import directive_field
from strawberry.field import StrawberryField, field
from strawberry.object_type import _wrap_dataclass
from strawberry.schema_directive import Location, StrawberrySchemaDirective
from strawberry.types.type_resolver import _get_fields
from strawberry.utils.typing import __dataclass_transform__
@dataclasses.dataclass
class ComposeOptions:
import_url: Optional[str]
@dataclasses.dataclass
class StrawberryFederationSchemaDirective(StrawberrySchemaDirective):
compose_options: Optional[ComposeOptions] = None
T = TypeVar("T", bound=Type)
@__dataclass_transform__(
order_default=True,
kw_only_default=True,
field_descriptors=(directive_field, field, StrawberryField),
)
def schema_directive(
*,
locations: List[Location],
description: Optional[str] = None,
name: Optional[str] = None,
repeatable: bool = False,
print_definition: bool = True,
compose: bool = False,
import_url: Optional[str] = None,
) -> Callable[..., T]:
def _wrap(cls: T) -> T:
cls = _wrap_dataclass(cls)
fields = _get_fields(cls)
cls.__strawberry_directive__ = StrawberryFederationSchemaDirective(
python_name=cls.__name__,
graphql_name=name,
locations=locations,
description=description,
repeatable=repeatable,
fields=fields,
print_definition=print_definition,
origin=cls,
compose_options=ComposeOptions(import_url=import_url) if compose else None,
)
return cls
return _wrap
__all__ = ["Location", "schema_directive"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/schema_directive.py | schema_directive.py |
from enum import Enum
from strawberry.custom_scalar import scalar
from strawberry.enum import enum
FieldSet = scalar(str, name="_FieldSet")
LinkImport = scalar(object, name="link__Import")
@enum(name="link__Purpose")
class LinkPurpose(Enum):
SECURITY = "SECURITY"
EXECUTION = "EXECUTION"
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/types.py | types.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Iterable, Optional, Union, overload
from strawberry.enum import _process_enum
from strawberry.enum import enum_value as base_enum_value
if TYPE_CHECKING:
from strawberry.enum import EnumType, EnumValueDefinition
def enum_value(
value: Any,
deprecation_reason: Optional[str] = None,
directives: Iterable[object] = (),
inaccessible: bool = False,
tags: Iterable[str] = (),
) -> EnumValueDefinition:
from strawberry.federation.schema_directives import Inaccessible, Tag
directives = list(directives)
if inaccessible:
directives.append(Inaccessible())
if tags:
directives.extend(Tag(name=tag) for tag in tags)
return base_enum_value(value, deprecation_reason, directives)
@overload
def enum(
_cls: EnumType,
*,
name=None,
description=None,
directives: Iterable[object] = (),
inaccessible: bool = False,
tags: Optional[Iterable[str]] = (),
) -> EnumType:
...
@overload
def enum(
_cls: None = None,
*,
name=None,
description=None,
directives: Iterable[object] = (),
inaccessible: bool = False,
tags: Optional[Iterable[str]] = (),
) -> Callable[[EnumType], EnumType]:
...
def enum(
_cls: Optional[EnumType] = None,
*,
name=None,
description=None,
directives=(),
inaccessible=False,
tags=(),
) -> Union[EnumType, Callable[[EnumType], EnumType]]:
"""Registers the enum in the GraphQL type system.
If name is passed, the name of the GraphQL type will be
the value passed of name instead of the Enum class name.
"""
from strawberry.federation.schema_directives import Inaccessible, Tag
directives = list(directives)
if inaccessible:
directives.append(Inaccessible())
if tags:
directives.extend(Tag(name=tag) for tag in tags)
def wrap(cls: EnumType) -> EnumType:
return _process_enum(cls, name, description, directives=directives)
if not _cls:
return wrap
return wrap(_cls) # pragma: no cover
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/enum.py | enum.py |
import sys
from typing import Any, Callable, Iterable, NewType, Optional, TypeVar, Union, overload
from strawberry.custom_scalar import _process_scalar
# in python 3.10+ NewType is a class
if sys.version_info >= (3, 10):
_T = TypeVar("_T", bound=Union[type, NewType])
else:
_T = TypeVar("_T", bound=type)
def identity(x: _T) -> _T: # pragma: no cover
return x
@overload
def scalar(
*,
name: Optional[str] = None,
description: Optional[str] = None,
specified_by_url: Optional[str] = None,
serialize: Callable = identity,
parse_value: Optional[Callable] = None,
parse_literal: Optional[Callable] = None,
directives: Iterable[object] = (),
inaccessible: bool = False,
tags: Optional[Iterable[str]] = (),
) -> Callable[[_T], _T]:
...
@overload
def scalar(
cls: _T,
*,
name: Optional[str] = None,
description: Optional[str] = None,
specified_by_url: Optional[str] = None,
serialize: Callable = identity,
parse_value: Optional[Callable] = None,
parse_literal: Optional[Callable] = None,
directives: Iterable[object] = (),
inaccessible: bool = False,
tags: Optional[Iterable[str]] = (),
) -> _T:
...
def scalar(
cls=None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
specified_by_url: Optional[str] = None,
serialize: Callable = identity,
parse_value: Optional[Callable] = None,
parse_literal: Optional[Callable] = None,
directives: Iterable[object] = (),
inaccessible: bool = False,
tags: Optional[Iterable[str]] = (),
) -> Any:
"""Annotates a class or type as a GraphQL custom scalar.
Example usages:
>>> strawberry.federation.scalar(
>>> datetime.date,
>>> serialize=lambda value: value.isoformat(),
>>> parse_value=datetime.parse_date
>>> )
>>> Base64Encoded = strawberry.federation.scalar(
>>> NewType("Base64Encoded", bytes),
>>> serialize=base64.b64encode,
>>> parse_value=base64.b64decode
>>> )
>>> @strawberry.federation.scalar(
>>> serialize=lambda value: ",".join(value.items),
>>> parse_value=lambda value: CustomList(value.split(","))
>>> )
>>> class CustomList:
>>> def __init__(self, items):
>>> self.items = items
"""
from strawberry.federation.schema_directives import Inaccessible, Tag
if parse_value is None:
parse_value = cls
directives = list(directives)
if inaccessible:
directives.append(Inaccessible())
if tags:
directives.extend(Tag(name=tag) for tag in tags)
def wrap(cls):
return _process_scalar(
cls,
name=name,
description=description,
specified_by_url=specified_by_url,
serialize=serialize,
parse_value=parse_value,
parse_literal=parse_literal,
directives=directives,
)
if cls is None:
return wrap
return wrap(cls)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/scalar.py | scalar.py |
from collections import defaultdict
from copy import copy
from functools import partial
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
DefaultDict,
Dict,
Iterable,
List,
Mapping,
Optional,
Set,
Type,
Union,
cast,
)
from graphql import (
GraphQLError,
GraphQLField,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLScalarType,
GraphQLUnionType,
)
from graphql.type.definition import GraphQLArgument
from strawberry.printer import print_schema
from strawberry.schema import Schema as BaseSchema
from strawberry.types.types import TypeDefinition
from strawberry.utils.cached_property import cached_property
from strawberry.utils.inspect import get_func_args
from .schema_directive import StrawberryFederationSchemaDirective
if TYPE_CHECKING:
from graphql import ExecutionContext as GraphQLExecutionContext
from graphql import GraphQLObjectType
from strawberry.custom_scalar import ScalarDefinition, ScalarWrapper
from strawberry.enum import EnumDefinition
from strawberry.extensions import SchemaExtension
from strawberry.federation.schema_directives import ComposeDirective
from strawberry.schema.config import StrawberryConfig
from strawberry.schema.types.concrete_type import TypeMap
from strawberry.schema_directive import StrawberrySchemaDirective
from strawberry.union import StrawberryUnion
class Schema(BaseSchema):
def __init__(
self,
query: Optional[Type] = None,
mutation: Optional[Type] = None,
subscription: Optional[Type] = None,
# TODO: we should update directives' type in the main schema
directives: Iterable[Type] = (),
types: Iterable[Type] = (),
extensions: Iterable[Union[Type["SchemaExtension"], "SchemaExtension"]] = (),
execution_context_class: Optional[Type["GraphQLExecutionContext"]] = None,
config: Optional["StrawberryConfig"] = None,
scalar_overrides: Optional[
Dict[object, Union[Type, "ScalarWrapper", "ScalarDefinition"]]
] = None,
schema_directives: Iterable[object] = (),
enable_federation_2: bool = False,
):
query = self._get_federation_query_type(query)
super().__init__(
query=query,
mutation=mutation,
subscription=subscription,
directives=directives, # type: ignore
types=types,
extensions=extensions,
execution_context_class=execution_context_class,
config=config,
scalar_overrides=scalar_overrides,
schema_directives=schema_directives,
)
self.schema_directives = list(schema_directives)
self._add_scalars()
self._add_entities_to_query()
if enable_federation_2:
composed_directives = self._add_compose_directives()
self._add_link_directives(composed_directives) # type: ignore
else:
self._remove_resolvable_field()
def _get_federation_query_type(self, query: Optional[Type]) -> Type:
"""Returns a new query type that includes the _service field.
If the query type is provided, it will be used as the base for the new
query type. Otherwise, a new query type will be created.
Federation needs the following two fields to be present in the query type:
- _service: This field is used by the gateway to query for the capabilities
of the federated service.
- _entities: This field is used by the gateway to query for the entities
that are part of the federated service.
The _service field is added by default, but the _entities field is only
added if the schema contains an entity type.
"""
# note we don't add the _entities field here, as we need to know if the
# schema contains an entity type first and we do that by leveraging
# the schema converter type map, so we don't have to do that twice
# TODO: ideally we should be able to do this without using the schema
# converter, but for now this is the easiest way to do it
# see `_add_entities_to_query`
import strawberry
from strawberry.tools.create_type import create_type
from strawberry.tools.merge_types import merge_types
@strawberry.type(name="_Service")
class Service:
sdl: str = strawberry.field(
resolver=lambda: print_schema(self),
)
@strawberry.field(name="_service")
def service() -> Service:
return Service()
fields = [service]
FederationQuery = create_type(name="Query", fields=fields)
if query is None:
return FederationQuery
query_type = merge_types(
"Query",
(
FederationQuery,
query,
),
)
# TODO: this should be probably done in merge_types
if query._type_definition.extend:
query_type._type_definition.extend = True # type: ignore
return query_type
def _add_entities_to_query(self):
entity_type = _get_entity_type(self.schema_converter.type_map)
if not entity_type:
return
self._schema.type_map[entity_type.name] = entity_type
fields = {"_entities": self._get_entities_field(entity_type)}
# Copy the query type, update it to use the modified fields
query_type = cast("GraphQLObjectType", self._schema.query_type)
fields.update(query_type.fields)
query_type = copy(query_type)
query_type._fields = fields
self._schema.query_type = query_type
self._schema.type_map[query_type.name] = query_type
def entities_resolver(self, root, info, representations) -> List[object]:
results = []
for representation in representations:
type_name = representation.pop("__typename")
type_ = self.schema_converter.type_map[type_name]
definition = cast(TypeDefinition, type_.definition)
if hasattr(definition.origin, "resolve_reference"):
resolve_reference = definition.origin.resolve_reference
func_args = get_func_args(resolve_reference)
kwargs = representation
# TODO: use the same logic we use for other resolvers
if "info" in func_args:
kwargs["info"] = info
get_result = partial(resolve_reference, **kwargs)
else:
from strawberry.arguments import convert_argument
strawberry_schema = info.schema.extensions["strawberry-definition"]
config = strawberry_schema.config
scalar_registry = strawberry_schema.schema_converter.scalar_registry
get_result = partial(
convert_argument,
representation,
type_=definition.origin,
scalar_registry=scalar_registry,
config=config,
)
try:
result = get_result()
except Exception as e:
result = GraphQLError(
f"Unable to resolve reference for {definition.origin}",
original_error=e,
)
results.append(result)
return results
def _add_scalars(self):
self.Any = GraphQLScalarType("_Any")
self._schema.type_map["_Any"] = self.Any
def _remove_resolvable_field(self) -> None:
# this might be removed when we remove support for federation 1
# or when we improve how we print the directives
from ..unset import UNSET
from .schema_directives import Key
for directive in self.schema_directives_in_use:
if isinstance(directive, Key):
directive.resolvable = UNSET
@cached_property
def schema_directives_in_use(self) -> List[object]:
all_graphql_types = self._schema.type_map.values()
directives: List[object] = []
for type_ in all_graphql_types:
strawberry_definition = type_.extensions.get("strawberry-definition")
if not strawberry_definition:
continue
directives.extend(strawberry_definition.directives)
fields = getattr(strawberry_definition, "fields", [])
values = getattr(strawberry_definition, "values", [])
for field in chain(fields, values):
directives.extend(field.directives)
return directives
def _add_link_for_composed_directive(
self,
directive: "StrawberrySchemaDirective",
directive_by_url: Mapping[str, Set[str]],
) -> None:
if not isinstance(directive, StrawberryFederationSchemaDirective):
return
if not directive.compose_options:
return
import_url = directive.compose_options.import_url
name = self.config.name_converter.from_directive(directive)
# import url is required by Apollo Federation, this might change in
# future to be optional, so for now, when it is not passed we
# define a mock one. The URL isn't used for validation anyway.
if import_url is None:
import_url = f"https://directives.strawberry.rocks/{name}/v0.1"
directive_by_url[import_url].add(f"@{name}")
def _add_link_directives(
self, additional_directives: Optional[List[object]] = None
):
from .schema_directives import FederationDirective, Link
directive_by_url: DefaultDict[str, Set[str]] = defaultdict(set)
additional_directives = additional_directives or []
for directive in self.schema_directives_in_use + additional_directives:
definition = directive.__strawberry_directive__ # type: ignore
self._add_link_for_composed_directive(definition, directive_by_url)
if isinstance(directive, FederationDirective):
directive_by_url[directive.imported_from.url].add(
f"@{directive.imported_from.name}"
)
link_directives: List[object] = [
Link(
url=url,
import_=list(sorted(directives)),
)
for url, directives in directive_by_url.items()
]
self.schema_directives = self.schema_directives + link_directives
def _add_compose_directives(self) -> List["ComposeDirective"]:
from .schema_directives import ComposeDirective
compose_directives: List[ComposeDirective] = []
for directive in self.schema_directives_in_use:
definition = directive.__strawberry_directive__ # type: ignore
is_federation_schema_directive = isinstance(
definition, StrawberryFederationSchemaDirective
)
if is_federation_schema_directive and definition.compose_options:
name = self.config.name_converter.from_directive(definition)
compose_directives.append(
ComposeDirective(
name=f"@{name}",
)
)
self.schema_directives = self.schema_directives + compose_directives
return compose_directives
def _get_entities_field(self, entity_type: GraphQLUnionType) -> GraphQLField:
return GraphQLField(
GraphQLNonNull(GraphQLList(entity_type)),
args={
"representations": GraphQLArgument(
GraphQLNonNull(GraphQLList(GraphQLNonNull(self.Any)))
)
},
resolve=self.entities_resolver,
)
def _warn_for_federation_directives(self) -> None:
# this is used in the main schema to raise if there's a directive
# that's for federation, but in this class we don't want to warn,
# since it is expected to have federation directives
pass
def _get_entity_type(type_map: "TypeMap"):
# https://www.apollographql.com/docs/apollo-server/federation/federation-spec/#resolve-requests-for-entities
# To implement the _Entity union, each type annotated with @key
# should be added to the _Entity union.
federation_key_types = [
type.implementation
for type in type_map.values()
if _has_federation_keys(type.definition)
# TODO: check this
and not isinstance(type.implementation, GraphQLInterfaceType)
]
# If no types are annotated with the key directive, then the _Entity
# union and Query._entities field should be removed from the schema.
if not federation_key_types:
return None
entity_type = GraphQLUnionType("_Entity", federation_key_types) # type: ignore
def _resolve_type(self, value, _type):
return self._type_definition.name
entity_type.resolve_type = _resolve_type
return entity_type
def _is_key(directive: Any) -> bool:
from .schema_directives import Key
return isinstance(directive, Key)
def _has_federation_keys(
definition: Union[
TypeDefinition, "ScalarDefinition", "EnumDefinition", "StrawberryUnion"
]
) -> bool:
if isinstance(definition, TypeDefinition):
return any(_is_key(directive) for directive in definition.directives or [])
return False
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/schema.py | schema.py |
from typing import Iterable, Optional
from strawberry.arguments import StrawberryArgumentAnnotation
def argument(
description: Optional[str] = None,
name: Optional[str] = None,
deprecation_reason: Optional[str] = None,
directives: Iterable[object] = (),
inaccessible: bool = False,
tags: Optional[Iterable[str]] = (),
) -> StrawberryArgumentAnnotation:
from strawberry.federation.schema_directives import Inaccessible, Tag
directives = list(directives)
if inaccessible:
directives.append(Inaccessible())
if tags:
directives.extend(Tag(name=tag) for tag in tags)
return StrawberryArgumentAnnotation(
description=description,
name=name,
deprecation_reason=deprecation_reason,
directives=directives,
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/argument.py | argument.py |
from .field import field
mutation = field
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/mutation.py | mutation.py |
from dataclasses import dataclass
from typing import ClassVar, List, Optional
from strawberry import directive_field
from strawberry.schema_directive import Location, schema_directive
from strawberry.unset import UNSET
from .types import FieldSet, LinkImport, LinkPurpose
@dataclass
class ImportedFrom:
name: str
url: str = "https://specs.apollo.dev/federation/v2.3"
class FederationDirective:
imported_from: ClassVar[ImportedFrom]
@schema_directive(
locations=[Location.FIELD_DEFINITION], name="external", print_definition=False
)
class External(FederationDirective):
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="external", url="https://specs.apollo.dev/federation/v2.3"
)
@schema_directive(
locations=[Location.FIELD_DEFINITION], name="requires", print_definition=False
)
class Requires(FederationDirective):
fields: FieldSet
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="requires", url="https://specs.apollo.dev/federation/v2.3"
)
@schema_directive(
locations=[Location.FIELD_DEFINITION], name="provides", print_definition=False
)
class Provides(FederationDirective):
fields: FieldSet
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="provides", url="https://specs.apollo.dev/federation/v2.3"
)
@schema_directive(
locations=[Location.OBJECT, Location.INTERFACE],
name="key",
repeatable=True,
print_definition=False,
)
class Key(FederationDirective):
fields: FieldSet
resolvable: Optional[bool] = True
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="key", url="https://specs.apollo.dev/federation/v2.3"
)
@schema_directive(
locations=[Location.FIELD_DEFINITION, Location.OBJECT],
name="shareable",
repeatable=True,
print_definition=False,
)
class Shareable(FederationDirective):
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="shareable", url="https://specs.apollo.dev/federation/v2.3"
)
@schema_directive(
locations=[Location.SCHEMA], name="link", repeatable=True, print_definition=False
)
class Link:
url: Optional[str]
as_: Optional[str] = directive_field(name="as")
for_: Optional[LinkPurpose] = directive_field(name="for")
import_: Optional[List[Optional[LinkImport]]] = directive_field(name="import")
def __init__(
self,
url: Optional[str] = UNSET,
as_: Optional[str] = UNSET,
for_: Optional[LinkPurpose] = UNSET,
import_: Optional[List[Optional[LinkImport]]] = UNSET,
):
self.url = url
self.as_ = as_
self.for_ = for_
self.import_ = import_
@schema_directive(
locations=[
Location.FIELD_DEFINITION,
Location.INTERFACE,
Location.OBJECT,
Location.UNION,
Location.ARGUMENT_DEFINITION,
Location.SCALAR,
Location.ENUM,
Location.ENUM_VALUE,
Location.INPUT_OBJECT,
Location.INPUT_FIELD_DEFINITION,
],
name="tag",
repeatable=True,
print_definition=False,
)
class Tag(FederationDirective):
name: str
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="tag", url="https://specs.apollo.dev/federation/v2.3"
)
@schema_directive(
locations=[Location.FIELD_DEFINITION], name="override", print_definition=False
)
class Override(FederationDirective):
override_from: str = directive_field(name="from")
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="override", url="https://specs.apollo.dev/federation/v2.3"
)
@schema_directive(
locations=[
Location.FIELD_DEFINITION,
Location.OBJECT,
Location.INTERFACE,
Location.UNION,
Location.ARGUMENT_DEFINITION,
Location.SCALAR,
Location.ENUM,
Location.ENUM_VALUE,
Location.INPUT_OBJECT,
Location.INPUT_FIELD_DEFINITION,
],
name="inaccessible",
print_definition=False,
)
class Inaccessible(FederationDirective):
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="inaccessible", url="https://specs.apollo.dev/federation/v2.3"
)
@schema_directive(
locations=[Location.SCHEMA], name="composeDirective", print_definition=False
)
class ComposeDirective(FederationDirective):
name: str
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="composeDirective", url="https://specs.apollo.dev/federation/v2.3"
)
@schema_directive(
locations=[Location.OBJECT], name="interfaceObject", print_definition=False
)
class InterfaceObject(FederationDirective):
imported_from: ClassVar[ImportedFrom] = ImportedFrom(
name="interfaceObject", url="https://specs.apollo.dev/federation/v2.3"
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/schema_directives.py | schema_directives.py |
from typing import (
TYPE_CHECKING,
Callable,
Iterable,
Optional,
Sequence,
Type,
TypeVar,
Union,
overload,
)
from strawberry.field import StrawberryField
from strawberry.field import field as base_field
from strawberry.object_type import type as base_type
from strawberry.unset import UNSET
from strawberry.utils.typing import __dataclass_transform__
from .field import field
if TYPE_CHECKING:
from .schema_directives import Key
T = TypeVar("T", bound=Type)
def _impl_type(
cls: Optional[T],
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Iterable[object] = (),
keys: Iterable[Union["Key", str]] = (),
extend: bool = False,
shareable: bool = False,
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
is_input: bool = False,
is_interface: bool = False,
is_interface_object: bool = False,
) -> T:
from strawberry.federation.schema_directives import (
Inaccessible,
InterfaceObject,
Key,
Shareable,
Tag,
)
directives = list(directives)
directives.extend(
Key(fields=key, resolvable=UNSET) if isinstance(key, str) else key
for key in keys
)
if shareable:
directives.append(Shareable())
if inaccessible is not UNSET:
directives.append(Inaccessible())
if tags:
directives.extend(Tag(name=tag) for tag in tags)
if is_interface_object:
directives.append(InterfaceObject())
return base_type( # type: ignore
cls,
name=name,
description=description,
directives=directives,
extend=extend,
is_input=is_input,
is_interface=is_interface,
)
@overload
@__dataclass_transform__(
order_default=True,
kw_only_default=True,
field_descriptors=(base_field, field, StrawberryField),
)
def type(
cls: T,
*,
name: Optional[str] = None,
description: Optional[str] = None,
keys: Iterable[Union["Key", str]] = (),
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
extend: bool = False,
) -> T:
...
@overload
@__dataclass_transform__(
order_default=True,
kw_only_default=True,
field_descriptors=(base_field, field, StrawberryField),
)
def type(
*,
name: Optional[str] = None,
description: Optional[str] = None,
keys: Iterable[Union["Key", str]] = (),
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
extend: bool = False,
shareable: bool = False,
directives: Iterable[object] = (),
) -> Callable[[T], T]:
...
def type(
cls: Optional[T] = None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
keys: Iterable[Union["Key", str]] = (),
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
extend: bool = False,
shareable: bool = False,
directives: Iterable[object] = (),
):
return _impl_type(
cls,
name=name,
description=description,
directives=directives,
keys=keys,
extend=extend,
shareable=shareable,
inaccessible=inaccessible,
tags=tags,
)
@overload
@__dataclass_transform__(
order_default=True,
kw_only_default=True,
field_descriptors=(base_field, field, StrawberryField),
)
def input(
cls: T,
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Sequence[object] = (),
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
) -> T:
...
@overload
@__dataclass_transform__(
order_default=True,
kw_only_default=True,
field_descriptors=(base_field, field, StrawberryField),
)
def input(
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Sequence[object] = (),
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
) -> Callable[[T], T]:
...
def input(
cls: Optional[T] = None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
directives: Sequence[object] = (),
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
):
return _impl_type(
cls,
name=name,
description=description,
directives=directives,
inaccessible=inaccessible,
is_input=True,
tags=tags,
)
@overload
@__dataclass_transform__(
order_default=True,
kw_only_default=True,
field_descriptors=(base_field, field, StrawberryField),
)
def interface(
cls: T,
*,
name: Optional[str] = None,
description: Optional[str] = None,
keys: Iterable[Union["Key", str]] = (),
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
directives: Iterable[object] = (),
) -> T:
...
@overload
@__dataclass_transform__(
order_default=True,
kw_only_default=True,
field_descriptors=(base_field, field, StrawberryField),
)
def interface(
*,
name: Optional[str] = None,
description: Optional[str] = None,
keys: Iterable[Union["Key", str]] = (),
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
directives: Iterable[object] = (),
) -> Callable[[T], T]:
...
def interface(
cls: Optional[T] = None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
keys: Iterable[Union["Key", str]] = (),
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
directives: Iterable[object] = (),
):
return _impl_type(
cls,
name=name,
description=description,
directives=directives,
keys=keys,
inaccessible=inaccessible,
is_interface=True,
tags=tags,
)
@overload
@__dataclass_transform__(
order_default=True,
kw_only_default=True,
field_descriptors=(base_field, field, StrawberryField),
)
def interface_object(
cls: T,
*,
keys: Iterable[Union["Key", str]],
name: Optional[str] = None,
description: Optional[str] = None,
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
directives: Iterable[object] = (),
) -> T:
...
@overload
@__dataclass_transform__(
order_default=True,
kw_only_default=True,
field_descriptors=(base_field, field, StrawberryField),
)
def interface_object(
*,
keys: Iterable[Union["Key", str]],
name: Optional[str] = None,
description: Optional[str] = None,
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
directives: Iterable[object] = (),
) -> Callable[[T], T]:
...
def interface_object(
cls: Optional[T] = None,
*,
keys: Iterable[Union["Key", str]],
name: Optional[str] = None,
description: Optional[str] = None,
inaccessible: bool = UNSET,
tags: Iterable[str] = (),
directives: Iterable[object] = (),
):
return _impl_type(
cls,
name=name,
description=description,
directives=directives,
keys=keys,
inaccessible=inaccessible,
is_interface=False,
is_interface_object=True,
tags=tags,
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/object_type.py | object_type.py |
from .argument import argument
from .enum import enum, enum_value
from .field import field
from .mutation import mutation
from .object_type import input, interface, interface_object, type
from .scalar import scalar
from .schema import Schema
from .schema_directive import schema_directive
from .union import union
__all__ = [
"argument",
"enum",
"enum_value",
"field",
"mutation",
"input",
"interface",
"interface_object",
"type",
"scalar",
"Schema",
"schema_directive",
"union",
]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/__init__.py | __init__.py |
from typing import Iterable, Optional, Tuple, Type, TypeVar, Union
from strawberry.union import union as base_union
Types = TypeVar("Types", bound=Type)
def union(
name: str,
types: Tuple[Types, ...],
*,
description: Optional[str] = None,
directives: Iterable[object] = (),
inaccessible: bool = False,
tags: Optional[Iterable[str]] = (),
) -> Union[Types]:
"""Creates a new named Union type.
Example usages:
>>> @strawberry.type
... class A: ...
>>> @strawberry.type
... class B: ...
>>> strawberry.federation.union("Name", (A, Optional[B]))
"""
from strawberry.federation.schema_directives import Inaccessible, Tag
directives = list(directives)
if inaccessible:
directives.append(Inaccessible())
if tags:
directives.extend(Tag(name=tag) for tag in tags)
return base_union(
name,
types,
description=description,
directives=directives,
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/federation/union.py | union.py |
GRAPHQL_TRANSPORT_WS_PROTOCOL = "graphql-transport-ws"
GRAPHQL_WS_PROTOCOL = "graphql-ws"
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/subscriptions/__init__.py | __init__.py |
from typing import Any, Dict, List, Optional, Union
from typing_extensions import TypedDict
from graphql import GraphQLFormattedError
ConnectionInitPayload = Dict[str, Any]
ConnectionErrorPayload = Dict[str, Any]
class StartPayload(TypedDict, total=False):
query: str
variables: Optional[Dict[str, Any]]
operationName: Optional[str]
class DataPayload(TypedDict, total=False):
data: Any
# Optional list of formatted graphql.GraphQLError objects
errors: Optional[List[GraphQLFormattedError]]
ErrorPayload = GraphQLFormattedError
OperationMessagePayload = Union[
ConnectionInitPayload,
ConnectionErrorPayload,
StartPayload,
DataPayload,
ErrorPayload,
]
class OperationMessage(TypedDict, total=False):
type: str
id: str
payload: OperationMessagePayload
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/subscriptions/protocols/graphql_ws/types.py | types.py |
GQL_CONNECTION_INIT = "connection_init"
GQL_CONNECTION_ACK = "connection_ack"
GQL_CONNECTION_ERROR = "connection_error"
GQL_CONNECTION_TERMINATE = "connection_terminate"
GQL_CONNECTION_KEEP_ALIVE = "ka"
GQL_START = "start"
GQL_DATA = "data"
GQL_ERROR = "error"
GQL_COMPLETE = "complete"
GQL_STOP = "stop"
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/subscriptions/protocols/graphql_ws/__init__.py | __init__.py |
from __future__ import annotations
import asyncio
from abc import ABC, abstractmethod
from contextlib import suppress
from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, Optional, cast
from graphql import ExecutionResult as GraphQLExecutionResult
from graphql import GraphQLError
from graphql.error.graphql_error import format_error as format_graphql_error
from strawberry.subscriptions.protocols.graphql_ws import (
GQL_COMPLETE,
GQL_CONNECTION_ACK,
GQL_CONNECTION_ERROR,
GQL_CONNECTION_INIT,
GQL_CONNECTION_KEEP_ALIVE,
GQL_CONNECTION_TERMINATE,
GQL_DATA,
GQL_ERROR,
GQL_START,
GQL_STOP,
)
from strawberry.utils.debug import pretty_print_graphql_operation
if TYPE_CHECKING:
from strawberry.schema import BaseSchema
from strawberry.subscriptions.protocols.graphql_ws.types import (
ConnectionInitPayload,
OperationMessage,
OperationMessagePayload,
StartPayload,
)
class BaseGraphQLWSHandler(ABC):
def __init__(
self,
schema: BaseSchema,
debug: bool,
keep_alive: bool,
keep_alive_interval: float,
):
self.schema = schema
self.debug = debug
self.keep_alive = keep_alive
self.keep_alive_interval = keep_alive_interval
self.keep_alive_task: Optional[asyncio.Task] = None
self.subscriptions: Dict[str, AsyncGenerator] = {}
self.tasks: Dict[str, asyncio.Task] = {}
self.connection_params: Optional[ConnectionInitPayload] = None
@abstractmethod
async def get_context(self) -> Any:
"""Return the operations context"""
@abstractmethod
async def get_root_value(self) -> Any:
"""Return the schemas root value"""
@abstractmethod
async def send_json(self, data: OperationMessage) -> None:
"""Send the data JSON encoded to the WebSocket client"""
@abstractmethod
async def close(self, code: int = 1000, reason: Optional[str] = None) -> None:
"""Close the WebSocket with the passed code and reason"""
@abstractmethod
async def handle_request(self) -> Any:
"""Handle the request this instance was created for"""
async def handle(self) -> Any:
return await self.handle_request()
async def handle_message(
self,
message: OperationMessage,
) -> None:
message_type = message["type"]
if message_type == GQL_CONNECTION_INIT:
await self.handle_connection_init(message)
elif message_type == GQL_CONNECTION_TERMINATE:
await self.handle_connection_terminate(message)
elif message_type == GQL_START:
await self.handle_start(message)
elif message_type == GQL_STOP:
await self.handle_stop(message)
async def handle_connection_init(self, message: OperationMessage) -> None:
payload = message.get("payload")
if payload is not None and not isinstance(payload, dict):
error_message: OperationMessage = {"type": GQL_CONNECTION_ERROR}
await self.send_json(error_message)
await self.close()
return
payload = cast(Optional["ConnectionInitPayload"], payload)
self.connection_params = payload
acknowledge_message: OperationMessage = {"type": GQL_CONNECTION_ACK}
await self.send_json(acknowledge_message)
if self.keep_alive:
keep_alive_handler = self.handle_keep_alive()
self.keep_alive_task = asyncio.create_task(keep_alive_handler)
async def handle_connection_terminate(self, message: OperationMessage) -> None:
await self.close()
async def handle_start(self, message: OperationMessage) -> None:
operation_id = message["id"]
payload = cast("StartPayload", message["payload"])
query = payload["query"]
operation_name = payload.get("operationName")
variables = payload.get("variables")
context = await self.get_context()
if isinstance(context, dict):
context["connection_params"] = self.connection_params
root_value = await self.get_root_value()
if self.debug:
pretty_print_graphql_operation(operation_name, query, variables)
try:
result_source = await self.schema.subscribe(
query=query,
variable_values=variables,
operation_name=operation_name,
context_value=context,
root_value=root_value,
)
except GraphQLError as error:
error_payload = format_graphql_error(error)
await self.send_message(GQL_ERROR, operation_id, error_payload)
self.schema.process_errors([error])
return
if isinstance(result_source, GraphQLExecutionResult):
assert result_source.errors
error_payload = format_graphql_error(result_source.errors[0])
await self.send_message(GQL_ERROR, operation_id, error_payload)
self.schema.process_errors(result_source.errors)
return
self.subscriptions[operation_id] = result_source
result_handler = self.handle_async_results(result_source, operation_id)
self.tasks[operation_id] = asyncio.create_task(result_handler)
async def handle_stop(self, message: OperationMessage) -> None:
operation_id = message["id"]
await self.cleanup_operation(operation_id)
async def handle_keep_alive(self) -> None:
while True:
data: OperationMessage = {"type": GQL_CONNECTION_KEEP_ALIVE}
await self.send_json(data)
await asyncio.sleep(self.keep_alive_interval)
async def handle_async_results(
self,
result_source: AsyncGenerator,
operation_id: str,
) -> None:
try:
async for result in result_source:
payload = {"data": result.data}
if result.errors:
payload["errors"] = [
format_graphql_error(err) for err in result.errors
]
await self.send_message(GQL_DATA, operation_id, payload)
# log errors after send_message to prevent potential
# slowdown of sending result
if result.errors:
self.schema.process_errors(result.errors)
except asyncio.CancelledError:
# CancelledErrors are expected during task cleanup.
pass
except Exception as error:
# GraphQLErrors are handled by graphql-core and included in the
# ExecutionResult
error = GraphQLError(str(error), original_error=error)
await self.send_message(
GQL_DATA,
operation_id,
{"data": None, "errors": [format_graphql_error(error)]},
)
self.schema.process_errors([error])
await self.send_message(GQL_COMPLETE, operation_id, None)
async def cleanup_operation(self, operation_id: str) -> None:
await self.subscriptions[operation_id].aclose()
del self.subscriptions[operation_id]
self.tasks[operation_id].cancel()
with suppress(BaseException):
await self.tasks[operation_id]
del self.tasks[operation_id]
async def send_message(
self,
type_: str,
operation_id: str,
payload: Optional[OperationMessagePayload] = None,
) -> None:
data: OperationMessage = {"type": type_, "id": operation_id}
if payload is not None:
data["payload"] = payload
await self.send_json(data)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/subscriptions/protocols/graphql_ws/handlers.py | handlers.py |
from __future__ import annotations
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from strawberry.unset import UNSET
if TYPE_CHECKING:
from graphql import GraphQLFormattedError
@dataclass
class GraphQLTransportMessage:
def as_dict(self) -> dict:
data = asdict(self)
if getattr(self, "payload", None) is UNSET:
# Unset fields must have a JSON value of "undefined" not "null"
data.pop("payload")
return data
@dataclass
class ConnectionInitMessage(GraphQLTransportMessage):
"""
Direction: Client -> Server
"""
payload: Optional[Dict[str, Any]] = UNSET
type: str = "connection_init"
@dataclass
class ConnectionAckMessage(GraphQLTransportMessage):
"""
Direction: Server -> Client
"""
payload: Optional[Dict[str, Any]] = UNSET
type: str = "connection_ack"
@dataclass
class PingMessage(GraphQLTransportMessage):
"""
Direction: bidirectional
"""
payload: Optional[Dict[str, Any]] = UNSET
type: str = "ping"
@dataclass
class PongMessage(GraphQLTransportMessage):
"""
Direction: bidirectional
"""
payload: Optional[Dict[str, Any]] = UNSET
type: str = "pong"
@dataclass
class SubscribeMessagePayload:
query: str
operationName: Optional[str] = None
variables: Optional[Dict[str, Any]] = None
extensions: Optional[Dict[str, Any]] = None
@dataclass
class SubscribeMessage(GraphQLTransportMessage):
"""
Direction: Client -> Server
"""
id: str
payload: SubscribeMessagePayload
type: str = "subscribe"
@dataclass
class NextMessage(GraphQLTransportMessage):
"""
Direction: Server -> Client
"""
id: str
payload: Dict[str, Any] # TODO: shape like ExecutionResult
type: str = "next"
def as_dict(self) -> dict:
return {"id": self.id, "payload": self.payload, "type": self.type}
@dataclass
class ErrorMessage(GraphQLTransportMessage):
"""
Direction: Server -> Client
"""
id: str
payload: List[GraphQLFormattedError]
type: str = "error"
@dataclass
class CompleteMessage(GraphQLTransportMessage):
"""
Direction: bidirectional
"""
id: str
type: str = "complete"
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/subscriptions/protocols/graphql_transport_ws/types.py | types.py |
# Code 4406 is "Subprotocol not acceptable"
WS_4406_PROTOCOL_NOT_ACCEPTABLE = 4406
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/subscriptions/protocols/graphql_transport_ws/__init__.py | __init__.py |
from __future__ import annotations
import asyncio
from abc import ABC, abstractmethod
from contextlib import suppress
from typing import TYPE_CHECKING, Any, AsyncGenerator, Callable, Dict, List, Optional
from graphql import ExecutionResult as GraphQLExecutionResult
from graphql import GraphQLError, GraphQLSyntaxError, parse
from graphql.error.graphql_error import format_error as format_graphql_error
from strawberry.subscriptions.protocols.graphql_transport_ws.types import (
CompleteMessage,
ConnectionAckMessage,
ConnectionInitMessage,
ErrorMessage,
NextMessage,
PingMessage,
PongMessage,
SubscribeMessage,
SubscribeMessagePayload,
)
from strawberry.types.graphql import OperationType
from strawberry.unset import UNSET
from strawberry.utils.debug import pretty_print_graphql_operation
from strawberry.utils.operation import get_operation_type
if TYPE_CHECKING:
from datetime import timedelta
from strawberry.schema import BaseSchema
from strawberry.subscriptions.protocols.graphql_transport_ws.types import (
GraphQLTransportMessage,
)
class BaseGraphQLTransportWSHandler(ABC):
def __init__(
self,
schema: BaseSchema,
debug: bool,
connection_init_wait_timeout: timedelta,
):
self.schema = schema
self.debug = debug
self.connection_init_wait_timeout = connection_init_wait_timeout
self.connection_init_timeout_task: Optional[asyncio.Task] = None
self.connection_init_received = False
self.connection_acknowledged = False
self.subscriptions: Dict[str, AsyncGenerator] = {}
self.tasks: Dict[str, asyncio.Task] = {}
self.completed_tasks: List[asyncio.Task] = []
self.connection_params: Optional[Dict[str, Any]] = None
@abstractmethod
async def get_context(self) -> Any:
"""Return the operations context"""
@abstractmethod
async def get_root_value(self) -> Any:
"""Return the schemas root value"""
@abstractmethod
async def send_json(self, data: dict) -> None:
"""Send the data JSON encoded to the WebSocket client"""
@abstractmethod
async def close(self, code: int, reason: str) -> None:
"""Close the WebSocket with the passed code and reason"""
@abstractmethod
async def handle_request(self) -> Any:
"""Handle the request this instance was created for"""
async def handle(self) -> Any:
timeout_handler = self.handle_connection_init_timeout()
self.connection_init_timeout_task = asyncio.create_task(timeout_handler)
return await self.handle_request()
async def handle_connection_init_timeout(self) -> None:
delay = self.connection_init_wait_timeout.total_seconds()
await asyncio.sleep(delay=delay)
if self.connection_init_received:
return
reason = "Connection initialisation timeout"
await self.close(code=4408, reason=reason)
async def handle_message(self, message: dict) -> None:
handler: Callable
handler_arg: Any
try:
message_type = message.pop("type")
if message_type == ConnectionInitMessage.type:
handler = self.handle_connection_init
handler_arg = ConnectionInitMessage(**message)
elif message_type == PingMessage.type:
handler = self.handle_ping
handler_arg = PingMessage(**message)
elif message_type == PongMessage.type:
handler = self.handle_pong
handler_arg = PongMessage(**message)
elif message_type == SubscribeMessage.type:
handler = self.handle_subscribe
payload = SubscribeMessagePayload(**message.pop("payload"))
handler_arg = SubscribeMessage(payload=payload, **message)
elif message_type == CompleteMessage.type:
handler = self.handle_complete
handler_arg = CompleteMessage(**message)
else:
handler = self.handle_invalid_message
handler_arg = f"Unknown message type: {message_type}"
except (KeyError, TypeError):
handler = self.handle_invalid_message
handler_arg = "Failed to parse message"
await handler(handler_arg)
await self.reap_completed_tasks()
async def handle_connection_init(self, message: ConnectionInitMessage) -> None:
if message.payload is not UNSET and not isinstance(message.payload, dict):
await self.close(code=4400, reason="Invalid connection init payload")
return
self.connection_params = message.payload
if self.connection_init_received:
reason = "Too many initialisation requests"
await self.close(code=4429, reason=reason)
return
self.connection_init_received = True
await self.send_message(ConnectionAckMessage())
self.connection_acknowledged = True
async def handle_ping(self, message: PingMessage) -> None:
await self.send_message(PongMessage())
async def handle_pong(self, message: PongMessage) -> None:
pass
async def handle_subscribe(self, message: SubscribeMessage) -> None:
if not self.connection_acknowledged:
await self.close(code=4401, reason="Unauthorized")
return
try:
graphql_document = parse(message.payload.query)
except GraphQLSyntaxError as exc:
await self.close(code=4400, reason=exc.message)
return
try:
operation_type = get_operation_type(
graphql_document, message.payload.operationName
)
except RuntimeError:
await self.close(code=4400, reason="Can't get GraphQL operation type")
return
if message.id in self.subscriptions:
reason = f"Subscriber for {message.id} already exists"
await self.close(code=4409, reason=reason)
return
if self.debug: # pragma: no cover
pretty_print_graphql_operation(
message.payload.operationName,
message.payload.query,
message.payload.variables,
)
context = await self.get_context()
if isinstance(context, dict):
context["connection_params"] = self.connection_params
root_value = await self.get_root_value()
# Get an AsyncGenerator yielding the results
if operation_type == OperationType.SUBSCRIPTION:
result_source = await self.schema.subscribe(
query=message.payload.query,
variable_values=message.payload.variables,
operation_name=message.payload.operationName,
context_value=context,
root_value=root_value,
)
else:
# create AsyncGenerator returning a single result
async def get_result_source():
yield await self.schema.execute(
query=message.payload.query,
variable_values=message.payload.variables,
context_value=context,
root_value=root_value,
operation_name=message.payload.operationName,
)
result_source = get_result_source()
operation = Operation(self, message.id)
# Handle initial validation errors
if isinstance(result_source, GraphQLExecutionResult):
assert result_source.errors
payload = [format_graphql_error(result_source.errors[0])]
await self.send_message(ErrorMessage(id=message.id, payload=payload))
self.schema.process_errors(result_source.errors)
return
# Create task to handle this subscription, reserve the operation ID
self.subscriptions[message.id] = result_source
self.tasks[message.id] = asyncio.create_task(
self.operation_task(result_source, operation)
)
async def operation_task(
self, result_source: AsyncGenerator, operation: Operation
) -> None:
"""
Operation task top level method. Cleans up and de-registers the operation
once it is done.
"""
try:
await self.handle_async_results(result_source, operation)
except BaseException: # pragma: no cover
# cleanup in case of something really unexpected
# wait for generator to be closed to ensure that any existing
# 'finally' statement is called
result_source = self.subscriptions[operation.id]
with suppress(RuntimeError):
await result_source.aclose()
del self.subscriptions[operation.id]
del self.tasks[operation.id]
raise
else:
await operation.send_message(CompleteMessage(id=operation.id))
finally:
# add this task to a list to be reaped later
task = asyncio.current_task()
assert task is not None
self.completed_tasks.append(task)
async def handle_async_results(
self,
result_source: AsyncGenerator,
operation: Operation,
) -> None:
try:
async for result in result_source:
if result.errors:
error_payload = [format_graphql_error(err) for err in result.errors]
error_message = ErrorMessage(id=operation.id, payload=error_payload)
await operation.send_message(error_message)
self.schema.process_errors(result.errors)
return
else:
next_payload = {"data": result.data}
next_message = NextMessage(id=operation.id, payload=next_payload)
await operation.send_message(next_message)
except asyncio.CancelledError:
# CancelledErrors are expected during task cleanup.
return
except Exception as error:
# GraphQLErrors are handled by graphql-core and included in the
# ExecutionResult
error = GraphQLError(str(error), original_error=error)
error_payload = [format_graphql_error(error)]
error_message = ErrorMessage(id=operation.id, payload=error_payload)
await operation.send_message(error_message)
self.schema.process_errors([error])
return
def forget_id(self, id: str) -> None:
# de-register the operation id making it immediately available
# for re-use
del self.subscriptions[id]
del self.tasks[id]
async def handle_complete(self, message: CompleteMessage) -> None:
await self.cleanup_operation(operation_id=message.id)
async def handle_invalid_message(self, error_message: str) -> None:
await self.close(code=4400, reason=error_message)
async def send_message(self, message: GraphQLTransportMessage) -> None:
data = message.as_dict()
await self.send_json(data)
async def cleanup_operation(self, operation_id: str) -> None:
if operation_id not in self.subscriptions:
return
result_source = self.subscriptions.pop(operation_id)
task = self.tasks.pop(operation_id)
task.cancel()
with suppress(BaseException):
await task
# since python 3.8, generators cannot be reliably closed
with suppress(RuntimeError):
await result_source.aclose()
async def reap_completed_tasks(self) -> None:
"""
Await tasks that have completed
"""
tasks, self.completed_tasks = self.completed_tasks, []
for task in tasks:
with suppress(BaseException):
await task
class Operation:
"""
A class encapsulating a single operation with its id.
Helps enforce protocol state transition.
"""
__slots__ = ["handler", "id", "completed"]
def __init__(self, handler: BaseGraphQLTransportWSHandler, id: str):
self.handler = handler
self.id = id
self.completed = False
async def send_message(self, message: GraphQLTransportMessage) -> None:
if self.completed:
return
if isinstance(message, (CompleteMessage, ErrorMessage)):
self.completed = True
# de-register the operation _before_ sending the final message
self.handler.forget_id(self.id)
await self.handler.send_message(message)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/subscriptions/protocols/graphql_transport_ws/handlers.py | handlers.py |
from dataclasses import dataclass
@dataclass
class TemporalResponse:
status_code: int = 200
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/http/temporal_response.py | temporal_response.py |
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional
from typing_extensions import TypedDict
from graphql.error.graphql_error import format_error as format_graphql_error
if TYPE_CHECKING:
from strawberry.types import ExecutionResult
class GraphQLHTTPResponse(TypedDict, total=False):
data: Optional[Dict[str, object]]
errors: Optional[List[object]]
extensions: Optional[Dict[str, object]]
def process_result(result: ExecutionResult) -> GraphQLHTTPResponse:
data: GraphQLHTTPResponse = {"data": result.data}
if result.errors:
data["errors"] = [format_graphql_error(err) for err in result.errors]
if result.extensions:
data["extensions"] = result.extensions
return data
@dataclass
class GraphQLRequestData:
# query is optional here as it can be added by an extensions
# (for example an extension for persisted queries)
query: Optional[str]
variables: Optional[Dict[str, Any]]
operation_name: Optional[str]
def parse_query_params(params: Dict[str, str]) -> Dict[str, Any]:
if "variables" in params:
params["variables"] = json.loads(params["variables"])
return params
def parse_request_data(data: Mapping[str, Any]) -> GraphQLRequestData:
return GraphQLRequestData(
query=data.get("query"),
variables=data.get("variables"),
operation_name=data.get("operationName"),
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/http/__init__.py | __init__.py |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from django.http import HttpRequest, HttpResponse
@dataclass
class StrawberryDjangoContext:
request: HttpRequest
response: HttpResponse
def __getitem__(self, key: str):
# __getitem__ override needed to avoid issues for who's
# using info.context["request"]
return super().__getattribute__(key)
def get(self, key: str) -> Any:
"""Enable .get notation for accessing the request"""
return super().__getattribute__(key)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/django/context.py | context.py |
from django.apps import AppConfig # pragma: no cover
class StrawberryConfig(AppConfig): # pragma: no cover
name = "strawberry"
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/django/apps.py | apps.py |
from __future__ import annotations
import asyncio
import json
import warnings
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Type, Union
from django.core.exceptions import BadRequest, SuspiciousOperation
from django.core.serializers.json import DjangoJSONEncoder
from django.http import Http404, HttpResponseNotAllowed, JsonResponse
from django.http.response import HttpResponse
from django.template import RequestContext, Template
from django.template.exceptions import TemplateDoesNotExist
from django.template.loader import render_to_string
from django.template.response import TemplateResponse
from django.utils.decorators import classonlymethod, method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from strawberry.exceptions import MissingQueryError
from strawberry.file_uploads.utils import replace_placeholders_with_files
from strawberry.http import (
parse_query_params,
parse_request_data,
process_result,
)
from strawberry.schema.exceptions import InvalidOperationTypeError
from strawberry.types.graphql import OperationType
from strawberry.utils.graphiql import get_graphiql_html
from .context import StrawberryDjangoContext
if TYPE_CHECKING:
from django.http import HttpRequest
from strawberry.http import GraphQLHTTPResponse, GraphQLRequestData
from strawberry.types import ExecutionResult
from ..schema import BaseSchema
class TemporalHttpResponse(JsonResponse):
status_code = None
def __init__(self) -> None:
super().__init__({})
def __repr__(self) -> str:
"""Adopted from Django to handle `status_code=None`."""
if self.status_code is not None:
return super().__repr__()
return "<{cls} status_code={status_code}{content_type}>".format(
cls=self.__class__.__name__,
status_code=self.status_code,
content_type=self._content_type_for_repr,
)
class BaseView(View):
subscriptions_enabled = False
graphiql = True
allow_queries_via_get = True
schema: Optional[BaseSchema] = None
json_encoder: Optional[Type[json.JSONEncoder]] = None
json_dumps_params: Optional[Dict[str, Any]] = None
def __init__(
self,
schema: BaseSchema,
graphiql: bool = True,
allow_queries_via_get: bool = True,
subscriptions_enabled: bool = False,
**kwargs: Any,
):
self.schema = schema
self.graphiql = graphiql
self.allow_queries_via_get = allow_queries_via_get
self.subscriptions_enabled = subscriptions_enabled
super().__init__(**kwargs)
self.json_dumps_params = kwargs.pop("json_dumps_params", self.json_dumps_params)
if self.json_dumps_params:
warnings.warn(
"json_dumps_params is deprecated, override encode_json instead",
DeprecationWarning,
stacklevel=2,
)
self.json_encoder = DjangoJSONEncoder
self.json_encoder = kwargs.pop("json_encoder", self.json_encoder)
if self.json_encoder is not None:
warnings.warn(
"json_encoder is deprecated, override encode_json instead",
DeprecationWarning,
stacklevel=2,
)
def parse_body(self, request: HttpRequest) -> Dict[str, Any]:
content_type = request.content_type or ""
if "application/json" in content_type:
return json.loads(request.body)
elif content_type.startswith("multipart/form-data"):
data = json.loads(request.POST.get("operations", "{}"))
files_map = json.loads(request.POST.get("map", "{}"))
data = replace_placeholders_with_files(data, files_map, request.FILES)
return data
elif request.method.lower() == "get" and request.META.get("QUERY_STRING"):
return parse_query_params(request.GET.copy())
return json.loads(request.body)
def is_request_allowed(self, request: HttpRequest) -> bool:
return request.method.lower() in ("get", "post")
def should_render_graphiql(self, request: HttpRequest) -> bool:
if request.method.lower() != "get":
return False
if self.allow_queries_via_get and request.META.get("QUERY_STRING"):
return False
return any(
supported_header in request.META.get("HTTP_ACCEPT", "")
for supported_header in ("text/html", "*/*")
)
def get_request_data(self, request: HttpRequest) -> GraphQLRequestData:
try:
data = self.parse_body(request)
except json.decoder.JSONDecodeError:
raise SuspiciousOperation("Unable to parse request body as JSON")
except KeyError:
raise BadRequest("File(s) missing in form data")
return parse_request_data(data)
def _render_graphiql(self, request: HttpRequest, context=None) -> TemplateResponse:
if not self.graphiql:
raise Http404()
try:
template = Template(render_to_string("graphql/graphiql.html"))
except TemplateDoesNotExist:
template = Template(get_graphiql_html(replace_variables=False))
context = context or {}
context.update({"SUBSCRIPTION_ENABLED": json.dumps(self.subscriptions_enabled)})
response = TemplateResponse(request=request, template=None, context=context)
response.content = template.render(RequestContext(request, context))
return response
def _create_response(
self, response_data: GraphQLHTTPResponse, sub_response: HttpResponse
) -> HttpResponse:
data = self.encode_json(response_data)
response = HttpResponse(
data,
content_type="application/json",
)
for name, value in sub_response.items():
response[name] = value
if sub_response.status_code is not None:
response.status_code = sub_response.status_code
for name, value in sub_response.cookies.items():
response.cookies[name] = value
return response
def encode_json(self, response_data: GraphQLHTTPResponse) -> str:
if self.json_dumps_params:
assert self.json_encoder
return json.dumps(
response_data, cls=self.json_encoder, **self.json_dumps_params
)
if self.json_encoder:
return json.dumps(response_data, cls=self.json_encoder)
return json.dumps(response_data)
class GraphQLView(BaseView):
def get_root_value(self, request: HttpRequest) -> Any:
return None
def get_context(self, request: HttpRequest, response: HttpResponse) -> Any:
return StrawberryDjangoContext(request=request, response=response)
def process_result(
self, request: HttpRequest, result: ExecutionResult
) -> GraphQLHTTPResponse:
return process_result(result)
@method_decorator(csrf_exempt)
def dispatch(
self, request, *args, **kwargs
) -> Union[HttpResponseNotAllowed, TemplateResponse, HttpResponse]:
if not self.is_request_allowed(request):
return HttpResponseNotAllowed(
["GET", "POST"], "GraphQL only supports GET and POST requests."
)
if self.should_render_graphiql(request):
return self._render_graphiql(request)
request_data = self.get_request_data(request)
sub_response = TemporalHttpResponse()
context = self.get_context(request, response=sub_response)
root_value = self.get_root_value(request)
method = request.method
allowed_operation_types = OperationType.from_http(method)
if not self.allow_queries_via_get and method == "GET":
allowed_operation_types = allowed_operation_types - {OperationType.QUERY}
assert self.schema
try:
result = self.schema.execute_sync(
request_data.query,
root_value=root_value,
variable_values=request_data.variables,
context_value=context,
operation_name=request_data.operation_name,
allowed_operation_types=allowed_operation_types,
)
except InvalidOperationTypeError as e:
raise BadRequest(e.as_http_error_reason(method)) from e
except MissingQueryError:
raise SuspiciousOperation("No GraphQL query found in the request")
response_data = self.process_result(request=request, result=result)
return self._create_response(
response_data=response_data, sub_response=sub_response
)
class AsyncGraphQLView(BaseView):
@classonlymethod
def as_view(cls, **initkwargs) -> Callable[..., HttpResponse]:
# This code tells django that this view is async, see docs here:
# https://docs.djangoproject.com/en/3.1/topics/async/#async-views
view = super().as_view(**initkwargs)
view._is_coroutine = asyncio.coroutines._is_coroutine # type: ignore[attr-defined] # noqa: E501
return view
@method_decorator(csrf_exempt)
async def dispatch(
self, request, *args, **kwargs
) -> Union[HttpResponseNotAllowed, TemplateResponse, HttpResponse]:
if not self.is_request_allowed(request):
return HttpResponseNotAllowed(
["GET", "POST"], "GraphQL only supports GET and POST requests."
)
if self.should_render_graphiql(request):
return self._render_graphiql(request)
request_data = self.get_request_data(request)
sub_response = TemporalHttpResponse()
context = await self.get_context(request, response=sub_response)
root_value = await self.get_root_value(request)
method = request.method
allowed_operation_types = OperationType.from_http(method)
if not self.allow_queries_via_get and method == "GET":
allowed_operation_types = allowed_operation_types - {OperationType.QUERY}
assert self.schema
try:
result = await self.schema.execute(
request_data.query,
root_value=root_value,
variable_values=request_data.variables,
context_value=context,
operation_name=request_data.operation_name,
allowed_operation_types=allowed_operation_types,
)
except InvalidOperationTypeError as e:
raise BadRequest(e.as_http_error_reason(method)) from e
except MissingQueryError:
raise SuspiciousOperation("No GraphQL query found in the request")
response_data = await self.process_result(request=request, result=result)
return self._create_response(
response_data=response_data, sub_response=sub_response
)
async def get_root_value(self, request: HttpRequest) -> Any:
return None
async def get_context(self, request: HttpRequest, response: HttpResponse) -> Any:
return StrawberryDjangoContext(request=request, response=response)
async def process_result(
self, request: HttpRequest, result: ExecutionResult
) -> GraphQLHTTPResponse:
return process_result(result)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/django/views.py | views.py |
try:
# import modules and objects from external strawberry-graphql-django
# package so that it can be used through strawberry.django namespace
from strawberry_django import * # noqa: F403
except ModuleNotFoundError:
import importlib
def __getattr__(name):
# try to import submodule and raise exception only if it does not exist
import_symbol = f"{__name__}.{name}"
try:
return importlib.import_module(import_symbol)
except ModuleNotFoundError:
raise AttributeError(
f"Attempted import of {import_symbol} failed. Make sure to install the"
"'strawberry-graphql-django' package to use the Strawberry Django "
"extension API."
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/django/__init__.py | __init__.py |
from typing import Any, Dict, Optional
from strawberry.test import BaseGraphQLTestClient
class GraphQLTestClient(BaseGraphQLTestClient):
def request(
self,
body: Dict[str, object],
headers: Optional[Dict[str, object]] = None,
files: Optional[Dict[str, object]] = None,
) -> Any:
if files:
return self._client.post(
self.url, data=body, format="multipart", headers=headers
)
return self._client.post(
self.url, data=body, content_type="application/json", headers=headers
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/django/test/client.py | client.py |
from .client import GraphQLTestClient
__all__ = ["GraphQLTestClient"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/django/test/__init__.py | __init__.py |
import os
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware
from strawberry import Schema
from strawberry.asgi import GraphQL
from strawberry.cli.constants import (
DEBUG_SERVER_LOG_OPERATIONS,
DEBUG_SERVER_SCHEMA_ENV_VAR_KEY,
)
from strawberry.utils.importer import import_module_symbol
app = Starlette(debug=True)
app.add_middleware(
CORSMiddleware, allow_headers=["*"], allow_origins=["*"], allow_methods=["*"]
)
schema_import_string = os.environ[DEBUG_SERVER_SCHEMA_ENV_VAR_KEY]
schema_symbol = import_module_symbol(schema_import_string, default_symbol_name="schema")
log_operations = os.environ[DEBUG_SERVER_LOG_OPERATIONS] == "True"
assert isinstance(schema_symbol, Schema)
graphql_app = GraphQL(schema_symbol, debug=log_operations)
paths = ["/", "/graphql"]
for path in paths:
app.add_route(path, graphql_app)
app.add_websocket_route(path, graphql_app)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/cli/debug_server.py | debug_server.py |
DEBUG_SERVER_SCHEMA_ENV_VAR_KEY = "STRAWBERRY_DEBUG_SERVER_SCHEMA"
DEBUG_SERVER_LOG_OPERATIONS = "STRAWBERRY_DEBUG_SERVER_LOG_OPERATIONS"
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/cli/constants.py | constants.py |
import click
from .commands.codegen import codegen as cmd_codegen
from .commands.export_schema import export_schema as cmd_export_schema
from .commands.server import server as cmd_server
@click.group()
def run() -> None: # pragma: no cover
pass
run.add_command(cmd_server)
run.add_command(cmd_export_schema)
run.add_command(cmd_codegen)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/cli/__init__.py | __init__.py |
import sys
import click
from strawberry import Schema
from strawberry.utils.importer import import_module_symbol
def load_schema(schema: str, app_dir: str) -> Schema:
sys.path.insert(0, app_dir)
try:
schema_symbol = import_module_symbol(schema, default_symbol_name="schema")
except (ImportError, AttributeError) as exc:
message = str(exc)
raise click.BadArgumentUsage(message)
if not isinstance(schema_symbol, Schema):
message = "The `schema` must be an instance of strawberry.Schema"
raise click.BadArgumentUsage(message)
return schema_symbol
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/cli/utils/__init__.py | __init__.py |
from __future__ import annotations
import importlib
import inspect
from pathlib import Path
from typing import TYPE_CHECKING, List, Optional, Type
import click
from strawberry.cli.utils import load_schema
from strawberry.codegen import QueryCodegen, QueryCodegenPlugin
if TYPE_CHECKING:
from strawberry.codegen import CodegenResult
def _is_codegen_plugin(obj: object) -> bool:
return (
inspect.isclass(obj)
and issubclass(obj, QueryCodegenPlugin)
and obj is not QueryCodegenPlugin
)
def _import_plugin(plugin: str) -> Optional[Type[QueryCodegenPlugin]]:
module_name = plugin
symbol_name: Optional[str] = None
if ":" in plugin:
module_name, symbol_name = plugin.split(":", 1)
try:
module = importlib.import_module(module_name)
except ModuleNotFoundError:
return None
if symbol_name:
obj = getattr(module, symbol_name)
assert _is_codegen_plugin(obj)
return obj
else:
symbols = {
key: value
for key, value in module.__dict__.items()
if not key.startswith("__")
}
if "__all__" in module.__dict__:
symbols = {
name: symbol
for name, symbol in symbols.items()
if name in module.__dict__["__all__"]
}
for obj in symbols.values():
if _is_codegen_plugin(obj):
return obj
return None
def _load_plugin(plugin_path: str) -> Type[QueryCodegenPlugin]:
# try to import plugin_name from current folder
# then try to import from strawberry.codegen.plugins
plugin = _import_plugin(plugin_path)
if plugin is None and "." not in plugin_path:
plugin = _import_plugin(f"strawberry.codegen.plugins.{plugin_path}")
if plugin is None:
raise click.ClickException(f"Plugin {plugin_path} not found")
return plugin
def _load_plugins(plugins: List[str]) -> List[QueryCodegenPlugin]:
return [_load_plugin(plugin)() for plugin in plugins]
class ConsolePlugin(QueryCodegenPlugin):
def __init__(
self, query: Path, output_dir: Path, plugins: List[QueryCodegenPlugin]
):
self.query = query
self.output_dir = output_dir
self.plugins = plugins
def on_start(self) -> None:
click.echo(
click.style(
"The codegen is experimental. Please submit any bug at "
"https://github.com/strawberry-graphql/strawberry\n",
fg="yellow",
bold=True,
)
)
plugin_names = [plugin.__class__.__name__ for plugin in self.plugins]
click.echo(
click.style(
f"Generating code for {self.query} using "
f"{', '.join(plugin_names)} plugin(s)",
fg="green",
)
)
def on_end(self, result: CodegenResult) -> None:
self.output_dir.mkdir(parents=True, exist_ok=True)
result.write(self.output_dir)
click.echo(
click.style(
f"Generated {len(result.files)} files in {self.output_dir}", fg="green"
)
)
@click.command(short_help="Generate code from a query")
@click.option("--plugins", "-p", "selected_plugins", multiple=True, required=True)
@click.option("--cli-plugin", "cli_plugin", required=False)
@click.option(
"--output-dir",
"-o",
default=".",
help="Output directory",
type=click.Path(path_type=Path, exists=False, dir_okay=True, file_okay=False),
)
@click.option("--schema", type=str, required=True)
@click.argument("query", type=click.Path(path_type=Path, exists=True))
@click.option(
"--app-dir",
default=".",
type=str,
show_default=True,
help=(
"Look for the module in the specified directory, by adding this to the "
"PYTHONPATH. Defaults to the current working directory. "
"Works the same as `--app-dir` in uvicorn."
),
)
def codegen(
schema: str,
query: Path,
app_dir: str,
output_dir: Path,
selected_plugins: List[str],
cli_plugin: Optional[str] = None,
) -> None:
schema_symbol = load_schema(schema, app_dir)
console_plugin = _load_plugin(cli_plugin) if cli_plugin else ConsolePlugin
plugins = _load_plugins(selected_plugins)
plugins.append(console_plugin(query, output_dir, plugins))
code_generator = QueryCodegen(schema_symbol, plugins=plugins)
code_generator.run(query.read_text())
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/cli/commands/codegen.py | codegen.py |
import click
from strawberry.cli.utils import load_schema
from strawberry.printer import print_schema
@click.command(short_help="Exports the schema")
@click.argument("schema", type=str)
@click.option(
"--app-dir",
default=".",
type=str,
show_default=True,
help=(
"Look for the module in the specified directory, by adding this to the "
"PYTHONPATH. Defaults to the current working directory. "
"Works the same as `--app-dir` in uvicorn."
),
)
def export_schema(schema: str, app_dir: str) -> None:
schema_symbol = load_schema(schema, app_dir)
print(print_schema(schema_symbol)) # noqa: T201
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/cli/commands/export_schema.py | export_schema.py |
import os
import sys
import click
from strawberry.cli.constants import (
DEBUG_SERVER_LOG_OPERATIONS,
DEBUG_SERVER_SCHEMA_ENV_VAR_KEY,
)
from strawberry.cli.utils import load_schema
@click.command("server", short_help="Starts debug server")
@click.argument("schema", type=str)
@click.option("-h", "--host", default="0.0.0.0", type=str)
@click.option("-p", "--port", default=8000, type=int)
@click.option(
"--log-level",
default="error",
type=click.Choice(["debug", "info", "warning", "error"], case_sensitive=False),
help="passed to uvicorn to determine the log level",
)
@click.option(
"--app-dir",
default=".",
type=str,
show_default=True,
help=(
"Look for the module in the specified directory, by adding this to the "
"PYTHONPATH. Defaults to the current working directory. "
"Works the same as `--app-dir` in uvicorn."
),
)
@click.option(
"--log-operations",
default=True,
type=bool,
show_default=True,
help="Log GraphQL operations",
)
def server(schema, host, port, log_level, app_dir, log_operations) -> None:
sys.path.insert(0, app_dir)
try:
import starlette # noqa: F401
import uvicorn
except ImportError:
message = (
"The debug server requires additional packages, install them by running:\n"
"pip install 'strawberry-graphql[debug-server]'"
)
raise click.ClickException(message)
load_schema(schema, app_dir=app_dir)
os.environ[DEBUG_SERVER_SCHEMA_ENV_VAR_KEY] = schema
os.environ[DEBUG_SERVER_LOG_OPERATIONS] = str(log_operations)
app = "strawberry.cli.debug_server:app"
# Windows doesn't support UTF-8 by default
endl = " 🍓\n" if sys.platform != "win32" else "\n"
print(f"Running strawberry on http://{host}:{port}/graphql", end=endl) # noqa: T201
uvicorn.run(
app,
host=host,
port=port,
log_level=log_level,
reload=True,
reload_dirs=[app_dir],
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/cli/commands/server.py | server.py |
from __future__ import annotations
import json
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Coroutine, Dict, List, Mapping, Optional, Union
from typing_extensions import Literal, TypedDict
if TYPE_CHECKING:
from graphql import GraphQLFormattedError
@dataclass
class Response:
errors: Optional[List[GraphQLFormattedError]]
data: Optional[Dict[str, object]]
extensions: Optional[Dict[str, object]]
class Body(TypedDict, total=False):
query: str
variables: Optional[Dict[str, object]]
class BaseGraphQLTestClient(ABC):
def __init__(self, client, url: str = "/graphql/"):
self._client = client
self.url = url
def query(
self,
query: str,
variables: Optional[Dict[str, Mapping]] = None,
headers: Optional[Dict[str, object]] = None,
asserts_errors: Optional[bool] = True,
files: Optional[Dict[str, object]] = None,
) -> Union[Coroutine[Any, Any, Response], Response]:
body = self._build_body(query, variables, files)
resp = self.request(body, headers, files)
data = self._decode(resp, type="multipart" if files else "json")
response = Response(
errors=data.get("errors"),
data=data.get("data"),
extensions=data.get("extensions"),
)
if asserts_errors:
assert response.errors is None
return response
@abstractmethod
def request(
self,
body: Dict[str, object],
headers: Optional[Dict[str, object]] = None,
files: Optional[Dict[str, object]] = None,
) -> Any:
raise NotImplementedError
def _build_body(
self,
query: str,
variables: Optional[Dict[str, Mapping]] = None,
files: Optional[Dict[str, object]] = None,
) -> Dict[str, object]:
body: Dict[str, object] = {"query": query}
if variables:
body["variables"] = variables
if files:
assert variables is not None
assert files is not None
file_map = BaseGraphQLTestClient._build_multipart_file_map(variables, files)
body = {
"operations": json.dumps(body),
"map": json.dumps(file_map),
**files,
}
return body
@staticmethod
def _build_multipart_file_map(
variables: Dict[str, Mapping], files: Dict[str, object]
) -> Dict[str, List[str]]:
"""Creates the file mapping between the variables and the files objects passed
as key arguments
Example usages:
>>> _build_multipart_file_map(
>>> variables={"textFile": None}, files={"textFile": f}
>>> )
... {"textFile": ["variables.textFile"]}
If the variable is a list we have to enumerate files in the mapping
>>> _build_multipart_file_map(
>>> variables={"files": [None, None]},
>>> files={"file1": file1, "file2": file2},
>>> )
... {"file1": ["variables.files.0"], "file2": ["variables.files.1"]}
If `variables` contains another keyword (a folder) we must include that keyword
in the mapping
>>> _build_multipart_file_map(
>>> variables={"folder": {"files": [None, None]}},
>>> files={"file1": file1, "file2": file2},
>>> )
... {
... "file1": ["variables.files.folder.files.0"],
... "file2": ["variables.files.folder.files.1"]
... }
If `variables` includes both a list of files and other single values, we must
map them accordingly
>>> _build_multipart_file_map(
>>> variables={"files": [None, None], "textFile": None},
>>> files={"file1": file1, "file2": file2, "textFile": file3},
>>> )
... {
... "file1": ["variables.files.0"],
... "file2": ["variables.files.1"],
... "textFile": ["variables.textFile"],
... }
"""
map: Dict[str, List[str]] = {}
for key, values in variables.items():
reference = key
variable_values = values
# In case of folders the variables will look like
# `{"folder": {"files": ...]}}`
if isinstance(values, dict):
folder_key = list(values.keys())[0]
reference += f".{folder_key}"
# the list of file is inside the folder keyword
variable_values = variable_values[folder_key]
# If the variable is an array of files we must number the keys
if isinstance(variable_values, list):
# copying `files` as when we map a file we must discard from the dict
_kwargs = files.copy()
for index, _ in enumerate(variable_values):
k = list(_kwargs.keys())[0]
_kwargs.pop(k)
map.setdefault(k, [])
map[k].append(f"variables.{reference}.{index}")
else:
map[key] = [f"variables.{reference}"]
# Variables can be mixed files and other data, we don't want to map non-files
# vars so we need to remove them, we can't remove them before
# because they can be part of a list of files or folder
map_without_vars = {k: v for k, v in map.items() if k in files}
return map_without_vars
def _decode(self, response: Any, type: Literal["multipart", "json"]):
if type == "multipart":
return json.loads(response.content.decode())
return response.json()
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/test/client.py | client.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.