code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
from .client import BaseGraphQLTestClient, Body, Response
__all__ = ["Body", "Response", "BaseGraphQLTestClient"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/test/__init__.py | __init__.py |
from __future__ import annotations
import json
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Optional, Union
from starlette.websockets import WebSocket
from strawberry.asgi.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 starlette.requests import Request
from starlette.responses import Response
from starlette.types import Receive, Scope, Send
from strawberry.http import GraphQLHTTPResponse
from strawberry.schema import BaseSchema
from strawberry.types import ExecutionResult
class GraphQL:
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 = False,
keep_alive_interval: float = 1,
debug: bool = False,
subscription_protocols=(GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL),
connection_init_wait_timeout: timedelta = timedelta(minutes=1),
) -> None:
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.protocols = subscription_protocols
self.connection_init_wait_timeout = connection_init_wait_timeout
async def __call__(self, scope: Scope, receive: Receive, send: Send):
if scope["type"] == "http":
await self.http_handler_class(
schema=self.schema,
graphiql=self.graphiql,
allow_queries_via_get=self.allow_queries_via_get,
debug=self.debug,
get_context=self.get_context,
get_root_value=self.get_root_value,
process_result=self.process_result,
encode_json=self.encode_json,
).handle(scope=scope, receive=receive, send=send)
elif scope["type"] == "websocket":
ws = WebSocket(scope=scope, receive=receive, send=send)
preferred_protocol = self.pick_preferred_protocol(ws)
if preferred_protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
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,
get_root_value=self.get_root_value,
ws=ws,
).handle()
elif preferred_protocol == GRAPHQL_WS_PROTOCOL:
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,
ws=ws,
).handle()
else:
# Subprotocol not acceptable
await ws.close(code=4406)
else: # pragma: no cover
raise ValueError("Unknown scope type: {!r}".format(scope["type"]))
def pick_preferred_protocol(self, ws: WebSocket) -> Optional[str]:
protocols = ws["subprotocols"]
intersection = set(protocols) & set(self.protocols)
sorted_intersection = sorted(intersection, key=protocols.index)
return next(iter(sorted_intersection), None)
async def get_root_value(self, request: Union[Request, WebSocket]) -> Optional[Any]:
return None
async def get_context(
self,
request: Union[Request, WebSocket],
response: Optional[Response] = None,
) -> Optional[Any]:
return {"request": request, "response": response}
async def process_result(
self, request: 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/asgi/__init__.py | __init__.py |
from __future__ import annotations
from contextlib import suppress
from typing import TYPE_CHECKING, Any, Optional
from starlette.websockets import WebSocketDisconnect, WebSocketState
from strawberry.subscriptions import GRAPHQL_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_ws.handlers import BaseGraphQLWSHandler
if TYPE_CHECKING:
from starlette.websockets import WebSocket
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: WebSocket,
):
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)
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)
try:
while self._ws.application_state != WebSocketState.DISCONNECTED:
try:
message = await self._ws.receive_json()
except KeyError:
# Ignore non-text messages
continue
else:
await self.handle_message(message)
except WebSocketDisconnect: # pragma: no cover
pass
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)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/asgi/handlers/graphql_ws_handler.py | graphql_ws_handler.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from starlette.websockets import WebSocketDisconnect, WebSocketState
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 starlette.websockets import WebSocket
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: WebSocket,
):
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)
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, reason: str) -> None:
await self._ws.close(code=code, reason=reason)
async def handle_request(self) -> None:
await self._ws.accept(subprotocol=GRAPHQL_TRANSPORT_WS_PROTOCOL)
try:
while self._ws.application_state != WebSocketState.DISCONNECTED:
try:
message = await self._ws.receive_json()
except KeyError:
error_message = "WebSocket message type must be text"
await self.handle_invalid_message(error_message)
else:
await self.handle_message(message)
except WebSocketDisconnect: # pragma: no cover
pass
finally:
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/asgi/handlers/graphql_transport_ws_handler.py | graphql_transport_ws_handler.py |
from strawberry.asgi.handlers.graphql_transport_ws_handler import (
GraphQLTransportWSHandler,
)
from strawberry.asgi.handlers.graphql_ws_handler import GraphQLWSHandler
from strawberry.asgi.handlers.http_handler import HTTPHandler
__all__ = ["GraphQLTransportWSHandler", "GraphQLWSHandler", "HTTPHandler"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/asgi/handlers/__init__.py | __init__.py |
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Optional
from starlette import status
from starlette.requests import Request
from starlette.responses import HTMLResponse, PlainTextResponse, Response
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.debug import pretty_print_graphql_operation
from strawberry.utils.graphiql import get_graphiql_html
if TYPE_CHECKING:
from starlette.types import Receive, Scope, Send
from strawberry.schema import BaseSchema
from strawberry.types.execution import ExecutionResult
class HTTPHandler:
def __init__(
self,
schema: BaseSchema,
graphiql: bool,
allow_queries_via_get: bool,
debug: bool,
get_context,
get_root_value,
process_result,
encode_json,
):
self.schema = schema
self.graphiql = graphiql
self.allow_queries_via_get = allow_queries_via_get
self.debug = debug
self.get_context = get_context
self.get_root_value = get_root_value
self.process_result = process_result
self.encode_json = encode_json
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope=scope, receive=receive)
root_value = await self.get_root_value(request)
sub_response = Response()
sub_response.status_code = None # type: ignore
del sub_response.headers["content-length"]
context = await self.get_context(request=request, response=sub_response)
response = await self.get_http_response(
request=request,
execute=self.execute,
process_result=self.process_result,
root_value=root_value,
context=context,
)
response.headers.raw.extend(sub_response.headers.raw)
if sub_response.background:
response.background = sub_response.background
if sub_response.status_code:
response.status_code = sub_response.status_code
await response(scope, receive, send)
async def get_http_response(
self,
request: Request,
execute: Callable,
process_result: Callable,
root_value: Optional[Any],
context: Optional[Any],
) -> Response:
method = request.method
if method == "GET":
if request.query_params:
try:
data = parse_query_params(request.query_params._dict)
except json.JSONDecodeError:
return PlainTextResponse(
"Unable to parse request body as JSON",
status_code=status.HTTP_400_BAD_REQUEST,
)
elif self.should_render_graphiql(request):
return self.get_graphiql_response()
else:
return HTMLResponse(status_code=status.HTTP_404_NOT_FOUND)
elif method == "POST":
content_type = request.headers.get("Content-Type", "")
if "application/json" in content_type:
try:
data = await request.json()
except json.JSONDecodeError:
return PlainTextResponse(
"Unable to parse request body as JSON",
status_code=status.HTTP_400_BAD_REQUEST,
)
elif content_type.startswith("multipart/form-data"):
multipart_data = await request.form()
try:
operations_text = multipart_data.get("operations", "{}")
operations = json.loads(operations_text) # type: ignore
files_map = json.loads(multipart_data.get("map", "{}")) # type: ignore # noqa: E501
except json.JSONDecodeError:
return PlainTextResponse(
"Unable to parse request body as JSON",
status_code=status.HTTP_400_BAD_REQUEST,
)
try:
data = replace_placeholders_with_files(
operations, files_map, multipart_data
)
except KeyError:
return PlainTextResponse(
"File(s) missing in form data",
status_code=status.HTTP_400_BAD_REQUEST,
)
else:
return PlainTextResponse(
"Unsupported Media Type",
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
)
else:
return PlainTextResponse(
"Method Not Allowed",
status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
)
try:
request_data = parse_request_data(data)
except json.JSONDecodeError:
return PlainTextResponse(
"Unable to parse request body as JSON",
status_code=status.HTTP_400_BAD_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 execute(
request_data.query,
variables=request_data.variables,
context=context,
operation_name=request_data.operation_name,
root_value=root_value,
allowed_operation_types=allowed_operation_types,
)
except InvalidOperationTypeError as e:
return PlainTextResponse(
e.as_http_error_reason(method),
status_code=status.HTTP_400_BAD_REQUEST,
)
except MissingQueryError:
return PlainTextResponse(
"No GraphQL query found in the request",
status_code=status.HTTP_400_BAD_REQUEST,
)
response_data = await process_result(request=request, result=result)
return Response(
self.encode_json(response_data),
status_code=status.HTTP_200_OK,
media_type="application/json",
)
def should_render_graphiql(self, request: Request) -> bool:
if not self.graphiql:
return False
return any(
supported_header in request.headers.get("accept", "")
for supported_header in ("text/html", "*/*")
)
def get_graphiql_response(self) -> HTMLResponse:
html = get_graphiql_html()
return HTMLResponse(html)
async def execute(
self,
query: str,
variables: Optional[Dict[str, Any]] = None,
context: Any = None,
operation_name: Optional[str] = None,
root_value: Any = None,
allowed_operation_types: Optional[Iterable[OperationType]] = None,
) -> ExecutionResult:
if self.debug:
pretty_print_graphql_operation(operation_name, query, variables)
return await self.schema.execute(
query,
root_value=root_value,
variable_values=variables,
operation_name=operation_name,
context_value=context,
allowed_operation_types=allowed_operation_types,
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/asgi/handlers/http_handler.py | http_handler.py |
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional
from strawberry.test import BaseGraphQLTestClient
if TYPE_CHECKING:
from typing_extensions import Literal
class GraphQLTestClient(BaseGraphQLTestClient):
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 = GraphQLTestClient._build_multipart_file_map(variables, files)
body = {
"operations": json.dumps(body),
"map": json.dumps(file_map),
}
return body
def request(
self,
body: Dict[str, object],
headers: Optional[Dict[str, object]] = None,
files: Optional[Dict[str, object]] = None,
) -> Any:
return self._client.post(
self.url,
json=body if not files else None,
data=body if files else None,
files=files,
headers=headers,
)
def _decode(self, response, type: Literal["multipart", "json"]):
return response.json()
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/asgi/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/asgi/test/__init__.py | __init__.py |
from __future__ import annotations
import dataclasses
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Mapping,
Optional,
Sequence,
Type,
TypeVar,
Union,
)
from typing_extensions import Self
from strawberry.type import StrawberryType, StrawberryTypeVar
from strawberry.utils.inspect import get_specialized_type_var_map
from strawberry.utils.typing import is_generic as is_type_generic
if TYPE_CHECKING:
from graphql import GraphQLResolveInfo
from strawberry.field import StrawberryField
@dataclasses.dataclass(eq=False)
class TypeDefinition(StrawberryType):
name: str
is_input: bool
is_interface: bool
origin: Type[Any]
description: Optional[str]
interfaces: List[TypeDefinition]
extend: bool
directives: Optional[Sequence[object]]
is_type_of: Optional[Callable[[Any, GraphQLResolveInfo], bool]]
_fields: List[StrawberryField]
concrete_of: Optional[TypeDefinition] = None
"""Concrete implementations of Generic TypeDefinitions fill this in"""
type_var_map: Mapping[TypeVar, Union[StrawberryType, type]] = dataclasses.field(
default_factory=dict
)
def __post_init__(self):
# resolve `Self` annotation with the origin type
for index, field in enumerate(self.fields):
if isinstance(field.type, StrawberryType) and field.type.has_generic(Self): # type: ignore # noqa: E501
self.fields[index] = field.copy_with({Self: self.origin}) # type: ignore # noqa: E501
# TODO: remove wrapped cls when we "merge" this with `StrawberryObject`
def resolve_generic(self, wrapped_cls: type) -> type:
from strawberry.annotation import StrawberryAnnotation
passed_types = wrapped_cls.__args__ # type: ignore
params = wrapped_cls.__origin__.__parameters__ # type: ignore
# Make sure all passed_types are turned into StrawberryTypes
resolved_types = []
for passed_type in passed_types:
resolved_type = StrawberryAnnotation(passed_type).resolve()
resolved_types.append(resolved_type)
type_var_map = dict(zip(params, resolved_types))
return self.copy_with(type_var_map)
# TODO: Return a StrawberryObject
def copy_with(
self, type_var_map: Mapping[TypeVar, Union[StrawberryType, type]]
) -> type:
# TODO: Logic unnecessary with StrawberryObject
fields = [field.copy_with(type_var_map) for field in self.fields]
new_type_definition = TypeDefinition(
name=self.name,
is_input=self.is_input,
origin=self.origin,
is_interface=self.is_interface,
directives=self.directives,
interfaces=self.interfaces,
description=self.description,
extend=self.extend,
is_type_of=self.is_type_of,
_fields=fields,
concrete_of=self,
type_var_map=type_var_map,
)
new_type = type(
new_type_definition.name,
(self.origin,),
{"_type_definition": new_type_definition},
)
new_type_definition.origin = new_type
return new_type
def get_field(self, python_name: str) -> Optional[StrawberryField]:
return next(
(field for field in self.fields if field.python_name == python_name), None
)
@property
def fields(self) -> List[StrawberryField]:
# TODO: rename _fields to fields and remove this property
return self._fields
@property
def is_generic(self) -> bool:
return is_type_generic(self.origin)
@property
def is_specialized_generic(self) -> bool:
if not self.is_generic:
return False
type_var_map = get_specialized_type_var_map(self.origin, include_type_vars=True)
return type_var_map is None or not any(
isinstance(arg, TypeVar) for arg in type_var_map.values()
)
@property
def type_params(self) -> List[TypeVar]:
type_params: List[TypeVar] = []
for field in self.fields:
type_params.extend(field.type_params)
return type_params
def is_implemented_by(self, root: Union[type, dict]) -> bool:
# TODO: Accept StrawberryObject instead
# TODO: Support dicts
if isinstance(root, dict):
raise NotImplementedError
type_definition = root._type_definition # type: ignore
if type_definition is self:
# No generics involved. Exact type match
return True
if type_definition is not self.concrete_of:
# Either completely different type, or concrete type of a different generic
return False
# Check the mapping of all fields' TypeVars
for generic_field in type_definition.fields:
generic_field_type = generic_field.type
if not isinstance(generic_field_type, StrawberryTypeVar):
continue
# For each TypeVar found, get the expected type from the copy's type map
expected_concrete_type = self.type_var_map.get(generic_field_type.type_var)
if expected_concrete_type is None:
# TODO: Should this return False?
continue
# Check if the expected type matches the type found on the type_map
real_concrete_type = type(getattr(root, generic_field.name))
# TODO: uniform type var map, at the moment we map object types
# to their class (not to TypeDefinition) while we map enum to
# the EnumDefinition class. This is why we do this check here:
if hasattr(real_concrete_type, "_enum_definition"):
real_concrete_type = real_concrete_type._enum_definition
if real_concrete_type is not expected_concrete_type:
return False
# All field mappings succeeded. This is a match
return True
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/types/types.py | types.py |
from __future__ import annotations
import dataclasses
import warnings
from typing import TYPE_CHECKING, Any, Dict, Generic, List, Optional, TypeVar, Union
from strawberry.utils.cached_property import cached_property
from .nodes import convert_selections
if TYPE_CHECKING:
from graphql import GraphQLResolveInfo, OperationDefinitionNode
from graphql.language import FieldNode
from graphql.pyutils.path import Path
from strawberry.field import StrawberryField
from strawberry.schema import Schema
from strawberry.type import StrawberryType
from .nodes import Selection
ContextType = TypeVar("ContextType")
RootValueType = TypeVar("RootValueType")
@dataclasses.dataclass
class Info(Generic[ContextType, RootValueType]):
_raw_info: GraphQLResolveInfo
_field: StrawberryField
@property
def field_name(self) -> str:
return self._raw_info.field_name
@property
def schema(self) -> Schema:
return self._raw_info.schema._strawberry_schema # type: ignore
@property
def field_nodes(self) -> List[FieldNode]: # deprecated
warnings.warn(
"`info.field_nodes` is deprecated, use `selected_fields` instead",
DeprecationWarning,
stacklevel=2,
)
return self._raw_info.field_nodes
@cached_property
def selected_fields(self) -> List[Selection]:
info = self._raw_info
return convert_selections(info, info.field_nodes)
@property
def context(self) -> ContextType:
return self._raw_info.context
@property
def root_value(self) -> RootValueType:
return self._raw_info.root_value
@property
def variable_values(self) -> Dict[str, Any]:
return self._raw_info.variable_values
# TODO: merge type with StrawberryType when StrawberryObject is implemented
@property
def return_type(self) -> Optional[Union[type, StrawberryType]]:
return self._field.type
@property
def python_name(self) -> str:
return self._field.python_name
# TODO: create an abstraction on these fields
@property
def operation(self) -> OperationDefinitionNode:
return self._raw_info.operation
@property
def path(self) -> Path:
return self._raw_info.path
# TODO: parent_type as strawberry types
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/types/info.py | info.py |
from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type
from graphql import specified_rules
from strawberry.utils.operation import get_first_operation, get_operation_type
if TYPE_CHECKING:
from graphql import ASTValidationRule
from graphql import ExecutionResult as GraphQLExecutionResult
from graphql.error.graphql_error import GraphQLError
from graphql.language import DocumentNode, OperationDefinitionNode
from strawberry.schema import Schema
from .graphql import OperationType
@dataclasses.dataclass
class ExecutionContext:
query: Optional[str]
schema: Schema
context: Any = None
variables: Optional[Dict[str, Any]] = None
root_value: Optional[Any] = None
validation_rules: Tuple[Type[ASTValidationRule], ...] = dataclasses.field(
default_factory=lambda: tuple(specified_rules)
)
# The operation name that is provided by the request
provided_operation_name: dataclasses.InitVar[Optional[str]] = None
# Values that get populated during the GraphQL execution so that they can be
# accessed by extensions
graphql_document: Optional[DocumentNode] = None
errors: Optional[List[GraphQLError]] = None
result: Optional[GraphQLExecutionResult] = None
def __post_init__(self, provided_operation_name: str):
self._provided_operation_name = provided_operation_name
@property
def operation_name(self) -> Optional[str]:
if self._provided_operation_name:
return self._provided_operation_name
definition = self._get_first_operation()
if not definition:
return None
if not definition.name:
return None
return definition.name.value
@property
def operation_type(self) -> OperationType:
graphql_document = self.graphql_document
if not graphql_document:
raise RuntimeError("No GraphQL document available")
return get_operation_type(graphql_document, self.operation_name)
def _get_first_operation(self) -> Optional[OperationDefinitionNode]:
graphql_document = self.graphql_document
if not graphql_document:
return None
return get_first_operation(graphql_document)
@dataclasses.dataclass
class ExecutionResult:
data: Optional[Dict[str, Any]]
errors: Optional[List[GraphQLError]]
extensions: Optional[Dict[str, Any]] = None
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/types/execution.py | execution.py |
from __future__ import annotations
import dataclasses
import sys
from typing import TYPE_CHECKING, Dict, List, Type, TypeVar
from strawberry.annotation import StrawberryAnnotation
from strawberry.exceptions import (
FieldWithResolverAndDefaultFactoryError,
FieldWithResolverAndDefaultValueError,
PrivateStrawberryFieldError,
)
from strawberry.private import is_private
from strawberry.unset import UNSET
from strawberry.utils.inspect import get_specialized_type_var_map
if TYPE_CHECKING:
from strawberry.field import StrawberryField
def _get_fields(cls: Type) -> List[StrawberryField]:
"""Get all the strawberry fields off a strawberry.type cls
This function returns a list of StrawberryFields (one for each field item), while
also paying attention the name and typing of the field.
StrawberryFields can be defined on a strawberry.type class as either a dataclass-
style field or using strawberry.field as a decorator.
>>> import strawberry
>>> @strawberry.type
... class Query:
... type_1a: int = 5
... type_1b: int = strawberry.field(...)
... type_1c: int = strawberry.field(resolver=...)
...
... @strawberry.field
... def type_2(self) -> int:
... ...
Type #1:
A pure dataclass-style field. Will not have a StrawberryField; one will need to
be created in this function. Type annotation is required.
Type #2:
A field defined using @strawberry.field as a decorator around the resolver. The
resolver must be type-annotated.
The StrawberryField.python_name value will be assigned to the field's name on the
class if one is not set by either using an explicit strawberry.field(name=...) or by
passing a named function (i.e. not an anonymous lambda) to strawberry.field
(typically as a decorator).
"""
# Deferred import to avoid import cycles
from strawberry.field import StrawberryField
fields: Dict[str, StrawberryField] = {}
# before trying to find any fields, let's first add the fields defined in
# parent classes, we do this by checking if parents have a type definition
for base in cls.__bases__:
if hasattr(base, "_type_definition"):
base_fields = {
field.python_name: field
# TODO: we need to rename _fields to something else
for field in base._type_definition._fields
}
# Add base's fields to cls' fields
fields = {**fields, **base_fields}
# Find the class the each field was originally defined on so we can use
# that scope later when resolving the type, as it may have different names
# available to it.
origins: Dict[str, type] = {field_name: cls for field_name in cls.__annotations__}
for base in cls.__mro__:
if hasattr(base, "_type_definition"):
for field in base._type_definition._fields:
if field.python_name in base.__annotations__:
origins.setdefault(field.name, base)
# then we can proceed with finding the fields for the current class
for field in dataclasses.fields(cls):
if isinstance(field, StrawberryField):
# Check that the field type is not Private
if is_private(field.type):
raise PrivateStrawberryFieldError(field.python_name, cls)
# Check that default is not set if a resolver is defined
if (
field.default is not dataclasses.MISSING
and field.default is not UNSET
and field.base_resolver is not None
):
raise FieldWithResolverAndDefaultValueError(
field.python_name, cls.__name__
)
# Check that default_factory is not set if a resolver is defined
# Note: using getattr because of this issue:
# https://github.com/python/mypy/issues/6910
default_factory = getattr(field, "default_factory", None)
if (
default_factory is not dataclasses.MISSING
and default_factory is not UNSET
and field.base_resolver is not None
):
raise FieldWithResolverAndDefaultFactoryError(
field.python_name, cls.__name__
)
# we make sure that the origin is either the field's resolver when
# called as:
#
# >>> @strawberry.field
# ... def x(self): ...
#
# or the class where this field was defined, so we always have
# the correct origin for determining field types when resolving
# the types.
field.origin = field.origin or cls
# Set the correct namespace for annotations if a namespace isn't
# already set
# Note: We do this here rather in the `Strawberry.type` setter
# function because at that point we don't have a link to the object
# type that the field as attached to.
if isinstance(field.type_annotation, StrawberryAnnotation):
type_annotation = field.type_annotation
if type_annotation.namespace is None:
type_annotation.set_namespace_from_field(field)
# Create a StrawberryField for fields that didn't use strawberry.field
else:
# Only ignore Private fields that weren't defined using StrawberryFields
if is_private(field.type):
continue
field_type = field.type
origin = origins.get(field.name, cls)
module = sys.modules[origin.__module__]
if isinstance(field_type, TypeVar):
specialized_type_var_map = get_specialized_type_var_map(cls)
# If field_type is specialized and a TypeVar, replace it with its
# mapped type
if specialized_type_var_map and field_type in specialized_type_var_map:
field_type = specialized_type_var_map[field_type]
else:
specialized_type_var_map = get_specialized_type_var_map(field_type)
# If field_type is specialized, copy its type_var_map to the definition
if specialized_type_var_map:
field_type = field_type._type_definition.copy_with(
specialized_type_var_map
)
# Create a StrawberryField, for fields of Types #1 and #2a
field = StrawberryField( # noqa: PLW2901
python_name=field.name,
graphql_name=None,
type_annotation=StrawberryAnnotation(
annotation=field_type,
namespace=module.__dict__,
),
origin=origin,
default=getattr(cls, field.name, dataclasses.MISSING),
)
field_name = field.python_name
assert_message = "Field must have a name by the time the schema is generated"
assert field_name is not None, assert_message
# TODO: Raise exception if field_name already in fields
fields[field_name] = field
return list(fields.values())
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/types/type_resolver.py | type_resolver.py |
"""
Abstraction layer for graphql-core field nodes.
Call `convert_sections` on a list of GraphQL `FieldNode`s,
such as in `info.field_nodes`.
If a node has only one useful value, it's value is inlined.
If a list of nodes have unique names, it's transformed into a mapping.
Note Python dicts maintain ordering (for all supported versions).
"""
from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING, Any, Collection, Dict, Iterable, List, Optional, Union
from graphql.language import FieldNode as GQLFieldNode
from graphql.language import FragmentSpreadNode as GQLFragmentSpreadNode
from graphql.language import InlineFragmentNode as GQLInlineFragmentNode
from graphql.language import ListValueNode as GQLListValueNode
from graphql.language import ObjectValueNode as GQLObjectValueNode
from graphql.language import VariableNode as GQLVariableNode
if TYPE_CHECKING:
from graphql import GraphQLResolveInfo
from graphql.language import ArgumentNode as GQLArgumentNode
from graphql.language import DirectiveNode as GQLDirectiveNode
from graphql.language import ValueNode as GQLValueNode
Arguments = Dict[str, Any]
Directives = Dict[str, Arguments]
Selection = Union["SelectedField", "FragmentSpread", "InlineFragment"]
def convert_value(info: GraphQLResolveInfo, node: GQLValueNode) -> Any:
"""Return useful value from any node."""
if isinstance(node, GQLVariableNode):
# Look up variable
name = node.name.value
return info.variable_values.get(name)
if isinstance(node, GQLListValueNode):
return [convert_value(info, value) for value in node.values]
if isinstance(node, GQLObjectValueNode):
return {
field.name.value: convert_value(info, field.value) for field in node.fields
}
return getattr(node, "value", None)
def convert_arguments(
info: GraphQLResolveInfo, nodes: Iterable[GQLArgumentNode]
) -> Arguments:
"""Return mapping of arguments."""
return {node.name.value: convert_value(info, node.value) for node in nodes}
def convert_directives(
info: GraphQLResolveInfo, nodes: Iterable[GQLDirectiveNode]
) -> Directives:
"""Return mapping of directives."""
return {node.name.value: convert_arguments(info, node.arguments) for node in nodes}
def convert_selections(
info: GraphQLResolveInfo, field_nodes: Collection[GQLFieldNode]
) -> List[Selection]:
"""Return typed `Selection` based on node type."""
selections: List[Selection] = []
for node in field_nodes:
if isinstance(node, GQLFieldNode):
selections.append(SelectedField.from_node(info, node))
elif isinstance(node, GQLInlineFragmentNode):
selections.append(InlineFragment.from_node(info, node))
elif isinstance(node, GQLFragmentSpreadNode):
selections.append(FragmentSpread.from_node(info, node))
else:
raise TypeError(f"Unknown node type: {node}")
return selections
@dataclasses.dataclass
class FragmentSpread:
"""Wrapper for a FragmentSpreadNode."""
name: str
type_condition: str
directives: Directives
selections: List[Selection]
@classmethod
def from_node(cls, info: GraphQLResolveInfo, node: GQLFragmentSpreadNode):
# Look up fragment
name = node.name.value
fragment = info.fragments[name]
return cls(
name=name,
directives=convert_directives(info, node.directives),
type_condition=fragment.type_condition.name.value,
selections=convert_selections(
info, getattr(fragment.selection_set, "selections", [])
),
)
@dataclasses.dataclass
class InlineFragment:
"""Wrapper for a InlineFragmentNode."""
type_condition: str
selections: List[Selection]
directives: Directives
@classmethod
def from_node(cls, info: GraphQLResolveInfo, node: GQLInlineFragmentNode):
return cls(
type_condition=node.type_condition.name.value,
selections=convert_selections(
info, getattr(node.selection_set, "selections", [])
),
directives=convert_directives(info, node.directives),
)
@dataclasses.dataclass
class SelectedField:
"""Wrapper for a FieldNode."""
name: str
directives: Directives
arguments: Arguments
selections: List[Selection]
alias: Optional[str] = None
@classmethod
def from_node(cls, info: GraphQLResolveInfo, node: GQLFieldNode):
return cls(
name=node.name.value,
directives=convert_directives(info, node.directives),
alias=getattr(node.alias, "value", None),
arguments=convert_arguments(info, node.arguments),
selections=convert_selections(
info, getattr(node.selection_set, "selections", [])
),
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/types/nodes.py | nodes.py |
from __future__ import annotations
import enum
from typing import Set
class OperationType(enum.Enum):
QUERY = "query"
MUTATION = "mutation"
SUBSCRIPTION = "subscription"
@staticmethod
def from_http(method: str) -> Set[OperationType]:
if method == "GET":
return {OperationType.QUERY}
if method == "POST":
return {
OperationType.QUERY,
OperationType.MUTATION,
OperationType.SUBSCRIPTION,
}
raise ValueError(f"Unsupported HTTP method: {method}") # pragma: no cover
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/types/graphql.py | graphql.py |
from .execution import ExecutionContext, ExecutionResult
from .info import Info
__all__ = ["ExecutionContext", "ExecutionResult", "Info"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/types/__init__.py | __init__.py |
from __future__ import annotations as _
import inspect
import sys
import warnings
from inspect import isasyncgenfunction, iscoroutinefunction
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
ForwardRef,
Generic,
List,
Mapping,
NamedTuple,
Optional,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from typing_extensions import Annotated, Protocol, get_args, get_origin
from strawberry.annotation import StrawberryAnnotation
from strawberry.arguments import StrawberryArgument
from strawberry.exceptions import MissingArgumentsAnnotationsError
from strawberry.type import StrawberryType
from strawberry.types.info import Info
from strawberry.utils.cached_property import cached_property
from strawberry.utils.typing import eval_type
if TYPE_CHECKING:
import builtins
class Parameter(inspect.Parameter):
def __hash__(self):
"""Override to exclude default value from hash.
This adds compatibility for using unhashable default values in resolvers such as
list and dict. The present use-case is limited to analyzing parameters from one
resolver. Therefore, the name, kind, and annotation combination are guaranteed
to be unique since two arguments cannot have the same name in a callable.
Furthermore, even though it is not currently a use-case to collect parameters
from different resolvers, the likelihood of collision from having the same hash
value but different defaults is mitigated by Python invoking the
:py:meth:`__eq__` method if two items have the same hash. See the verification
of this behavior in the `test_parameter_hash_collision` test.
"""
return hash((self.name, self.kind, self.annotation))
class Signature(inspect.Signature):
_parameter_cls = Parameter
class ReservedParameterSpecification(Protocol):
def find(
self, parameters: Tuple[inspect.Parameter, ...], resolver: StrawberryResolver
) -> Optional[inspect.Parameter]:
"""Finds the reserved parameter from ``parameters``."""
class ReservedName(NamedTuple):
name: str
def find(
self, parameters: Tuple[inspect.Parameter, ...], _: StrawberryResolver
) -> Optional[inspect.Parameter]:
return next((p for p in parameters if p.name == self.name), None)
class ReservedNameBoundParameter(NamedTuple):
name: str
def find(
self, parameters: Tuple[inspect.Parameter, ...], _: StrawberryResolver
) -> Optional[inspect.Parameter]:
if parameters: # Add compatibility for resolvers with no arguments
first_parameter = parameters[0]
return first_parameter if first_parameter.name == self.name else None
else:
return None
class ReservedType(NamedTuple):
"""Define a reserved type by name or by type.
To preserve backwards-comaptibility, if an annotation was defined but does not match
:attr:`type`, then the name is used as a fallback.
"""
name: str
type: Type
def find(
self, parameters: Tuple[inspect.Parameter, ...], resolver: StrawberryResolver
) -> Optional[inspect.Parameter]:
for parameter in parameters:
annotation = parameter.annotation
try:
resolved_annotation = eval_type(
ForwardRef(annotation)
if isinstance(annotation, str)
else annotation,
resolver._namespace,
None,
)
resolver._resolved_annotations[parameter] = resolved_annotation
except NameError:
# Type-annotation could not be resolved
resolved_annotation = annotation
if self.is_reserved_type(resolved_annotation):
return parameter
# Fallback to matching by name
reserved_name = ReservedName(name=self.name).find(parameters, resolver)
if reserved_name:
warning = DeprecationWarning(
f"Argument name-based matching of '{self.name}' is deprecated and will "
"be removed in v1.0. Ensure that reserved arguments are annotated "
"their respective types (i.e. use value: 'DirectiveValue[str]' instead "
"of 'value: str' and 'info: Info' instead of a plain 'info')."
)
warnings.warn(warning, stacklevel=3)
return reserved_name
else:
return None
def is_reserved_type(self, other: Type) -> bool:
origin = cast(type, get_origin(other)) or other
if origin is Annotated:
# Handle annotated arguments such as Private[str] and DirectiveValue[str]
return any(isinstance(argument, self.type) for argument in get_args(other))
else:
# Handle both concrete and generic types (i.e Info, and Info[Any, Any])
return (
issubclass(origin, self.type)
if isinstance(origin, type)
else origin is self.type
)
SELF_PARAMSPEC = ReservedNameBoundParameter("self")
CLS_PARAMSPEC = ReservedNameBoundParameter("cls")
ROOT_PARAMSPEC = ReservedName("root")
INFO_PARAMSPEC = ReservedType("info", Info)
T = TypeVar("T")
class StrawberryResolver(Generic[T]):
RESERVED_PARAMSPEC: Tuple[ReservedParameterSpecification, ...] = (
SELF_PARAMSPEC,
CLS_PARAMSPEC,
ROOT_PARAMSPEC,
INFO_PARAMSPEC,
)
def __init__(
self,
func: Union[Callable[..., T], staticmethod, classmethod],
*,
description: Optional[str] = None,
type_override: Optional[Union[StrawberryType, type]] = None,
):
self.wrapped_func = func
self._description = description
self._type_override = type_override
"""Specify the type manually instead of calculating from wrapped func
This is used when creating copies of types w/ generics
"""
self._resolved_annotations: Dict[inspect.Parameter, Any] = {}
"""Populated during reserved parameter determination.
Caching resolved annotations this way prevents evaling them repeatedly.
"""
# TODO: Use this when doing the actual resolving? How to deal with async resolvers?
def __call__(self, *args, **kwargs) -> T:
if not callable(self.wrapped_func):
raise UncallableResolverError(self)
return self.wrapped_func(*args, **kwargs)
@cached_property
def signature(self) -> inspect.Signature:
return Signature.from_callable(self._unbound_wrapped_func, follow_wrapped=True)
@cached_property
def reserved_parameters(
self,
) -> Dict[ReservedParameterSpecification, Optional[inspect.Parameter]]:
"""Mapping of reserved parameter specification to parameter."""
parameters = tuple(self.signature.parameters.values())
return {spec: spec.find(parameters, self) for spec in self.RESERVED_PARAMSPEC}
@cached_property
def arguments(self) -> List[StrawberryArgument]:
"""Resolver arguments exposed in the GraphQL Schema."""
parameters = self.signature.parameters.values()
reserved_parameters = set(self.reserved_parameters.values())
missing_annotations = []
arguments = []
user_parameters = (p for p in parameters if p not in reserved_parameters)
for param in user_parameters:
annotation = self._resolved_annotations.get(param, param.annotation)
if annotation is inspect.Signature.empty:
missing_annotations.append(param.name)
else:
argument = StrawberryArgument(
python_name=param.name,
graphql_name=None,
type_annotation=StrawberryAnnotation(
annotation=annotation, namespace=self._namespace
),
default=param.default,
)
arguments.append(argument)
if missing_annotations:
raise MissingArgumentsAnnotationsError(self, missing_annotations)
return arguments
@cached_property
def info_parameter(self) -> Optional[inspect.Parameter]:
return self.reserved_parameters.get(INFO_PARAMSPEC)
@cached_property
def root_parameter(self) -> Optional[inspect.Parameter]:
return self.reserved_parameters.get(ROOT_PARAMSPEC)
@cached_property
def self_parameter(self) -> Optional[inspect.Parameter]:
return self.reserved_parameters.get(SELF_PARAMSPEC)
@cached_property
def name(self) -> str:
# TODO: What to do if resolver is a lambda?
return self._unbound_wrapped_func.__name__
@cached_property
def annotations(self) -> Dict[str, object]:
"""Annotations for the resolver.
Does not include special args defined in `RESERVED_PARAMSPEC` (e.g. self, root,
info)
"""
reserved_parameters = self.reserved_parameters
reserved_names = {p.name for p in reserved_parameters.values() if p is not None}
annotations = self._unbound_wrapped_func.__annotations__
annotations = {
name: annotation
for name, annotation in annotations.items()
if name not in reserved_names
}
return annotations
@cached_property
def type_annotation(self) -> Optional[StrawberryAnnotation]:
return_annotation = self.signature.return_annotation
if return_annotation is inspect.Signature.empty:
return None
else:
type_annotation = StrawberryAnnotation(
annotation=return_annotation, namespace=self._namespace
)
return type_annotation
@property
def type(self) -> Optional[Union[StrawberryType, type]]:
if self._type_override:
return self._type_override
if self.type_annotation is None:
return None
return self.type_annotation.resolve()
@cached_property
def is_async(self) -> bool:
return iscoroutinefunction(self._unbound_wrapped_func) or isasyncgenfunction(
self._unbound_wrapped_func
)
def copy_with(
self, type_var_map: Mapping[TypeVar, Union[StrawberryType, builtins.type]]
) -> StrawberryResolver:
type_override = None
if self.type:
if isinstance(self.type, StrawberryType):
type_override = self.type.copy_with(type_var_map)
elif hasattr(self.type, "_type_definition"):
type_override = self.type._type_definition.copy_with(
type_var_map,
)
other = type(self)(
func=self.wrapped_func,
description=self._description,
type_override=type_override,
)
# Resolve generic arguments
for argument in other.arguments:
if isinstance(argument.type, StrawberryType) and argument.type.is_generic:
argument.type_annotation = StrawberryAnnotation(
annotation=argument.type.copy_with(type_var_map),
namespace=argument.type_annotation.namespace,
)
return other
@cached_property
def _namespace(self) -> Dict[str, Any]:
return sys.modules[self._unbound_wrapped_func.__module__].__dict__
@cached_property
def _unbound_wrapped_func(self) -> Callable[..., T]:
if isinstance(self.wrapped_func, (staticmethod, classmethod)):
return self.wrapped_func.__func__
return self.wrapped_func
class UncallableResolverError(Exception):
def __init__(self, resolver: StrawberryResolver):
message = (
f"Attempted to call resolver {resolver} with uncallable function "
f"{resolver.wrapped_func}"
)
super().__init__(message)
__all__ = ["StrawberryResolver"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/types/fields/resolver.py | resolver.py |
from typing import Any, Dict, Optional, Union
from starlette.background import BackgroundTasks
from starlette.requests import Request
from starlette.responses import Response
from starlette.websockets import WebSocket
CustomContext = Union["BaseContext", Dict[str, Any]]
MergedContext = Union[
"BaseContext", Dict[str, Union[Any, BackgroundTasks, Request, Response, WebSocket]]
]
class BaseContext:
connection_params: Optional[Any] = None
def __init__(self) -> None:
self.request: Optional[Union[Request, WebSocket]] = None
self.background_tasks: Optional[BackgroundTasks] = None
self.response: Optional[Response] = None
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/fastapi/context.py | context.py |
from strawberry.fastapi.context import BaseContext
from strawberry.fastapi.router import GraphQLRouter
__all__ = ["BaseContext", "GraphQLRouter"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/fastapi/__init__.py | __init__.py |
from __future__ import annotations
import json
from datetime import timedelta
from inspect import signature
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Iterable,
Optional,
Sequence,
Union,
cast,
)
from starlette import status
from starlette.background import BackgroundTasks # noqa: TCH002
from starlette.requests import HTTPConnection, Request
from starlette.responses import (
HTMLResponse,
PlainTextResponse,
Response,
)
from starlette.websockets import WebSocket
from fastapi import APIRouter, Depends
from strawberry.exceptions import InvalidCustomContext, MissingQueryError
from strawberry.fastapi.context import BaseContext, CustomContext
from strawberry.fastapi.handlers import GraphQLTransportWSHandler, GraphQLWSHandler
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.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL
from strawberry.types.graphql import OperationType
from strawberry.utils.debug import pretty_print_graphql_operation
from strawberry.utils.graphiql import get_graphiql_html
if TYPE_CHECKING:
from starlette.types import ASGIApp
from strawberry.fastapi.context import MergedContext
from strawberry.http import GraphQLHTTPResponse
from strawberry.schema import BaseSchema
from strawberry.types import ExecutionResult
class GraphQLRouter(APIRouter):
graphql_ws_handler_class = GraphQLWSHandler
graphql_transport_ws_handler_class = GraphQLTransportWSHandler
@staticmethod
async def __get_root_value():
return None
@staticmethod
def __get_context_getter(
custom_getter: Callable[
..., Union[Optional[CustomContext], Awaitable[Optional[CustomContext]]]
]
) -> Callable[..., Awaitable[CustomContext]]:
async def dependency(
custom_context: Optional[CustomContext],
background_tasks: BackgroundTasks,
connection: HTTPConnection,
response: Response = None, # type: ignore
) -> MergedContext:
request = cast(Union[Request, WebSocket], connection)
if isinstance(custom_context, BaseContext):
custom_context.request = request
custom_context.background_tasks = background_tasks
custom_context.response = response
return custom_context
default_context = {
"request": request,
"background_tasks": background_tasks,
"response": response,
}
if isinstance(custom_context, dict):
return {
**default_context,
**custom_context,
}
elif custom_context is None:
return default_context
else:
raise InvalidCustomContext()
# replace the signature parameters of dependency...
# ...with the old parameters minus the first argument as it will be replaced...
# ...with the value obtained by injecting custom_getter context as a dependency.
sig = signature(dependency)
sig = sig.replace(
parameters=[
*list(sig.parameters.values())[1:],
sig.parameters["custom_context"].replace(
default=Depends(custom_getter)
),
],
)
# there is an ongoing issue with types and .__signature__ applied to Callables:
# https://github.com/python/mypy/issues/5958, as of 14/12/21
# as such, the below line has its typing ignored by MyPy
dependency.__signature__ = sig # type: ignore
return dependency
def __init__(
self,
schema: BaseSchema,
path: str = "",
graphiql: bool = True,
allow_queries_via_get: bool = True,
keep_alive: bool = False,
keep_alive_interval: float = 1,
debug: bool = False,
root_value_getter=None,
context_getter=None,
subscription_protocols=(GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL),
connection_init_wait_timeout: timedelta = timedelta(minutes=1),
default: Optional[ASGIApp] = None,
on_startup: Optional[Sequence[Callable[[], Any]]] = None,
on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,
):
super().__init__(
default=default,
on_startup=on_startup,
on_shutdown=on_shutdown,
)
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.root_value_getter = root_value_getter or self.__get_root_value
self.context_getter = self.__get_context_getter(
context_getter or (lambda: None)
)
self.protocols = subscription_protocols
self.connection_init_wait_timeout = connection_init_wait_timeout
@self.get(
path,
responses={
200: {
"description": "The GraphiQL integrated development environment.",
},
404: {
"description": "Not found if GraphiQL is not enabled.",
},
},
)
async def handle_http_get(
request: Request,
response: Response,
context=Depends(self.context_getter),
root_value=Depends(self.root_value_getter),
) -> Response:
if request.query_params:
try:
query_data = parse_query_params(request.query_params._dict)
except json.JSONDecodeError:
return PlainTextResponse(
"Unable to parse request body as JSON",
status_code=status.HTTP_400_BAD_REQUEST,
)
return await self.execute_request(
request=request,
response=response,
data=query_data,
context=context,
root_value=root_value,
)
elif self.should_render_graphiql(request):
return self.get_graphiql_response()
return Response(status_code=status.HTTP_404_NOT_FOUND)
@self.post(path)
async def handle_http_post(
request: Request,
response: Response,
context=Depends(self.context_getter),
root_value=Depends(self.root_value_getter),
) -> Response:
actual_response: Response
content_type = request.headers.get("content-type", "")
if "application/json" in content_type:
try:
data = await request.json()
except json.JSONDecodeError:
actual_response = PlainTextResponse(
"Unable to parse request body as JSON",
status_code=status.HTTP_400_BAD_REQUEST,
)
return self._merge_responses(response, actual_response)
elif content_type.startswith("multipart/form-data"):
multipart_data = await request.form()
try:
operations_text = multipart_data.get("operations", "{}")
operations = json.loads(operations_text) # type: ignore
files_map = json.loads(multipart_data.get("map", "{}")) # type: ignore # noqa: E501
except json.JSONDecodeError:
actual_response = PlainTextResponse(
"Unable to parse request body as JSON",
status_code=status.HTTP_400_BAD_REQUEST,
)
return self._merge_responses(response, actual_response)
try:
data = replace_placeholders_with_files(
operations, files_map, multipart_data
)
except KeyError:
actual_response = PlainTextResponse(
"File(s) missing in form data",
status_code=status.HTTP_400_BAD_REQUEST,
)
return self._merge_responses(response, actual_response)
else:
actual_response = PlainTextResponse(
"Unsupported Media Type",
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
)
return self._merge_responses(response, actual_response)
return await self.execute_request(
request=request,
response=response,
data=data,
context=context,
root_value=root_value,
)
@self.websocket(path)
async def websocket_endpoint(
websocket: WebSocket,
context=Depends(self.context_getter),
root_value=Depends(self.root_value_getter),
):
async def _get_context():
return context
async def _get_root_value():
return root_value
preferred_protocol = self.pick_preferred_protocol(websocket)
if preferred_protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
await self.graphql_transport_ws_handler_class(
schema=self.schema,
debug=self.debug,
connection_init_wait_timeout=self.connection_init_wait_timeout,
get_context=_get_context,
get_root_value=_get_root_value,
ws=websocket,
).handle()
elif preferred_protocol == GRAPHQL_WS_PROTOCOL:
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=_get_context,
get_root_value=_get_root_value,
ws=websocket,
).handle()
else:
# Code 4406 is "Subprotocol not acceptable"
await websocket.close(code=4406)
def pick_preferred_protocol(self, ws: WebSocket) -> Optional[str]:
protocols = ws["subprotocols"]
intersection = set(protocols) & set(self.protocols)
return min(
intersection,
key=lambda i: protocols.index(i),
default=None,
)
def should_render_graphiql(self, request: Request) -> bool:
if not self.graphiql:
return False
return any(
supported_header in request.headers.get("accept", "")
for supported_header in ("text/html", "*/*")
)
def get_graphiql_response(self) -> HTMLResponse:
html = get_graphiql_html()
return HTMLResponse(html)
@staticmethod
def _merge_responses(response: Response, actual_response: Response) -> Response:
actual_response.headers.raw.extend(response.headers.raw)
if response.status_code:
actual_response.status_code = response.status_code
return actual_response
async def execute(
self,
query: Optional[str],
variables: Optional[Dict[str, Any]] = None,
context: Any = None,
operation_name: Optional[str] = None,
root_value: Any = None,
allowed_operation_types: Optional[Iterable[OperationType]] = None,
) -> ExecutionResult:
if self.debug and query:
pretty_print_graphql_operation(operation_name, query, variables)
return await self.schema.execute(
query,
root_value=root_value,
variable_values=variables,
operation_name=operation_name,
context_value=context,
allowed_operation_types=allowed_operation_types,
)
async def process_result(
self, request: Request, result: ExecutionResult
) -> GraphQLHTTPResponse:
return process_result(result)
async def execute_request(
self, request: Request, response: Response, data: dict, context, root_value
) -> Response:
request_data = parse_request_data(data)
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}
try:
result = await self.execute(
request_data.query,
variables=request_data.variables,
context=context,
operation_name=request_data.operation_name,
root_value=root_value,
allowed_operation_types=allowed_operation_types,
)
except InvalidOperationTypeError as e:
return PlainTextResponse(
e.as_http_error_reason(method),
status_code=status.HTTP_400_BAD_REQUEST,
)
except MissingQueryError:
missing_query_response = PlainTextResponse(
"No GraphQL query found in the request",
status_code=status.HTTP_400_BAD_REQUEST,
)
return self._merge_responses(response, missing_query_response)
response_data = await self.process_result(request, result)
actual_response = Response(
self.encode_json(response_data),
media_type="application/json",
status_code=status.HTTP_200_OK,
)
return self._merge_responses(response, actual_response)
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/fastapi/router.py | router.py |
from typing import Any
from strawberry.asgi.handlers import GraphQLWSHandler as BaseGraphQLWSHandler
from strawberry.fastapi.context import BaseContext
class GraphQLWSHandler(BaseGraphQLWSHandler):
async def get_context(self) -> Any:
context = await self._get_context()
if isinstance(context, BaseContext):
context.connection_params = self.connection_params
return context
async def get_root_value(self) -> Any:
return await self._get_root_value()
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/fastapi/handlers/graphql_ws_handler.py | graphql_ws_handler.py |
from typing import Any
from strawberry.asgi.handlers import (
GraphQLTransportWSHandler as BaseGraphQLTransportWSHandler,
)
from strawberry.fastapi.context import BaseContext
class GraphQLTransportWSHandler(BaseGraphQLTransportWSHandler):
async def get_context(self) -> Any:
context = await self._get_context()
if isinstance(context, BaseContext):
context.connection_params = self.connection_params
return context
async def get_root_value(self) -> Any:
return await self._get_root_value()
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/fastapi/handlers/graphql_transport_ws_handler.py | graphql_transport_ws_handler.py |
from strawberry.fastapi.handlers.graphql_transport_ws_handler import (
GraphQLTransportWSHandler,
)
from strawberry.fastapi.handlers.graphql_ws_handler import GraphQLWSHandler
__all__ = ["GraphQLTransportWSHandler", "GraphQLWSHandler"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/fastapi/handlers/__init__.py | __init__.py |
"""Starlite integration for strawberry-graphql."""
from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Dict, Optional, Union, cast
from starlite import (
BackgroundTasks,
Controller,
HttpMethod,
MediaType,
Provide,
Request,
Response,
WebSocket,
get,
post,
websocket,
)
from starlite.exceptions import (
NotFoundException,
SerializationException,
ValidationException,
)
from starlite.status_codes import (
HTTP_200_OK,
HTTP_400_BAD_REQUEST,
HTTP_415_UNSUPPORTED_MEDIA_TYPE,
)
from strawberry.exceptions import InvalidCustomContext, MissingQueryError
from strawberry.file_uploads.utils import replace_placeholders_with_files
from strawberry.http import (
GraphQLHTTPResponse,
parse_query_params,
parse_request_data,
process_result,
)
from strawberry.schema.exceptions import InvalidOperationTypeError
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_transport_ws import (
WS_4406_PROTOCOL_NOT_ACCEPTABLE,
)
from strawberry.types.graphql import OperationType
from strawberry.utils.debug import pretty_print_graphql_operation
from strawberry.utils.graphiql import get_graphiql_html
from .handlers.graphql_transport_ws_handler import (
GraphQLTransportWSHandler as BaseGraphQLTransportWSHandler,
)
from .handlers.graphql_ws_handler import GraphQLWSHandler as BaseGraphQLWSHandler
if TYPE_CHECKING:
from typing import FrozenSet, Iterable, List, Set, Tuple, Type
from starlite.types import AnyCallable, Dependencies
from strawberry.schema import BaseSchema
from strawberry.types import ExecutionResult
MergedContext = Union[
"BaseContext",
Union[
Dict[str, Any],
Dict[str, BackgroundTasks],
Dict[str, Request],
Dict[str, Response],
Dict[str, websocket],
],
]
CustomContext = Union["BaseContext", Dict[str, Any]]
async def _context_getter(
custom_context: Optional[CustomContext],
request: Request,
) -> MergedContext:
if isinstance(custom_context, BaseContext):
custom_context.request = request
return custom_context
default_context = {
"request": request,
}
if isinstance(custom_context, dict):
return {
**default_context,
**custom_context,
}
if custom_context is None:
return default_context
raise InvalidCustomContext()
@dataclass
class GraphQLResource:
data: Optional[Dict[str, object]]
errors: Optional[List[object]]
extensions: Optional[Dict[str, object]]
@dataclass
class EmptyResponseModel:
pass
class GraphQLWSHandler(BaseGraphQLWSHandler):
async def get_context(self) -> Any:
return await self._get_context()
async def get_root_value(self) -> Any:
return await self._get_root_value()
class GraphQLTransportWSHandler(BaseGraphQLTransportWSHandler):
async def get_context(self) -> Any:
return await self._get_context()
async def get_root_value(self) -> Any:
return await self._get_root_value()
class BaseContext:
def __init__(self):
self.request: Optional[Union[Request, WebSocket]] = None
self.response: Optional[Response] = None
def make_graphql_controller(
schema: BaseSchema,
path: str = "",
graphiql: bool = True,
allow_queries_via_get: bool = True,
keep_alive: bool = False,
keep_alive_interval: float = 1,
debug: bool = False,
# TODO: root typevar
root_value_getter: Optional[AnyCallable] = None,
# TODO: context typevar
context_getter: Optional[AnyCallable] = None,
subscription_protocols: Tuple[str, ...] = (
GRAPHQL_TRANSPORT_WS_PROTOCOL,
GRAPHQL_WS_PROTOCOL,
),
connection_init_wait_timeout: timedelta = timedelta(minutes=1),
) -> Type[Controller]:
routes_path = path
if context_getter is None:
def custom_context_getter_():
return None
else:
custom_context_getter_ = context_getter
if root_value_getter is None:
def root_value_getter_():
return None
else:
root_value_getter_ = root_value_getter
class GraphQLController(Controller):
path: str = routes_path
dependencies: Optional[Dependencies] = {
"custom_context": Provide(custom_context_getter_),
"context": Provide(_context_getter),
"root_value": Provide(root_value_getter_),
}
graphql_ws_handler_class: Type[GraphQLWSHandler] = GraphQLWSHandler
graphql_transport_ws_handler_class: Type[
GraphQLTransportWSHandler
] = GraphQLTransportWSHandler
_schema: BaseSchema = schema
_graphiql: bool = graphiql
_allow_queries_via_get: bool = allow_queries_via_get
_keep_alive: bool = keep_alive
_keep_alive_interval: float = keep_alive_interval
_debug: bool = debug
_protocols: Tuple[str, ...] = subscription_protocols
_connection_init_wait_timeout: timedelta = connection_init_wait_timeout
_graphiql_allowed_accept: FrozenSet[str] = frozenset({"text/html", "*/*"})
async def execute(
self,
query: Optional[str],
variables: Optional[Dict[str, Any]] = None,
context: Optional[CustomContext] = None,
operation_name: Optional[str] = None,
root_value: Optional[Any] = None,
allowed_operation_types: Optional[Iterable[OperationType]] = None,
):
if self._debug:
pretty_print_graphql_operation(operation_name, query or "", variables)
return await self._schema.execute(
query,
root_value=root_value,
variable_values=variables,
operation_name=operation_name,
context_value=context,
allowed_operation_types=allowed_operation_types,
)
async def process_result(self, result: ExecutionResult) -> GraphQLHTTPResponse:
return process_result(result)
async def execute_request(
self,
request: Request,
data: dict,
context: CustomContext,
root_value: Any,
) -> Response[Union[GraphQLResource, str]]:
request_data = parse_request_data(data or {})
allowed_operation_types = OperationType.from_http(request.method)
if not self._allow_queries_via_get and request.method == HttpMethod.GET:
allowed_operation_types = allowed_operation_types - {
OperationType.QUERY
}
response: Union[Response[dict], Response[BaseContext]] = Response(
{}, background=BackgroundTasks([])
)
if isinstance(context, BaseContext):
context.response = response
elif isinstance(context, dict):
context["response"] = response
try:
result = await self.execute(
request_data.query,
variables=request_data.variables,
context=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(request.method),
status_code=HTTP_400_BAD_REQUEST,
media_type=MediaType.TEXT,
)
except MissingQueryError:
return Response(
"No GraphQL query found in the request",
status_code=HTTP_400_BAD_REQUEST,
media_type=MediaType.TEXT,
)
response_data = await self.process_result(result)
actual_response: Response[GraphQLHTTPResponse] = Response(
response_data, status_code=HTTP_200_OK, media_type=MediaType.JSON
)
return self._merge_responses(response, actual_response)
def should_render_graphiql(self, request: Request) -> bool:
if not self._graphiql:
return False
accept: Set[str] = set()
for value in request.headers.getall("accept", ""):
accept.symmetric_difference_update(set(value.split(",")))
return bool(self._graphiql_allowed_accept & accept)
def get_graphiql_response(self) -> Response[str]:
html = get_graphiql_html()
return Response(html, media_type=MediaType.HTML)
@staticmethod
def _merge_responses(
response: Response, actual_response: Response
) -> Response[Union[GraphQLResource, str]]:
actual_response.headers.update(response.headers)
actual_response.cookies.extend(response.cookies)
actual_response.background = response.background
if response.status_code:
actual_response.status_code = response.status_code
return actual_response
@get(raises=[ValidationException, NotFoundException])
async def handle_http_get(
self,
request: Request,
context: CustomContext,
root_value: Any,
) -> Response[Union[GraphQLResource, str]]:
if request.query_params:
try:
query_data = parse_query_params(
cast("Dict[str, Any]", request.query_params)
)
except json.JSONDecodeError as error:
raise ValidationException(
detail="Unable to parse request body as JSON"
) from error
return await self.execute_request(
request=request,
data=query_data,
context=context,
root_value=root_value,
)
if self.should_render_graphiql(request):
return cast(
"Response[Union[GraphQLResource, str]]",
self.get_graphiql_response(),
)
raise NotFoundException()
@post(status_code=HTTP_200_OK)
async def handle_http_post(
self,
request: Request,
context: CustomContext,
root_value: Any,
) -> Response[Union[GraphQLResource, str]]:
actual_response: Response[Union[GraphQLResource, str]]
content_type, _ = request.content_type
if "application/json" in content_type:
try:
data = await request.json()
except SerializationException:
actual_response = Response(
"Unable to parse request body as JSON",
status_code=HTTP_400_BAD_REQUEST,
media_type=MediaType.TEXT,
)
return actual_response
elif content_type.startswith("multipart/form-data"):
multipart_data = await request.form()
operations: Dict[str, Any] = multipart_data.get("operations", "{}")
files_map: Dict[str, List[str]] = multipart_data.get("map", "{}")
try:
data = replace_placeholders_with_files(
operations, files_map, multipart_data
)
except KeyError:
return Response(
"File(s) missing in form data",
status_code=HTTP_400_BAD_REQUEST,
media_type=MediaType.TEXT,
)
except (TypeError, AttributeError):
return Response(
"Unable to parse the multipart body",
status_code=HTTP_400_BAD_REQUEST,
media_type=MediaType.TEXT,
)
else:
return Response(
"Unsupported Media Type",
status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE,
media_type=MediaType.TEXT,
)
return await self.execute_request(
request=request,
data=data,
context=context,
root_value=root_value,
)
@websocket()
async def websocket_endpoint(
self,
socket: WebSocket,
context: CustomContext,
root_value: Any,
) -> None:
async def _get_context():
return context
async def _get_root_value():
return root_value
preferred_protocol = self.pick_preferred_protocol(socket)
if preferred_protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
await self.graphql_transport_ws_handler_class(
schema=self._schema,
debug=self._debug,
connection_init_wait_timeout=self._connection_init_wait_timeout,
get_context=_get_context,
get_root_value=_get_root_value,
ws=socket,
).handle()
elif preferred_protocol == GRAPHQL_WS_PROTOCOL:
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=_get_context,
get_root_value=_get_root_value,
ws=socket,
).handle()
else:
await socket.close(code=WS_4406_PROTOCOL_NOT_ACCEPTABLE)
def pick_preferred_protocol(self, socket: WebSocket) -> Optional[str]:
protocols: List[str] = socket.scope["subprotocols"]
intersection = set(protocols) & set(self._protocols)
return (
min(
intersection,
key=lambda i: protocols.index(i) if i else "",
default=None,
)
or None
)
return GraphQLController
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/starlite/controller.py | controller.py |
from strawberry.starlite.controller import BaseContext, make_graphql_controller
__all__ = ["BaseContext", "make_graphql_controller"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/starlite/__init__.py | __init__.py |
from contextlib import suppress
from typing import Any, Optional
from starlite import WebSocket
from starlite.exceptions import SerializationException, WebSocketDisconnect
from strawberry.schema import BaseSchema
from strawberry.subscriptions import GRAPHQL_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_ws.handlers import BaseGraphQLWSHandler
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: WebSocket,
):
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()
async def get_root_value(self) -> Any:
return await self._get_root_value()
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(subprotocols=GRAPHQL_WS_PROTOCOL)
try:
while self._ws.connection_state != "disconnect":
try:
message = await self._ws.receive_json()
except (SerializationException, ValueError):
# Ignore non-text messages
continue
else:
await self.handle_message(message)
except WebSocketDisconnect: # pragma: no cover
pass
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)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/starlite/handlers/graphql_ws_handler.py | graphql_ws_handler.py |
from datetime import timedelta
from typing import Any
from starlite import WebSocket
from starlite.exceptions import SerializationException, WebSocketDisconnect
from strawberry.schema import BaseSchema
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL
from strawberry.subscriptions.protocols.graphql_transport_ws.handlers import (
BaseGraphQLTransportWSHandler,
)
class GraphQLTransportWSHandler(BaseGraphQLTransportWSHandler):
def __init__(
self,
schema: BaseSchema,
debug: bool,
connection_init_wait_timeout: timedelta,
get_context,
get_root_value,
ws: WebSocket,
):
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()
async def get_root_value(self) -> Any:
return await self._get_root_value()
async def send_json(self, data: dict) -> None:
await self._ws.send_json(data)
async def close(self, code: int, reason: str) -> None:
# Close messages are not part of the ASGI ref yet
await self._ws.close(code=code)
async def handle_request(self) -> None:
await self._ws.accept(subprotocols=GRAPHQL_TRANSPORT_WS_PROTOCOL)
try:
while self._ws.connection_state != "disconnect":
try:
message = await self._ws.receive_json()
except (SerializationException, ValueError):
error_message = "WebSocket message type must be text"
await self.handle_invalid_message(error_message)
else:
await self.handle_message(message)
except WebSocketDisconnect: # pragma: no cover
pass
finally:
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/starlite/handlers/graphql_transport_ws_handler.py | graphql_transport_ws_handler.py |
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
from .utils.source_finder import SourceFinder
if TYPE_CHECKING:
from strawberry.types.fields.resolver import StrawberryResolver
from .exception_source import ExceptionSource
class MissingArgumentsAnnotationsError(StrawberryException):
"""The field is missing the annotation for one or more arguments"""
def __init__(self, resolver: StrawberryResolver, arguments: List[str]):
self.missing_arguments = arguments
self.function = resolver.wrapped_func
self.argument_name = arguments[0]
self.message = (
f"Missing annotation for {self.missing_arguments_str} "
f'in field "{resolver.name}", did you forget to add it?'
)
self.rich_message = (
f"Missing annotation for {self.missing_arguments_str} in "
f"`[underline]{resolver.name}[/]`"
)
self.suggestion = (
"To fix this error you can add an annotation to the argument "
f"like so [italic]`{self.missing_arguments[0]}: str`"
)
first = "first " if len(self.missing_arguments) > 1 else ""
self.annotation_message = f"{first}argument missing annotation"
@property
def missing_arguments_str(self) -> str:
arguments = self.missing_arguments
if len(arguments) == 1:
return f'argument "{arguments[0]}"'
head = ", ".join(arguments[:-1])
return f'arguments "{head}" and "{arguments[-1]}"'
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if self.function is None:
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_argument_from_object(
self.function, self.argument_name # type: ignore
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/missing_arguments_annotations.py | missing_arguments_annotations.py |
import os
import sys
import threading
from types import TracebackType
from typing import Any, Callable, Optional, Tuple, Type, cast
from .exception import StrawberryException, UnableToFindExceptionSource
if sys.version_info >= (3, 8):
original_threading_exception_hook = threading.excepthook
else:
original_threading_exception_hook = None
ExceptionHandler = Callable[
[Type[BaseException], BaseException, Optional[TracebackType]], None
]
def should_use_rich_exceptions() -> bool:
errors_disabled = os.environ.get("STRAWBERRY_DISABLE_RICH_ERRORS", "")
return errors_disabled.lower() not in ["true", "1", "yes"]
def _get_handler(exception_type: Type[BaseException]) -> ExceptionHandler:
if issubclass(exception_type, StrawberryException):
try:
import rich
except ImportError:
pass
else:
def _handler(
exception_type: Type[BaseException],
exception: BaseException,
traceback: Optional[TracebackType],
):
try:
rich.print(exception)
# we check if weren't able to find the exception source
# in that case we fallback to the original exception handler
except UnableToFindExceptionSource:
sys.__excepthook__(exception_type, exception, traceback)
return _handler
return sys.__excepthook__
def strawberry_exception_handler(
exception_type: Type[BaseException],
exception: BaseException,
traceback: Optional[TracebackType],
) -> None:
_get_handler(exception_type)(exception_type, exception, traceback)
def strawberry_threading_exception_handler(
args: Tuple[
Type[BaseException],
Optional[BaseException],
Optional[TracebackType],
Optional[threading.Thread],
]
) -> None:
(exception_type, exception, traceback, _) = args
if exception is None:
if sys.version_info >= (3, 8):
# this cast is only here because some weird issue with mypy
# and the inability to disable this error based on the python version
# (we'd need to do type ignore for python 3.8 and above, but mypy
# doesn't seem to be able to handle that and will complain in python 3.7)
cast(Any, original_threading_exception_hook)(args)
return
_get_handler(exception_type)(exception_type, exception, traceback)
def reset_exception_handler() -> None:
sys.excepthook = sys.__excepthook__
if sys.version_info >= (3, 8):
threading.excepthook = original_threading_exception_hook
def setup_exception_handler() -> None:
if should_use_rich_exceptions():
sys.excepthook = strawberry_exception_handler
if sys.version_info >= (3, 8):
threading.excepthook = strawberry_threading_exception_handler
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/handler.py | handler.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Optional, Set, Tuple
from pygments.lexers import PythonLexer
from rich.segment import Segment
from rich.syntax import Syntax as RichSyntax
if TYPE_CHECKING:
from rich.console import Console, ConsoleOptions, RenderResult
class Syntax(RichSyntax):
def __init__(
self,
code: str,
line_range: Tuple[int, int],
highlight_lines: Optional[Set[int]] = None,
line_offset: int = 0,
line_annotations: Optional[Dict[int, str]] = None,
) -> None:
self.line_offset = line_offset
self.line_annotations = line_annotations or {}
super().__init__(
code=code,
lexer=PythonLexer(),
line_numbers=True,
word_wrap=False,
theme="ansi_light",
highlight_lines=highlight_lines,
line_range=line_range,
)
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
assert self.line_range
segments = self._get_syntax(console, options)
annotations = self.line_annotations.copy()
current_line = self.line_range[0] or 0
for segment in segments:
if segment.text == "\n":
# 3 = | + space + space
prefix = " " * (self._numbers_column_width + 3)
annotation = annotations.pop(current_line, None)
current_line += 1
if annotation:
yield ""
yield prefix + annotation
continue
yield segment
if segment.text.strip() == str(current_line):
yield Segment("| ")
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/syntax.py | syntax.py |
from __future__ import annotations
from inspect import getframeinfo, stack
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Type
from strawberry.exceptions.utils.source_finder import SourceFinder
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
if TYPE_CHECKING:
from strawberry.union import StrawberryUnion
from .exception_source import ExceptionSource
class InvalidUnionTypeError(StrawberryException):
"""The union is constructed with an invalid type"""
invalid_type: object
def __init__(self, union_name: str, invalid_type: object) -> None:
from strawberry.custom_scalar import ScalarWrapper
self.union_name = union_name
self.invalid_type = invalid_type
# assuming that the exception happens two stack frames above the current one.
# one is our code checking for invalid types, the other is the caller
self.frame = getframeinfo(stack()[2][0])
if isinstance(invalid_type, ScalarWrapper):
type_name = invalid_type.wrap.__name__
else:
try:
type_name = invalid_type.__name__ # type: ignore
except AttributeError:
# might be StrawberryList instance
type_name = invalid_type.__class__.__name__
self.message = f"Type `{type_name}` cannot be used in a GraphQL Union"
self.rich_message = (
f"Type `[underline]{type_name}[/]` cannot be used in a GraphQL Union"
)
self.suggestion = (
"To fix this error you should replace the type a strawberry.type"
)
self.annotation_message = "invalid type here"
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
path = Path(self.frame.filename)
source_finder = SourceFinder()
return source_finder.find_union_call(path, self.union_name, self.invalid_type)
class InvalidTypeForUnionMergeError(StrawberryException):
"""A specialized version of InvalidUnionTypeError for when trying
to merge unions using the pipe operator."""
invalid_type: Type
def __init__(self, union: StrawberryUnion, other: object) -> None:
self.union = union
self.other = other
# assuming that the exception happens two stack frames above the current one.
# one is our code checking for invalid types, the other is the caller
self.frame = getframeinfo(stack()[2][0])
other_name = getattr(other, "__name__", str(other))
self.message = f"`{other_name}` cannot be used when merging GraphQL Unions"
self.rich_message = (
f"`[underline]{other_name}[/]` cannot be used when merging GraphQL Unions"
)
self.suggestion = ""
self.annotation_message = "invalid type here"
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
source_finder = SourceFinder()
return source_finder.find_union_merge(self.union, self.other, frame=self.frame)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/invalid_union_type.py | invalid_union_type.py |
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, Optional
from strawberry.exceptions.utils.source_finder import SourceFinder
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
if TYPE_CHECKING:
from strawberry.custom_scalar import ScalarDefinition
from .exception_source import ExceptionSource
class ScalarAlreadyRegisteredError(StrawberryException):
def __init__(
self,
scalar_definition: ScalarDefinition,
other_scalar_definition: ScalarDefinition,
):
self.scalar_definition = scalar_definition
scalar_name = scalar_definition.name
self.message = f"Scalar `{scalar_name}` has already been registered"
self.rich_message = (
f"Scalar `[underline]{scalar_name}[/]` has already been registered"
)
self.annotation_message = "scalar defined here"
self.suggestion = (
"To fix this error you should either rename the scalar, "
"or reuse the existing one"
)
if other_scalar_definition._source_file:
other_path = Path(other_scalar_definition._source_file)
other_line = other_scalar_definition._source_line
self.suggestion += (
f", defined in [bold white][link=file://{other_path}]"
f"{other_path.relative_to(Path.cwd())}:{other_line}[/]"
)
super().__init__(self.message)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if not all(
(self.scalar_definition._source_file, self.scalar_definition._source_line)
):
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_scalar_call(self.scalar_definition)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/scalar_already_registered.py | scalar_already_registered.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from strawberry.exceptions.utils.source_finder import SourceFinder
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
if TYPE_CHECKING:
from strawberry.field import StrawberryField
from strawberry.object_type import TypeDefinition
from .exception_source import ExceptionSource
class UnresolvedFieldTypeError(StrawberryException):
def __init__(
self,
type_definition: TypeDefinition,
field: StrawberryField,
):
self.type_definition = type_definition
self.field = field
self.message = (
f"Could not resolve the type of '{self.field.name}'. "
"Check that the class is accessible from the global module scope."
)
self.rich_message = (
f"Could not resolve the type of [underline]'{self.field.name}'[/]. "
"Check that the class is accessible from the global module scope."
)
self.annotation_message = "field defined here"
self.suggestion = (
"To fix this error you should either import the type or use LazyType."
)
super().__init__(self.message)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
source_finder = SourceFinder()
# field could be attached to the class or not
source = source_finder.find_class_attribute_from_object(
self.type_definition.origin, self.field.name
)
if source is not None:
return source
if self.field.base_resolver:
return source_finder.find_function_from_object(
self.field.base_resolver.wrapped_func # type: ignore
)
return None # pragma: no cover
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/unresolved_field_type.py | unresolved_field_type.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
from .utils.source_finder import SourceFinder
if TYPE_CHECKING:
from enum import EnumMeta
from .exception_source import ExceptionSource
class NotAStrawberryEnumError(StrawberryException):
def __init__(self, enum: EnumMeta):
self.enum = enum
self.message = f'Enum "{enum.__name__}" is not a Strawberry enum.'
self.rich_message = (
f"Enum `[underline]{enum.__name__}[/]` is not a Strawberry enum."
)
self.suggestion = (
"To fix this error you can declare the enum using `@strawberry.enum`."
)
self.annotation_message = "enum defined here"
super().__init__(self.message)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if self.enum is None:
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_class_from_object(self.enum)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/not_a_strawberry_enum.py | not_a_strawberry_enum.py |
from dataclasses import dataclass
from pathlib import Path
@dataclass
class ExceptionSource:
path: Path
code: str
start_line: int
end_line: int
error_line: int
error_column: int
error_column_end: int
@property
def path_relative_to_cwd(self) -> Path:
if self.path.is_absolute():
return self.path.relative_to(Path.cwd())
return self.path
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/exception_source.py | exception_source.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, Type
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
from .utils.source_finder import SourceFinder
if TYPE_CHECKING:
from enum import Enum
from .exception_source import ExceptionSource
class ObjectIsNotAnEnumError(StrawberryException):
def __init__(self, cls: Type[Enum]):
self.cls = cls
self.message = (
"strawberry.enum can only be used with subclasses of Enum. "
f"Provided object {cls.__name__} is not an enum."
)
self.rich_message = (
"strawberry.enum can only be used with subclasses of Enum. "
f"Provided object `[underline]{cls.__name__}[/]` is not an enum."
)
self.annotation_message = "class defined here"
self.suggestion = (
"To fix this error, make sure your class is a subclass of enum.Enum."
)
super().__init__(self.message)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if self.cls is None:
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_class_from_object(self.cls)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/object_is_not_an_enum.py | object_is_not_an_enum.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
from .utils.source_finder import SourceFinder
if TYPE_CHECKING:
from strawberry.arguments import StrawberryArgument
from strawberry.types.fields.resolver import StrawberryResolver
from strawberry.types.types import TypeDefinition
from .exception_source import ExceptionSource
class InvalidArgumentTypeError(StrawberryException):
def __init__(
self,
resolver: StrawberryResolver,
argument: StrawberryArgument,
):
from strawberry.union import StrawberryUnion
self.function = resolver.wrapped_func
self.argument_name = argument.python_name
# argument_type: Literal["union", "interface"],
argument_type = "unknown"
if isinstance(argument.type, StrawberryUnion):
argument_type = "union"
else:
type_definition: Optional[TypeDefinition] = getattr(
argument.type, "_type_definition", None
)
if type_definition and type_definition.is_interface:
argument_type = "interface"
self.message = (
f'Argument "{self.argument_name}" on field '
f'"{resolver.name}" cannot be of type '
f'"{argument_type}"'
)
self.rich_message = self.message
if argument_type == "union":
self.suggestion = "Unions are not supported as arguments in GraphQL."
elif argument_type == "interface":
self.suggestion = "Interfaces are not supported as arguments in GraphQL."
else:
self.suggestion = f"{self.argument_name} is not supported as an argument."
self.annotation_message = (
f'Argument "{self.argument_name}" cannot be of type "{argument_type}"'
)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if self.function is None:
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_argument_from_object(
self.function, self.argument_name # type: ignore
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/invalid_argument_type.py | invalid_argument_type.py |
from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING, Optional
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
from .utils.source_finder import SourceFinder
if TYPE_CHECKING:
from .exception_source import ExceptionSource
class ObjectIsNotClassError(StrawberryException):
class MethodType(Enum):
INPUT = "input"
INTERFACE = "interface"
TYPE = "type"
def __init__(self, obj: object, method_type: MethodType):
self.obj = obj
self.function = obj
# TODO: assert obj is a function for now and skip the error if it is
# something else
obj_name = obj.__name__ # type: ignore
self.message = (
f"strawberry.{method_type.value} can only be used with class types. "
f"Provided object {obj_name} is not a type."
)
self.rich_message = (
f"strawberry.{method_type.value} can only be used with class types. "
f"Provided object `[underline]{obj_name}[/]` is not a type."
)
self.annotation_message = "function defined here"
self.suggestion = (
"To fix this error, make sure your use "
f"strawberry.{method_type.value} on a class."
)
super().__init__(self.message)
@classmethod
def input(cls, obj: object) -> ObjectIsNotClassError:
return cls(obj, cls.MethodType.INPUT)
@classmethod
def interface(cls, obj: object) -> ObjectIsNotClassError:
return cls(obj, cls.MethodType.INTERFACE)
@classmethod
def type(cls, obj: object) -> ObjectIsNotClassError:
return cls(obj, cls.MethodType.TYPE)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if self.function is None:
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_function_from_object(self.function) # type: ignore
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/object_is_not_a_class.py | object_is_not_a_class.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, Type
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
from .utils.source_finder import SourceFinder
if TYPE_CHECKING:
from .exception_source import ExceptionSource
class MissingFieldAnnotationError(StrawberryException):
def __init__(self, field_name: str, cls: Type):
self.cls = cls
self.field_name = field_name
self.message = (
f'Unable to determine the type of field "{field_name}". Either '
f"annotate it directly, or provide a typed resolver using "
f"@strawberry.field."
)
self.rich_message = (
f"Missing annotation for field `[underline]{self.field_name}[/]`"
)
self.suggestion = (
"To fix this error you can add an annotation, "
f"like so [italic]`{self.field_name}: str`"
)
self.annotation_message = "field missing annotation"
super().__init__(self.message)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if self.cls is None:
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_class_attribute_from_object(self.cls, self.field_name)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/missing_field_annotation.py | missing_field_annotation.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, Type
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
from .utils.source_finder import SourceFinder
if TYPE_CHECKING:
from .exception_source import ExceptionSource
class PrivateStrawberryFieldError(StrawberryException):
def __init__(self, field_name: str, cls: Type):
self.cls = cls
self.field_name = field_name
self.message = (
f"Field {field_name} on type {cls.__name__} cannot be both "
"private and a strawberry.field"
)
self.rich_message = (
f"`[underline]{self.field_name}[/]` field cannot be both "
"private and a strawberry.field "
)
self.annotation_message = "private field defined here"
self.suggestion = (
"To fix this error you should either make the field non private, "
"or remove the strawberry.field annotation."
)
super().__init__(self.message)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if self.cls is None:
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_class_attribute_from_object(self.cls, self.field_name)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/private_strawberry_field.py | private_strawberry_field.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
from .utils.source_finder import SourceFinder
if TYPE_CHECKING:
from strawberry.types.fields.resolver import StrawberryResolver
from .exception_source import ExceptionSource
class MissingReturnAnnotationError(StrawberryException):
"""The field is missing the return annotation"""
def __init__(self, field_name: str, resolver: StrawberryResolver):
self.function = resolver.wrapped_func
self.message = (
f'Return annotation missing for field "{field_name}", '
"did you forget to add it?"
)
self.rich_message = (
"[bold red]Missing annotation for field " f"`[underline]{resolver.name}[/]`"
)
self.suggestion = (
"To fix this error you can add an annotation, "
f"like so [italic]`def {resolver.name}(...) -> str:`"
)
self.annotation_message = "resolver missing annotation"
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if self.function is None:
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_function_from_object(self.function) # type: ignore
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/missing_return_annotation.py | missing_return_annotation.py |
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Optional
from strawberry.utils.cached_property import cached_property
from strawberry.utils.str_converters import to_kebab_case
if TYPE_CHECKING:
from rich.console import RenderableType
from .exception_source import ExceptionSource
class UnableToFindExceptionSource(Exception):
"""Internal exception raised when we can't find the exception source."""
class StrawberryException(Exception, ABC):
message: str
rich_message: str
suggestion: str
annotation_message: str
def __init__(self, message: str) -> None:
self.message = message
def __str__(self) -> str:
return self.message
@property
def documentation_path(self) -> str:
return to_kebab_case(self.__class__.__name__.replace("Error", ""))
@property
def documentation_url(self) -> str:
prefix = "https://errors.strawberry.rocks/"
return prefix + self.documentation_path
@cached_property
@abstractmethod
def exception_source(self) -> Optional[ExceptionSource]:
return None
@property
def __rich_header__(self) -> RenderableType:
return f"[bold red]error: {self.rich_message}"
@property
def __rich_body__(self) -> RenderableType:
assert self.exception_source
return self._get_error_inline(self.exception_source, self.annotation_message)
@property
def __rich_footer__(self) -> RenderableType:
return (
f"{self.suggestion}\n\n"
"Read more about this error on [bold underline]"
f"[link={self.documentation_url}]{self.documentation_url}"
).strip()
def __rich__(self) -> Optional[RenderableType]:
from rich.box import SIMPLE
from rich.console import Group
from rich.panel import Panel
if self.exception_source is None:
raise UnableToFindExceptionSource() from self
content = (
self.__rich_header__,
"",
self.__rich_body__,
"",
"",
self.__rich_footer__,
)
return Panel.fit(
Group(*content),
box=SIMPLE,
)
def _get_error_inline(
self, exception_source: ExceptionSource, message: str
) -> RenderableType:
source_file = exception_source.path
relative_path = exception_source.path_relative_to_cwd
error_line = exception_source.error_line
from rich.console import Group
from .syntax import Syntax
path = f"[white] @ [link=file://{source_file}]{relative_path}:{error_line}"
prefix = " " * exception_source.error_column
caret = "^" * (
exception_source.error_column_end - exception_source.error_column
)
message = f"{prefix}[bold]{caret}[/] {message}"
error_line = exception_source.error_line
line_annotations = {error_line: message}
return Group(
path,
"",
Syntax(
code=exception_source.code,
highlight_lines={error_line},
line_offset=exception_source.start_line - 1,
line_annotations=line_annotations,
line_range=(
exception_source.start_line - 1,
exception_source.end_line,
),
),
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/exception.py | exception.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, Type
from strawberry.utils.cached_property import cached_property
from .exception import StrawberryException
from .utils.source_finder import SourceFinder
if TYPE_CHECKING:
from rich.console import RenderableType
from .exception_source import ExceptionSource
class DuplicatedTypeName(StrawberryException):
"""Raised when the same type with different definition is reused inside a schema"""
def __init__(
self,
first_cls: Optional[Type],
second_cls: Optional[Type],
duplicated_type_name: str,
):
self.first_cls = first_cls
self.second_cls = second_cls
self.message = (
f"Type {duplicated_type_name} is defined multiple times in the schema"
)
self.rich_message = (
f"Type `[underline]{duplicated_type_name}[/]` "
"is defined multiple times in the schema"
)
self.suggestion = (
"To fix this error you should either rename the type or "
"remove the duplicated definition."
)
super().__init__(self.message)
@property
def __rich_body__(self) -> RenderableType:
if self.first_cls is None or self.second_cls is None:
return ""
from rich.console import Group
source_finder = SourceFinder()
first_class_source = self.exception_source
assert first_class_source
second_class_source = source_finder.find_class_from_object(self.second_cls)
if second_class_source is None:
return self._get_error_inline(
first_class_source, "first class defined here"
)
return Group(
self._get_error_inline(first_class_source, "first class defined here"),
"",
self._get_error_inline(second_class_source, "second class defined here"),
)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
if self.first_cls is None:
return None # pragma: no cover
source_finder = SourceFinder()
return source_finder.find_class_from_object(self.first_cls)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/duplicated_type_name.py | duplicated_type_name.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, Set, Union
from graphql import GraphQLError
from strawberry.utils.cached_property import cached_property
from .duplicated_type_name import DuplicatedTypeName
from .exception import StrawberryException, UnableToFindExceptionSource
from .handler import setup_exception_handler
from .invalid_argument_type import InvalidArgumentTypeError
from .invalid_union_type import InvalidTypeForUnionMergeError, InvalidUnionTypeError
from .missing_arguments_annotations import MissingArgumentsAnnotationsError
from .missing_field_annotation import MissingFieldAnnotationError
from .missing_return_annotation import MissingReturnAnnotationError
from .not_a_strawberry_enum import NotAStrawberryEnumError
from .object_is_not_a_class import ObjectIsNotClassError
from .object_is_not_an_enum import ObjectIsNotAnEnumError
from .private_strawberry_field import PrivateStrawberryFieldError
from .scalar_already_registered import ScalarAlreadyRegisteredError
from .unresolved_field_type import UnresolvedFieldTypeError
if TYPE_CHECKING:
from graphql import GraphQLInputObjectType, GraphQLObjectType
from strawberry.type import StrawberryType
from .exception_source import ExceptionSource
setup_exception_handler()
# TODO: this doesn't seem to be tested
class WrongReturnTypeForUnion(Exception):
"""The Union type cannot be resolved because it's not a field"""
def __init__(self, field_name: str, result_type: str):
message = (
f'The type "{result_type}" cannot be resolved for the field "{field_name}" '
", are you using a strawberry.field?"
)
super().__init__(message)
# TODO: this doesn't seem to be tested
class UnallowedReturnTypeForUnion(Exception):
"""The return type is not in the list of Union types"""
def __init__(
self, field_name: str, result_type: str, allowed_types: Set[GraphQLObjectType]
):
formatted_allowed_types = list(sorted(type_.name for type_ in allowed_types))
message = (
f'The type "{result_type}" of the field "{field_name}" '
f'is not in the list of the types of the union: "{formatted_allowed_types}"'
)
super().__init__(message)
# TODO: this doesn't seem to be tested
class InvalidTypeInputForUnion(Exception):
def __init__(self, annotation: GraphQLInputObjectType):
message = f"Union for {annotation} is not supported because it is an Input type"
super().__init__(message)
# TODO: this doesn't seem to be tested
class MissingTypesForGenericError(Exception):
"""Raised when a generic types was used without passing any type."""
def __init__(self, annotation: Union[StrawberryType, type]):
message = (
f'The type "{repr(annotation)}" is generic, but no type has been passed'
)
super().__init__(message)
class UnsupportedTypeError(StrawberryException):
def __init__(self, annotation: Union[StrawberryType, type]):
message = f"{annotation} conversion is not supported"
super().__init__(message)
@cached_property
def exception_source(self) -> Optional[ExceptionSource]:
return None
class MultipleStrawberryArgumentsError(Exception):
def __init__(self, argument_name: str):
message = (
f"Annotation for argument `{argument_name}` cannot have multiple "
f"`strawberry.argument`s"
)
super().__init__(message)
class WrongNumberOfResultsReturned(Exception):
def __init__(self, expected: int, received: int):
message = (
"Received wrong number of results in dataloader, "
f"expected: {expected}, received: {received}"
)
super().__init__(message)
class FieldWithResolverAndDefaultValueError(Exception):
def __init__(self, field_name: str, type_name: str):
message = (
f'Field "{field_name}" on type "{type_name}" cannot define a default '
"value and a resolver."
)
super().__init__(message)
class FieldWithResolverAndDefaultFactoryError(Exception):
def __init__(self, field_name: str, type_name: str):
message = (
f'Field "{field_name}" on type "{type_name}" cannot define a '
"default_factory and a resolver."
)
super().__init__(message)
class MissingQueryError(Exception):
def __init__(self):
message = 'Request data is missing a "query" value'
super().__init__(message)
class InvalidDefaultFactoryError(Exception):
def __init__(self):
message = "`default_factory` must be a callable that requires no arguments"
super().__init__(message)
class InvalidCustomContext(Exception):
"""Raised when a custom context object is of the wrong python type"""
def __init__(self):
message = (
"The custom context must be either a class "
"that inherits from BaseContext or a dictionary"
)
super().__init__(message)
class StrawberryGraphQLError(GraphQLError):
"""Use it when you want to override the graphql.GraphQLError in custom extensions"""
__all__ = [
"StrawberryException",
"UnableToFindExceptionSource",
"MissingArgumentsAnnotationsError",
"MissingReturnAnnotationError",
"WrongReturnTypeForUnion",
"UnallowedReturnTypeForUnion",
"ObjectIsNotAnEnumError",
"ObjectIsNotClassError",
"InvalidUnionTypeError",
"InvalidTypeForUnionMergeError",
"MissingTypesForGenericError",
"UnsupportedTypeError",
"UnresolvedFieldTypeError",
"PrivateStrawberryFieldError",
"MultipleStrawberryArgumentsError",
"NotAStrawberryEnumError",
"ScalarAlreadyRegisteredError",
"WrongNumberOfResultsReturned",
"FieldWithResolverAndDefaultValueError",
"FieldWithResolverAndDefaultFactoryError",
"MissingQueryError",
"InvalidArgumentTypeError",
"InvalidDefaultFactoryError",
"InvalidCustomContext",
"MissingFieldAnnotationError",
"DuplicatedTypeName",
"StrawberryGraphQLError",
]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/__init__.py | __init__.py |
from __future__ import annotations
import importlib
import importlib.util
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, Type, cast
from strawberry.utils.cached_property import cached_property
from ..exception_source import ExceptionSource
if TYPE_CHECKING:
from inspect import Traceback
from libcst import BinaryOperation, Call, CSTNode, FunctionDef
from strawberry.custom_scalar import ScalarDefinition
from strawberry.union import StrawberryUnion
@dataclass
class SourcePath:
path: Path
code: str
class LibCSTSourceFinder:
def __init__(self) -> None:
self.cst = importlib.import_module("libcst")
def find_source(self, module: str) -> Optional[SourcePath]:
# todo: support for pyodide
source_module = sys.modules.get(module)
path = None
if source_module is None:
spec = importlib.util.find_spec(module)
if spec is not None and spec.origin is not None:
path = Path(spec.origin)
elif source_module.__file__ is not None:
path = Path(source_module.__file__)
if path is None:
return None
if not path.exists() or path.suffix != ".py":
return None # pragma: no cover
source = path.read_text()
return SourcePath(path=path, code=source)
def _find(self, source: str, matcher: Any) -> Sequence[CSTNode]:
from libcst.metadata import (
MetadataWrapper,
ParentNodeProvider,
PositionProvider,
)
module = self.cst.parse_module(source)
self._metadata_wrapper = MetadataWrapper(module)
self._position_metadata = self._metadata_wrapper.resolve(PositionProvider)
self._parent_metadata = self._metadata_wrapper.resolve(ParentNodeProvider)
import libcst.matchers as m
return m.findall(self._metadata_wrapper, matcher)
def _find_definition_by_qualname(
self, qualname: str, nodes: Sequence[CSTNode]
) -> Optional[CSTNode]:
from libcst import ClassDef, FunctionDef
for definition in nodes:
parent: Optional[CSTNode] = definition
stack = []
while parent:
if isinstance(parent, ClassDef):
stack.append(parent.name.value)
if isinstance(parent, FunctionDef):
stack.extend(("<locals>", parent.name.value))
parent = self._parent_metadata.get(parent)
if stack[0] == "<locals>":
stack.pop(0)
found_class_name = ".".join(reversed(stack))
if found_class_name == qualname:
return definition
return None
def _find_function_definition(
self, source: SourcePath, function: Callable
) -> Optional[FunctionDef]:
import libcst.matchers as m
matcher = m.FunctionDef(name=m.Name(value=function.__name__))
function_defs = self._find(source.code, matcher)
return cast(
"FunctionDef",
self._find_definition_by_qualname(function.__qualname__, function_defs),
)
def _find_class_definition(
self, source: SourcePath, cls: Type
) -> Optional[CSTNode]:
import libcst.matchers as m
matcher = m.ClassDef(name=m.Name(value=cls.__name__))
class_defs = self._find(source.code, matcher)
return self._find_definition_by_qualname(cls.__qualname__, class_defs)
def find_class(self, cls: Type) -> Optional[ExceptionSource]:
source = self.find_source(cls.__module__)
if source is None:
return None # pragma: no cover
class_def = self._find_class_definition(source, cls)
if class_def is None:
return None # pragma: no cover
position = self._position_metadata[class_def]
column_start = position.start.column + len("class ")
return ExceptionSource(
path=source.path,
code=source.code,
start_line=position.start.line,
error_line=position.start.line,
end_line=position.end.line,
error_column=column_start,
error_column_end=column_start + len(cls.__name__),
)
def find_class_attribute(
self, cls: Type, attribute_name: str
) -> Optional[ExceptionSource]:
source = self.find_source(cls.__module__)
if source is None:
return None # pragma: no cover
class_def = self._find_class_definition(source, cls)
if class_def is None:
return None # pragma: no cover
import libcst.matchers as m
from libcst import AnnAssign
attribute_definitions = m.findall(
class_def,
m.AssignTarget(target=m.Name(value=attribute_name))
| m.AnnAssign(target=m.Name(value=attribute_name)),
)
if not attribute_definitions:
return None
attribute_definition = attribute_definitions[0]
if isinstance(attribute_definition, AnnAssign):
attribute_definition = attribute_definition.target
class_position = self._position_metadata[class_def]
attribute_position = self._position_metadata[attribute_definition]
return ExceptionSource(
path=source.path,
code=source.code,
start_line=class_position.start.line,
error_line=attribute_position.start.line,
end_line=class_position.end.line,
error_column=attribute_position.start.column,
error_column_end=attribute_position.end.column,
)
def find_function(self, function: Callable) -> Optional[ExceptionSource]:
source = self.find_source(function.__module__)
if source is None:
return None # pragma: no cover
function_def = self._find_function_definition(source, function)
if function_def is None:
return None # pragma: no cover
position = self._position_metadata[function_def]
prefix = f"def{function_def.whitespace_after_def.value}"
if function_def.asynchronous:
prefix = f"async{function_def.asynchronous.whitespace_after.value}{prefix}"
function_prefix = len(prefix)
error_column = position.start.column + function_prefix
error_column_end = error_column + len(function.__name__)
return ExceptionSource(
path=source.path,
code=source.code,
start_line=position.start.line,
error_line=position.start.line,
end_line=position.end.line,
error_column=error_column,
error_column_end=error_column_end,
)
def find_argument(
self, function: Callable, argument_name: str
) -> Optional[ExceptionSource]:
source = self.find_source(function.__module__)
if source is None:
return None # pragma: no cover
function_def = self._find_function_definition(source, function)
if function_def is None:
return None # pragma: no cover
import libcst.matchers as m
argument_defs = m.findall(
function_def,
m.Param(name=m.Name(value=argument_name)),
)
if not argument_defs:
return None # pragma: no cover
argument_def = argument_defs[0]
function_position = self._position_metadata[function_def]
position = self._position_metadata[argument_def]
return ExceptionSource(
path=source.path,
code=source.code,
start_line=function_position.start.line,
end_line=function_position.end.line,
error_line=position.start.line,
error_column=position.start.column,
error_column_end=position.end.column,
)
def find_union_call(
self, path: Path, union_name: str, invalid_type: object
) -> Optional[ExceptionSource]:
import libcst.matchers as m
source = path.read_text()
invalid_type_name = getattr(invalid_type, "__name__", None)
types_arg_matcher = (
[
m.Tuple(
elements=[
m.ZeroOrMore(),
m.Element(value=m.Name(value=invalid_type_name)),
m.ZeroOrMore(),
],
)
| m.List(
elements=[
m.ZeroOrMore(),
m.Element(value=m.Name(value=invalid_type_name)),
m.ZeroOrMore(),
],
)
]
if invalid_type_name is not None
else []
)
matcher = m.Call(
func=m.Attribute(
value=m.Name(value="strawberry"),
attr=m.Name(value="union"),
)
| m.Name(value="union"),
args=[
m.Arg(value=m.SimpleString(value=f"'{union_name}'"))
| m.Arg(value=m.SimpleString(value=f'"{union_name}"')),
m.Arg(*types_arg_matcher), # type: ignore
],
)
union_calls = self._find(source, matcher)
if not union_calls:
return None # pragma: no cover
union_call = cast("Call", union_calls[0])
if invalid_type_name:
invalid_type_nodes = m.findall(
union_call.args[1],
m.Element(value=m.Name(value=invalid_type_name)),
)
if not invalid_type_nodes:
return None # pragma: no cover
invalid_type_node = invalid_type_nodes[0]
else:
invalid_type_node = union_call
position = self._position_metadata[union_call]
invalid_type_node_position = self._position_metadata[invalid_type_node]
return ExceptionSource(
path=path,
code=source,
start_line=position.start.line,
error_line=invalid_type_node_position.start.line,
end_line=position.end.line,
error_column=invalid_type_node_position.start.column,
error_column_end=invalid_type_node_position.end.column,
)
def find_union_merge(
self, union: StrawberryUnion, other: object, frame: Traceback
) -> Optional[ExceptionSource]:
import libcst.matchers as m
path = Path(frame.filename)
source = path.read_text()
other_name = getattr(other, "__name__", None)
if other_name is None:
return None # pragma: no cover
matcher = m.BinaryOperation(operator=m.BitOr(), right=m.Name(value=other_name))
merge_calls = self._find(source, matcher)
if not merge_calls:
return None # pragma: no cover
merge_call_node = cast("BinaryOperation", merge_calls[0])
invalid_type_node = merge_call_node.right
position = self._position_metadata[merge_call_node]
invalid_type_node_position = self._position_metadata[invalid_type_node]
return ExceptionSource(
path=path,
code=source,
start_line=position.start.line,
error_line=invalid_type_node_position.start.line,
end_line=position.end.line,
error_column=invalid_type_node_position.start.column,
error_column_end=invalid_type_node_position.end.column,
)
def find_scalar_call(
self, scalar_definition: ScalarDefinition
) -> Optional[ExceptionSource]:
if scalar_definition._source_file is None:
return None # pragma: no cover
import libcst.matchers as m
path = Path(scalar_definition._source_file)
source = path.read_text()
matcher = m.Call(
func=m.Attribute(value=m.Name(value="strawberry"), attr=m.Name("scalar"))
| m.Name("scalar"),
args=[
m.ZeroOrMore(),
m.Arg(
keyword=m.Name(value="name"),
value=m.SimpleString(value=f"'{scalar_definition.name}'")
| m.SimpleString(value=f'"{scalar_definition.name}"'),
),
m.ZeroOrMore(),
],
)
scalar_calls = self._find(source, matcher)
if not scalar_calls:
return None # pragma: no cover
scalar_call_node = scalar_calls[0]
argument_node = m.findall(
scalar_call_node,
m.Arg(
keyword=m.Name(value="name"),
),
)
position = self._position_metadata[scalar_call_node]
argument_node_position = self._position_metadata[argument_node[0]]
return ExceptionSource(
path=path,
code=source,
start_line=position.start.line,
end_line=position.end.line,
error_line=argument_node_position.start.line,
error_column=argument_node_position.start.column,
error_column_end=argument_node_position.end.column,
)
class SourceFinder:
# TODO: this might need to become a getter
@cached_property
def cst(self) -> Optional[LibCSTSourceFinder]:
try:
return LibCSTSourceFinder()
except ImportError:
return None # pragma: no cover
def find_class_from_object(self, cls: Type) -> Optional[ExceptionSource]:
return self.cst.find_class(cls) if self.cst else None
def find_class_attribute_from_object(
self, cls: Type, attribute_name: str
) -> Optional[ExceptionSource]:
return self.cst.find_class_attribute(cls, attribute_name) if self.cst else None
def find_function_from_object(
self, function: Callable
) -> Optional[ExceptionSource]:
return self.cst.find_function(function) if self.cst else None
def find_argument_from_object(
self, function: Callable, argument_name: str
) -> Optional[ExceptionSource]:
return self.cst.find_argument(function, argument_name) if self.cst else None
def find_union_call(
self, path: Path, union_name: str, invalid_type: object
) -> Optional[ExceptionSource]:
return (
self.cst.find_union_call(path, union_name, invalid_type)
if self.cst
else None
)
def find_union_merge(
self, union: StrawberryUnion, other: object, frame: Traceback
) -> Optional[ExceptionSource]:
return self.cst.find_union_merge(union, other, frame) if self.cst else None
def find_scalar_call(
self, scalar_definition: ScalarDefinition
) -> Optional[ExceptionSource]:
return self.cst.find_scalar_call(scalar_definition) if self.cst else None
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/exceptions/utils/source_finder.py | source_finder.py |
from __future__ import annotations
import logging
import sys
from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING:
from typing_extensions import Final
from graphql.error import GraphQLError
from strawberry.types import ExecutionContext
class StrawberryLogger:
logger: Final[logging.Logger] = logging.getLogger("strawberry.execution")
@classmethod
def error(
cls,
error: GraphQLError,
execution_context: Optional[ExecutionContext] = None,
# https://www.python.org/dev/peps/pep-0484/#arbitrary-argument-lists-and-default-argument-values
**logger_kwargs: Any,
) -> None:
# "stack_info" is a boolean; check for None explicitly
if logger_kwargs.get("stack_info") is None:
logger_kwargs["stack_info"] = True
# stacklevel was added in version 3.8
# https://docs.python.org/3/library/logging.html#logging.Logger.debug
if sys.version_info >= (3, 8):
logger_kwargs["stacklevel"] = 3
cls.logger.error(error, exc_info=error.original_error, **logger_kwargs)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/logging.py | logging.py |
import datetime
import json
from json import JSONEncoder
from typing import Any, Dict, Optional
class StrawberryJSONEncoder(JSONEncoder):
def default(self, o: Any) -> Any:
return repr(o)
def pretty_print_graphql_operation(
operation_name: Optional[str], query: str, variables: Optional[Dict["str", Any]]
) -> None:
"""Pretty print a GraphQL operation using pygments.
Won't print introspection operation to prevent noise in the output."""
try:
from pygments import highlight, lexers
from pygments.formatters import Terminal256Formatter
except ImportError as e:
raise ImportError(
"pygments is not installed but is required for debug output, install it "
"directly or run `pip install strawberry-graphql[debug-server]`"
) from e
from .graphql_lexer import GraphQLLexer
if operation_name == "IntrospectionQuery":
return
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{now}]: {operation_name or 'No operation name'}") # noqa: T201
print(highlight(query, GraphQLLexer(), Terminal256Formatter())) # noqa: T201
if variables:
variables_json = json.dumps(variables, indent=4, cls=StrawberryJSONEncoder)
print( # noqa: T201
highlight(variables_json, lexers.JsonLexer(), Terminal256Formatter())
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/debug.py | debug.py |
import ast
import sys
import typing
from collections.abc import AsyncGenerator
from functools import lru_cache
from typing import ( # type: ignore
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
ForwardRef,
Generic,
Optional,
Tuple,
Type,
TypeVar,
Union,
_eval_type,
_GenericAlias,
_SpecialForm,
cast,
overload,
)
from typing_extensions import Annotated, get_args, get_origin
ast_unparse = getattr(ast, "unparse", None)
# ast.unparse is only available on python 3.9+. For older versions we will
# use `astunparse.unparse`.
# We are also using "not TYPE_CHECKING" here because mypy gives an erorr
# on tests because "astunparse" is missing stubs, but the mypy action says
# that the comment is unused.
if not TYPE_CHECKING and ast_unparse is None:
import astunparse
ast_unparse = astunparse.unparse
@lru_cache()
def get_generic_alias(type_: Type) -> Type:
"""Get the generic alias for a type.
Given a type, its generic alias from `typing` module will be returned
if it exists. For example:
>>> get_generic_alias(list)
typing.List
>>> get_generic_alias(dict)
typing.Dict
This is mostly useful for python versions prior to 3.9, to get a version
of a concrete type which supports `__class_getitem__`. In 3.9+ types like
`list`/`dict`/etc are subscriptable and can be used directly instead
of their generic alias version.
"""
if isinstance(type_, _SpecialForm):
return type_
for attr_name in dir(typing):
# ignore private attributes, they are not Generic aliases
if attr_name.startswith("_"): # pragma: no cover
continue
attr = getattr(typing, attr_name)
# _GenericAlias overrides all the methods that we can use to know if
# this is a subclass of it. But if it has an "_inst" attribute
# then it for sure is a _GenericAlias
if hasattr(attr, "_inst") and attr.__origin__ is type_:
return attr
raise AssertionError(f"No GenericAlias available for {type_}") # pragma: no cover
def is_list(annotation: object) -> bool:
"""Returns True if annotation is a List"""
annotation_origin = getattr(annotation, "__origin__", None)
return annotation_origin == list
def is_union(annotation: object) -> bool:
"""Returns True if annotation is a Union"""
# this check is needed because unions declared with the new syntax `A | B`
# don't have a `__origin__` property on them, but they are instances of
# `UnionType`, which is only available in Python 3.10+
if sys.version_info >= (3, 10):
from types import UnionType
if isinstance(annotation, UnionType):
return True
# unions declared as Union[A, B] fall through to this check, even on python 3.10+
annotation_origin = getattr(annotation, "__origin__", None)
return annotation_origin == Union
def is_optional(annotation: Type) -> bool:
"""Returns True if the annotation is Optional[SomeType]"""
# Optionals are represented as unions
if not is_union(annotation):
return False
types = annotation.__args__
# A Union to be optional needs to have at least one None type
return any(x == None.__class__ for x in types)
def get_optional_annotation(annotation: Type) -> Type:
types = annotation.__args__
non_none_types = tuple(x for x in types if x != None.__class__)
# if we have multiple non none types we want to return a copy of this
# type (normally a Union type).
if len(non_none_types) > 1:
return annotation.copy_with(non_none_types)
return non_none_types[0]
def get_list_annotation(annotation: Type) -> Type:
return annotation.__args__[0]
def is_concrete_generic(annotation: type) -> bool:
ignored_generics = (list, tuple, Union, ClassVar, AsyncGenerator)
return (
isinstance(annotation, _GenericAlias)
and annotation.__origin__ not in ignored_generics
)
def is_generic_subclass(annotation: type) -> bool:
return isinstance(annotation, type) and issubclass(
annotation, Generic # type:ignore
)
def is_generic(annotation: type) -> bool:
"""Returns True if the annotation is or extends a generic."""
return (
# TODO: These two lines appear to have the same effect. When will an
# annotation have parameters but not satisfy the first condition?
(is_generic_subclass(annotation) or is_concrete_generic(annotation))
and bool(get_parameters(annotation))
)
def is_type_var(annotation: Type) -> bool:
"""Returns True if the annotation is a TypeVar."""
return isinstance(annotation, TypeVar)
def get_parameters(annotation: Type) -> Union[Tuple[object], Tuple[()]]:
if (
isinstance(annotation, _GenericAlias)
or isinstance(annotation, type)
and issubclass(annotation, Generic) # type:ignore
and annotation is not Generic
):
return annotation.__parameters__
else:
return () # pragma: no cover
@overload
def _ast_replace_union_operation(expr: ast.expr) -> ast.expr:
...
@overload
def _ast_replace_union_operation(expr: ast.Expr) -> ast.Expr:
...
def _ast_replace_union_operation(
expr: Union[ast.Expr, ast.expr]
) -> Union[ast.Expr, ast.expr]:
if isinstance(expr, ast.Expr) and isinstance(
expr.value, (ast.BinOp, ast.Subscript)
):
expr = ast.Expr(_ast_replace_union_operation(expr.value))
elif isinstance(expr, ast.BinOp):
left = _ast_replace_union_operation(expr.left)
right = _ast_replace_union_operation(expr.right)
expr = ast.Subscript(
ast.Name(id="Union"),
ast.Tuple([left, right], ast.Load()),
ast.Load(),
)
elif isinstance(expr, ast.Tuple):
expr = ast.Tuple(
[_ast_replace_union_operation(elt) for elt in expr.elts],
ast.Load(),
)
elif isinstance(expr, ast.Subscript):
if hasattr(ast, "Index") and isinstance(expr.slice, ast.Index):
expr = ast.Subscript(
expr.value,
# The cast is required for mypy on python 3.7 and 3.8
ast.Index(_ast_replace_union_operation(cast(Any, expr.slice).value)),
ast.Load(),
)
elif isinstance(expr.slice, (ast.BinOp, ast.Tuple)):
expr = ast.Subscript(
expr.value,
_ast_replace_union_operation(expr.slice),
ast.Load(),
)
return expr
def eval_type(
type_: Any,
globalns: Optional[Dict] = None,
localns: Optional[Dict] = None,
) -> Type:
"""Evaluates a type, resolving forward references."""
from strawberry.auto import StrawberryAuto
from strawberry.lazy_type import StrawberryLazyReference
from strawberry.private import StrawberryPrivate
globalns = globalns or {}
# If this is not a string, maybe its args are (e.g. List["Foo"])
if isinstance(type_, ForwardRef):
# For Python 3.10+, we can use the built-in _eval_type function directly.
# It will handle "|" notations properly
if sys.version_info < (3, 10):
parsed = _ast_replace_union_operation(
cast(ast.Expr, ast.parse(type_.__forward_arg__).body[0])
)
# We replaced "a | b" with "Union[a, b], so make sure Union can be resolved
# at globalns because it may not be there
if "Union" not in globalns:
globalns["Union"] = Union
assert ast_unparse
type_ = ForwardRef(ast_unparse(parsed))
return _eval_type(type_, globalns, localns)
origin = get_origin(type_)
if origin is not None:
args = get_args(type_)
if origin is Annotated:
for arg in args[1:]:
if isinstance(arg, StrawberryPrivate):
return type_
if isinstance(arg, StrawberryLazyReference):
remaining_args = [
a
for a in args[1:]
if not isinstance(arg, StrawberryLazyReference)
]
args = (arg.resolve_forward_ref(args[0]), *remaining_args)
break
if isinstance(arg, StrawberryAuto):
remaining_args = [
a for a in args[1:] if not isinstance(arg, StrawberryAuto)
]
args = (arg, *remaining_args)
break
# If we have only a StrawberryLazyReference and no more annotations,
# we need to return the argument directly because Annotated
# will raise an error if trying to instantiate it with only
# one argument.
if len(args) == 1:
return args[0]
# python 3.10 will return UnionType for origin, and it cannot be
# subscripted like Union[Foo, Bar]
if sys.version_info >= (3, 10):
from types import UnionType
if origin is UnionType:
origin = Union
# Future annotations in older versions will eval generic aliases to their
# real types (i.e. List[foo] will have its origin set to list instead
# of List). If that type is not subscriptable, retrieve its generic
# alias version instead.
if sys.version_info < (3, 9) and not hasattr(origin, "__class_getitem__"):
origin = get_generic_alias(origin)
type_ = (
origin[tuple(eval_type(a, globalns, localns) for a in args)]
if args
else origin
)
return type_
_T = TypeVar("_T")
def __dataclass_transform__(
*,
eq_default: bool = True,
order_default: bool = False,
kw_only_default: bool = False,
field_descriptors: Tuple[Union[type, Callable[..., Any]], ...] = (()),
) -> Callable[[_T], _T]:
return lambda a: a
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/typing.py | typing.py |
import importlib
from typing import Optional
def import_module_symbol(
selector: str, default_symbol_name: Optional[str] = None
) -> object:
if ":" in selector:
module_name, symbol_name = selector.split(":", 1)
elif default_symbol_name:
module_name, symbol_name = selector, default_symbol_name
else:
raise ValueError("Selector does not include a symbol name")
module = importlib.import_module(module_name)
symbol = module
for attribute_name in symbol_name.split("."):
symbol = getattr(symbol, attribute_name)
return symbol
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/importer.py | importer.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, cast
from graphql.language import OperationDefinitionNode
from strawberry.types.graphql import OperationType
if TYPE_CHECKING:
from graphql.language import DocumentNode
def get_first_operation(
graphql_document: DocumentNode,
) -> Optional[OperationDefinitionNode]:
for definition in graphql_document.definitions:
if isinstance(definition, OperationDefinitionNode):
return definition
return None
def get_operation_type(
graphql_document: DocumentNode, operation_name: Optional[str] = None
) -> OperationType:
definition: Optional[OperationDefinitionNode] = None
if operation_name:
for d in graphql_document.definitions:
d = cast(OperationDefinitionNode, d) # noqa: PLW2901
if d.name and d.name.value == operation_name:
definition = d
break
else:
definition = get_first_operation(graphql_document)
if not definition:
raise RuntimeError("Can't get GraphQL operation type")
return OperationType(definition.operation.value)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/operation.py | operation.py |
import inspect
from typing import AsyncIterator, Awaitable, Iterator, TypeVar, Union, cast
T = TypeVar("T")
AwaitableOrValue = Union[Awaitable[T], T]
AsyncIteratorOrIterator = Union[AsyncIterator[T], Iterator[T]]
async def await_maybe(value: AwaitableOrValue[T]) -> T:
if inspect.isawaitable(value):
return await value
return cast(T, value)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/await_maybe.py | await_maybe.py |
from __future__ import annotations
import sys
from dataclasses import ( # type: ignore
_FIELD,
_FIELD_INITVAR,
_FIELDS,
_POST_INIT_NAME,
_set_new_attribute,
)
from typing import Any
from strawberry.ext.dataclasses.dataclasses import dataclass_init_fn
def add_custom_init_fn(cls: Any) -> None:
fields = [
f
for f in getattr(cls, _FIELDS).values()
if f._field_type in (_FIELD, _FIELD_INITVAR)
]
globals_ = sys.modules[cls.__module__].__dict__
_set_new_attribute(
cls,
"__init__",
dataclass_init_fn(
fields=fields,
frozen=False,
has_post_init=hasattr(cls, _POST_INIT_NAME),
self_name="__dataclass_self__" if "self" in fields else "self",
globals_=globals_,
),
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/dataclasses.py | dataclasses.py |
import json
import pathlib
def get_graphiql_html(
subscription_enabled: bool = True, replace_variables: bool = True
) -> str:
here = pathlib.Path(__file__).parents[1]
path = here / "static/graphiql.html"
template = path.read_text(encoding="utf-8")
if replace_variables:
template = template.replace(
"{{ SUBSCRIPTION_ENABLED }}", json.dumps(subscription_enabled)
)
return template
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/graphiql.py | graphiql.py |
import sys
from typing import TYPE_CHECKING
if sys.version_info < (3, 8):
from backports.cached_property import cached_property
else:
from functools import cached_property
if TYPE_CHECKING:
from threading import RLock
from typing import Any, Callable, Generic, Optional, Type, TypeVar, overload
_T = TypeVar("_T")
_S = TypeVar("_S")
class cached_property(Generic[_T]): # type: ignore[no-redef]
func: Callable[[Any], _T]
attrname: Optional[str]
lock: RLock
def __init__(self, func: Callable[[Any], _T]) -> None:
...
@overload # type: ignore[no-overload-impl]
def __get__(
self, instance: None, owner: Optional[Type[Any]] = ...
) -> cached_property[_T]:
...
@overload
def __get__(self, instance: _S, owner: Optional[Type[Any]] = ...) -> _T:
...
def __set_name__(self, owner: Type[Any], name: str) -> None:
...
__all__ = ["cached_property"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/cached_property.py | cached_property.py |
import inspect
from functools import lru_cache
from typing import Any, Callable, Dict, List, Optional, TypeVar, Union, overload
from typing_extensions import Literal, get_args
@lru_cache(maxsize=250)
def get_func_args(func: Callable[[Any], Any]) -> List[str]:
"""Returns a list of arguments for the function"""
sig = inspect.signature(func)
return [
arg_name
for arg_name, param in sig.parameters.items()
if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
]
@overload
def get_specialized_type_var_map(
cls: type,
*,
include_type_vars: Literal[True],
) -> Optional[Dict[TypeVar, Union[TypeVar, type]]]:
...
@overload
def get_specialized_type_var_map(
cls: type,
*,
include_type_vars: Literal[False] = ...,
) -> Optional[Dict[TypeVar, type]]:
...
@overload
def get_specialized_type_var_map(
cls: type,
*,
include_type_vars: bool,
) -> Optional[
Union[Optional[Dict[TypeVar, type]], Dict[TypeVar, Union[TypeVar, type]]]
]:
...
def get_specialized_type_var_map(cls: type, *, include_type_vars: bool = False):
"""Get a type var map for specialized types.
Consider the following:
>>> class Foo(Generic[T]):
... ...
...
>>> class Bar(Generic[K]):
... ...
...
>>> class IntBar(Bar[int]):
... ...
...
>>> class IntBarSubclass(IntBar):
... ...
...
>>> class IntBarFoo(IntBar, Foo[str]):
... ...
...
This would return:
>>> get_specialized_type_var_map(object)
None
>>> get_specialized_type_var_map(Foo)
{}
>>> get_specialized_type_var_map(Foo, include_type_vars=True)
{~T: ~T}
>>> get_specialized_type_var_map(Bar)
{~T: ~T}
>>> get_specialized_type_var_map(IntBar)
{~T: int}
>>> get_specialized_type_var_map(IntBarSubclass)
{~T: int}
>>> get_specialized_type_var_map(IntBarFoo)
{~T: int, ~K: str}
"""
orig_bases = getattr(cls, "__orig_bases__", None)
if orig_bases is None:
# Not a specialized type
return None
type_var_map = {}
for base in orig_bases:
# Recursively get type var map from base classes
base_type_var_map = get_specialized_type_var_map(base)
if base_type_var_map is not None:
type_var_map.update(base_type_var_map)
args = get_args(base)
origin = getattr(base, "__origin__", None)
params = origin and getattr(origin, "__parameters__", None)
if params is None:
params = getattr(base, "__parameters__", None)
if not params:
continue
type_var_map.update(
{
p: a
for p, a in zip(params, args)
if include_type_vars or not isinstance(a, TypeVar)
}
)
return type_var_map
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/inspect.py | inspect.py |
import re
# Adapted from this response in Stackoverflow
# http://stackoverflow.com/a/19053800/1072990
def to_camel_case(snake_str: str) -> str:
components = snake_str.split("_")
# We capitalize the first letter of each component except the first one
# with the 'capitalize' method and join them together.
return components[0] + "".join(x.capitalize() if x else "_" for x in components[1:])
TO_KEBAB_CASE_RE = re.compile("((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))")
def to_kebab_case(name: str) -> str:
return TO_KEBAB_CASE_RE.sub(r"-\1", name).lower()
def capitalize_first(name: str) -> str:
return name[0].upper() + name[1:]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/str_converters.py | str_converters.py |
from pygments import token
from pygments.lexer import RegexLexer
class GraphQLLexer(RegexLexer):
"""GraphQL Lexer for Pygments, used by the debug server."""
name = "GraphQL"
aliases = ["graphql", "gql"]
filenames = ["*.graphql", "*.gql"]
mimetypes = ["application/graphql"]
tokens = {
"root": [
(r"#.*", token.Comment.Singline),
(r"\.\.\.", token.Operator),
(r'"[\u0009\u000A\u000D\u0020-\uFFFF]*"', token.String.Double),
(
r"(-?0|-?[1-9][0-9]*)(\.[0-9]+[eE][+-]?[0-9]+|\.[0-9]+|[eE][+-]?[0-9]+)",
token.Number.Float,
),
(r"(-?0|-?[1-9][0-9]*)", token.Number.Integer),
(r"\$+[_A-Za-z][_0-9A-Za-z]*", token.Name.Variable),
(r"[_A-Za-z][_0-9A-Za-z]+\s?:", token.Text),
(r"(type|query|mutation|@[a-z]+|on|true|false|null)\b", token.Keyword.Type),
(r"[!$():=@\[\]{|}]+?", token.Punctuation),
(r"[_A-Za-z][_0-9A-Za-z]*", token.Keyword),
(r"(\s|,)", token.Text),
]
}
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/utils/graphql_lexer.py | graphql_lexer.py |
import warnings
from collections import Counter
from itertools import chain
from typing import Tuple
import strawberry
def merge_types(name: str, types: Tuple[type, ...]) -> type:
"""Merge multiple Strawberry types into one
For example, given two queries `A` and `B`, one can merge them into a
super type as follows:
merge_types("SuperQuery", (B, A))
This is essentially the same as:
class SuperQuery(B, A):
...
"""
if not types:
raise ValueError("Can't merge types if none are supplied")
fields = chain(
*(t._type_definition.fields for t in types) # type: ignore[attr-defined]
)
counter = Counter(f.name for f in fields)
dupes = [f for f, c in counter.most_common() if c > 1]
if dupes:
warnings.warn(
"{} has overridden fields: {}".format(name, ", ".join(dupes)), stacklevel=2
)
return strawberry.type(type(name, types, {}))
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/tools/merge_types.py | merge_types.py |
import types
from typing import List, Type
import strawberry
from strawberry.field import StrawberryField
def create_type(name: str, fields: List[StrawberryField]) -> Type:
"""Create a Strawberry type from a list of StrawberryFields
>>> @strawberry.field
>>> def hello(info) -> str:
>>> return "World"
>>>
>>> Query = create_type(name="Query", fields=[hello])
"""
if not fields:
raise ValueError(f'Can\'t create type "{name}" with no fields')
namespace = {}
annotations = {}
for field in fields:
if not isinstance(field, StrawberryField):
raise TypeError("Field is not an instance of StrawberryField")
if field.python_name is None:
raise ValueError(
"Field doesn't have a name. Fields passed to "
"`create_type` must define a name by passing the "
"`name` argument to `strawberry.field`."
)
namespace[field.python_name] = field
annotations[field.python_name] = field.type
namespace["__annotations__"] = annotations # type: ignore
cls = types.new_class(name, (), {}, lambda ns: ns.update(namespace))
return strawberry.type(cls)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/tools/create_type.py | create_type.py |
from .create_type import create_type
from .merge_types import merge_types
__all__ = [
"create_type",
"merge_types",
]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/tools/__init__.py | __init__.py |
from __future__ import annotations
import re
import typing
import warnings
from decimal import Decimal
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Set,
Tuple,
Union,
cast,
)
from mypy.nodes import (
ARG_OPT,
ARG_POS,
ARG_STAR2,
GDEF,
MDEF,
Argument,
AssignmentStmt,
Block,
CallExpr,
CastExpr,
FuncDef,
IndexExpr,
MemberExpr,
NameExpr,
PassStmt,
PlaceholderNode,
RefExpr,
SymbolTableNode,
TempNode,
TupleExpr,
TypeAlias,
TypeVarExpr,
Var,
)
from mypy.plugin import (
Plugin,
SemanticAnalyzerPluginInterface,
)
from mypy.plugins.common import _get_argument, _get_decorator_bool_argument, add_method
from mypy.plugins.dataclasses import DataclassAttribute
from mypy.semanal_shared import set_callable_name
from mypy.server.trigger import make_wildcard_trigger
from mypy.types import (
AnyType,
CallableType,
Instance,
NoneType,
TypeOfAny,
TypeVarType,
UnionType,
get_proper_type,
)
from mypy.typevars import fill_typevars
from mypy.util import get_unique_redefinition_name
# Backwards compatible with the removal of `TypeVarDef` in mypy 0.920.
try:
from mypy.types import TypeVarDef # type: ignore
except ImportError:
TypeVarDef = TypeVarType
# To be compatible with user who don't use pydantic
try:
from pydantic.mypy import METADATA_KEY as PYDANTIC_METADATA_KEY
from pydantic.mypy import PydanticModelField
except ImportError:
PYDANTIC_METADATA_KEY = ""
if TYPE_CHECKING:
from typing_extensions import Final
from mypy.nodes import ClassDef, Expression, TypeInfo
from mypy.plugins import ( # type: ignore
AnalyzeTypeContext,
CheckerPluginInterface,
ClassDefContext,
DynamicClassDefContext,
FunctionContext,
)
from mypy.types import Type
VERSION_RE = re.compile(r"(^0|^(?:[1-9][0-9]*))\.(0|(?:[1-9][0-9]*))")
FALLBACK_VERSION = Decimal("0.800")
class MypyVersion:
"""Stores the mypy version to be used by the plugin"""
VERSION: Decimal
class InvalidNodeTypeException(Exception):
def __init__(self, node: Any) -> None:
self.message = f"Invalid node type: {str(node)}"
super().__init__()
def __str__(self) -> str:
return self.message
def lazy_type_analyze_callback(ctx: AnalyzeTypeContext) -> Type:
if len(ctx.type.args) == 0:
# TODO: maybe this should throw an error
return AnyType(TypeOfAny.special_form)
type_name = ctx.type.args[0]
type_ = ctx.api.analyze_type(type_name)
return type_
def strawberry_field_hook(ctx: FunctionContext) -> Type:
# TODO: check when used as decorator, check type of the caller
# TODO: check type of resolver if any
return AnyType(TypeOfAny.special_form)
def _get_named_type(name: str, api: SemanticAnalyzerPluginInterface):
if "." in name:
return api.named_type_or_none(name)
return api.named_type(name)
def _get_type_for_expr(expr: Expression, api: SemanticAnalyzerPluginInterface) -> Type:
if isinstance(expr, NameExpr):
# guarding against invalid nodes, still have to figure out why this happens
# but sometimes mypy crashes because the internal node of the named type
# is actually a Var node, which is unexpected, so we do a naive guard here
# and raise an exception for it.
if expr.fullname:
sym = api.lookup_fully_qualified_or_none(expr.fullname)
if sym and isinstance(sym.node, Var):
raise InvalidNodeTypeException(sym.node)
return _get_named_type(expr.fullname or expr.name, api)
if isinstance(expr, IndexExpr):
type_ = _get_type_for_expr(expr.base, api)
type_.args = (_get_type_for_expr(expr.index, api),) # type: ignore
return type_
if isinstance(expr, MemberExpr):
if expr.fullname:
return _get_named_type(expr.fullname, api)
else:
raise InvalidNodeTypeException(expr)
if isinstance(expr, CallExpr):
if expr.analyzed:
return _get_type_for_expr(expr.analyzed, api)
else:
raise InvalidNodeTypeException(expr)
if isinstance(expr, CastExpr):
return expr.type
raise ValueError(f"Unsupported expression {type(expr)}")
def create_type_hook(ctx: DynamicClassDefContext) -> None:
# returning classes/type aliases is not supported yet by mypy
# see https://github.com/python/mypy/issues/5865
type_alias = TypeAlias(
AnyType(TypeOfAny.from_error),
fullname=ctx.api.qualified_name(ctx.name),
line=ctx.call.line,
column=ctx.call.column,
)
ctx.api.add_symbol_table_node(
ctx.name,
SymbolTableNode(GDEF, type_alias, plugin_generated=True),
)
return
def union_hook(ctx: DynamicClassDefContext) -> None:
try:
# Check if types is passed as a keyword argument
types = ctx.call.args[ctx.call.arg_names.index("types")]
except ValueError:
# Fall back to assuming position arguments
types = ctx.call.args[1]
if isinstance(types, TupleExpr):
try:
type_ = UnionType(
tuple(_get_type_for_expr(x, ctx.api) for x in types.items)
)
except InvalidNodeTypeException:
type_alias = TypeAlias(
AnyType(TypeOfAny.from_error),
fullname=ctx.api.qualified_name(ctx.name),
line=ctx.call.line,
column=ctx.call.column,
)
ctx.api.add_symbol_table_node(
ctx.name,
SymbolTableNode(GDEF, type_alias, plugin_generated=False),
)
return
type_alias = TypeAlias(
type_,
fullname=ctx.api.qualified_name(ctx.name),
line=ctx.call.line,
column=ctx.call.column,
)
ctx.api.add_symbol_table_node(
ctx.name, SymbolTableNode(GDEF, type_alias, plugin_generated=False)
)
def enum_hook(ctx: DynamicClassDefContext) -> None:
first_argument = ctx.call.args[0]
if isinstance(first_argument, NameExpr):
if not first_argument.node:
ctx.api.defer()
return
if isinstance(first_argument.node, Var):
var_type = first_argument.node.type or AnyType(
TypeOfAny.implementation_artifact
)
type_alias = TypeAlias(
var_type,
fullname=ctx.api.qualified_name(ctx.name),
line=ctx.call.line,
column=ctx.call.column,
)
ctx.api.add_symbol_table_node(
ctx.name, SymbolTableNode(GDEF, type_alias, plugin_generated=False)
)
return
enum_type: Optional[Type]
try:
enum_type = _get_type_for_expr(first_argument, ctx.api)
except InvalidNodeTypeException:
enum_type = None
if not enum_type:
enum_type = AnyType(TypeOfAny.from_error)
type_alias = TypeAlias(
enum_type,
fullname=ctx.api.qualified_name(ctx.name),
line=ctx.call.line,
column=ctx.call.column,
)
ctx.api.add_symbol_table_node(
ctx.name, SymbolTableNode(GDEF, type_alias, plugin_generated=False)
)
def scalar_hook(ctx: DynamicClassDefContext) -> None:
first_argument = ctx.call.args[0]
if isinstance(first_argument, NameExpr):
if not first_argument.node:
ctx.api.defer()
return
if isinstance(first_argument.node, Var):
var_type = first_argument.node.type or AnyType(
TypeOfAny.implementation_artifact
)
type_alias = TypeAlias(
var_type,
fullname=ctx.api.qualified_name(ctx.name),
line=ctx.call.line,
column=ctx.call.column,
)
ctx.api.add_symbol_table_node(
ctx.name, SymbolTableNode(GDEF, type_alias, plugin_generated=False)
)
return
scalar_type: Optional[Type]
# TODO: add proper support for NewType
try:
scalar_type = _get_type_for_expr(first_argument, ctx.api)
except InvalidNodeTypeException:
scalar_type = None
if not scalar_type:
scalar_type = AnyType(TypeOfAny.from_error)
type_alias = TypeAlias(
scalar_type,
fullname=ctx.api.qualified_name(ctx.name),
line=ctx.call.line,
column=ctx.call.column,
)
ctx.api.add_symbol_table_node(
ctx.name, SymbolTableNode(GDEF, type_alias, plugin_generated=False)
)
def add_static_method_to_class(
api: Union[SemanticAnalyzerPluginInterface, CheckerPluginInterface],
cls: ClassDef,
name: str,
args: List[Argument],
return_type: Type,
tvar_def: Optional[TypeVarType] = None,
) -> None:
"""Adds a static method
Edited add_method_to_class to incorporate static method logic
https://github.com/python/mypy/blob/9c05d3d19/mypy/plugins/common.py
"""
info = cls.info
# First remove any previously generated methods with the same name
# to avoid clashes and problems in the semantic analyzer.
if name in info.names:
sym = info.names[name]
if sym.plugin_generated and isinstance(sym.node, FuncDef):
cls.defs.body.remove(sym.node)
# For compat with mypy < 0.93
if MypyVersion.VERSION < Decimal("0.93"):
function_type = api.named_type("__builtins__.function")
else:
if isinstance(api, SemanticAnalyzerPluginInterface):
function_type = api.named_type("builtins.function")
else:
function_type = api.named_generic_type("builtins.function", [])
arg_types, arg_names, arg_kinds = [], [], []
for arg in args:
assert arg.type_annotation, "All arguments must be fully typed."
arg_types.append(arg.type_annotation)
arg_names.append(arg.variable.name)
arg_kinds.append(arg.kind)
signature = CallableType(
arg_types, arg_kinds, arg_names, return_type, function_type
)
if tvar_def:
signature.variables = [tvar_def]
func = FuncDef(name, args, Block([PassStmt()]))
func.is_static = True
func.info = info
func.type = set_callable_name(signature, func)
func._fullname = f"{info.fullname}.{name}"
func.line = info.line
# NOTE: we would like the plugin generated node to dominate, but we still
# need to keep any existing definitions so they get semantically analyzed.
if name in info.names:
# Get a nice unique name instead.
r_name = get_unique_redefinition_name(name, info.names)
info.names[r_name] = info.names[name]
info.names[name] = SymbolTableNode(MDEF, func, plugin_generated=True)
info.defn.defs.body.append(func)
def strawberry_pydantic_class_callback(ctx: ClassDefContext) -> None:
# in future we want to have a proper pydantic plugin, but for now
# let's fallback to **kwargs for __init__, some resources are here:
# https://github.com/samuelcolvin/pydantic/blob/master/pydantic/mypy.py
# >>> model_index = ctx.cls.decorators[0].arg_names.index("model")
# >>> model_name = ctx.cls.decorators[0].args[model_index].name
# >>> model_type = ctx.api.named_type("UserModel")
# >>> model_type = ctx.api.lookup(model_name, Context())
model_expression = _get_argument(call=ctx.reason, name="model")
if model_expression is None:
ctx.api.fail("model argument in decorator failed to be parsed", ctx.reason)
else:
# Add __init__
init_args = [
Argument(Var("kwargs"), AnyType(TypeOfAny.explicit), None, ARG_STAR2)
]
add_method(ctx, "__init__", init_args, NoneType())
model_type = cast(Instance, _get_type_for_expr(model_expression, ctx.api))
# these are the fields that the user added to the strawberry type
new_strawberry_fields: Set[str] = set()
# TODO: think about inheritance for strawberry?
for stmt in ctx.cls.defs.body:
if isinstance(stmt, AssignmentStmt):
lhs = cast(NameExpr, stmt.lvalues[0])
new_strawberry_fields.add(lhs.name)
pydantic_fields: Set[PydanticModelField] = set()
try:
for _name, data in model_type.type.metadata[PYDANTIC_METADATA_KEY][
"fields"
].items():
field = PydanticModelField.deserialize(ctx.cls.info, data)
pydantic_fields.add(field)
except KeyError:
# this will happen if the user didn't add the pydantic plugin
# AND is using the pydantic conversion decorator
ctx.api.fail(
"Pydantic plugin not installed,"
" please add pydantic.mypy your mypy.ini plugins",
ctx.reason,
)
potentially_missing_fields: Set[PydanticModelField] = {
f for f in pydantic_fields if f.name not in new_strawberry_fields
}
"""
Need to check if all_fields=True from the pydantic decorator
There is no way to real check that Literal[True] was used
We just check if the strawberry type is missing all the fields
This means that the user is using all_fields=True
"""
is_all_fields: bool = len(potentially_missing_fields) == len(pydantic_fields)
missing_pydantic_fields: Set[PydanticModelField] = (
potentially_missing_fields if not is_all_fields else set()
)
# Add the default to_pydantic if undefined by the user
if "to_pydantic" not in ctx.cls.info.names:
add_method(
ctx,
"to_pydantic",
args=[
f.to_argument(
# TODO: use_alias should depend on config?
info=model_type.type,
typed=True,
force_optional=False,
use_alias=True,
)
for f in missing_pydantic_fields
],
return_type=model_type,
)
# Add from_pydantic
model_argument = Argument(
variable=Var(name="instance", type=model_type),
type_annotation=model_type,
initializer=None,
kind=ARG_OPT,
)
add_static_method_to_class(
ctx.api,
ctx.cls,
name="from_pydantic",
args=[model_argument],
return_type=fill_typevars(ctx.cls.info),
)
def is_dataclasses_field_or_strawberry_field(expr: Expression) -> bool:
if isinstance(expr, CallExpr):
if isinstance(expr.callee, RefExpr) and expr.callee.fullname in (
"dataclasses.field",
"strawberry.field.field",
"strawberry.mutation.mutation",
"strawberry.federation.field",
"strawberry.federation.field.field",
):
return True
if isinstance(expr.callee, MemberExpr) and isinstance(
expr.callee.expr, NameExpr
):
return (
expr.callee.name in {"field", "mutation"}
and expr.callee.expr.name == "strawberry"
)
return False
def _collect_field_args(
ctx: ClassDefContext, expr: Expression
) -> Tuple[bool, Dict[str, Expression]]:
"""Returns a tuple where the first value represents whether or not
the expression is a call to dataclass.field and the second is a
dictionary of the keyword arguments that field() was called with.
"""
if is_dataclasses_field_or_strawberry_field(expr):
expr = cast(CallExpr, expr)
args = {}
for name, arg in zip(expr.arg_names, expr.args):
if name is None:
ctx.api.fail(
'"field()" or "mutation()" only takes keyword arguments', expr
)
return False, {}
args[name] = arg
return True, args
return False, {}
# Custom dataclass transformer that knows about strawberry.field, we cannot
# extend the mypy one as it might be compiled by mypyc and we'd get this error
# >>> TypeError: interpreted classes cannot inherit from compiled
# Original copy from
# https://github.com/python/mypy/blob/5253f7c0/mypy/plugins/dataclasses.py
SELF_TVAR_NAME: Final = "_DT"
class CustomDataclassTransformer:
def __init__(self, ctx: ClassDefContext) -> None:
self._ctx = ctx
def transform(self) -> None:
"""Apply all the necessary transformations to the underlying
dataclass so as to ensure it is fully type checked according
to the rules in PEP 557.
"""
ctx = self._ctx
info = self._ctx.cls.info
attributes = self.collect_attributes()
if attributes is None:
# Some definitions are not ready, defer() should be already called.
return
for attr in attributes:
if attr.type is None:
ctx.api.defer()
return
decorator_arguments = {
"init": _get_decorator_bool_argument(self._ctx, "init", True),
"eq": _get_decorator_bool_argument(self._ctx, "eq", True),
"order": _get_decorator_bool_argument(self._ctx, "order", False),
"frozen": _get_decorator_bool_argument(self._ctx, "frozen", False),
}
# If there are no attributes, it may be that the semantic analyzer has not
# processed them yet. In order to work around this, we can simply skip
# generating __init__ if there are no attributes, because if the user
# truly did not define any, then the object default __init__ with an
# empty signature will be present anyway.
if (
decorator_arguments["init"]
and (
"__init__" not in info.names or info.names["__init__"].plugin_generated
)
and attributes
):
args = [info] if MypyVersion.VERSION >= Decimal("1.0") else []
add_method(
ctx,
"__init__",
args=[
attr.to_argument(*args) for attr in attributes if attr.is_in_init
],
return_type=NoneType(),
)
if (
decorator_arguments["eq"]
and info.get("__eq__") is None
or decorator_arguments["order"]
):
# Type variable for self types in generated methods.
obj_type = ctx.api.named_type("__builtins__.object")
self_tvar_expr = TypeVarExpr(
SELF_TVAR_NAME, info.fullname + "." + SELF_TVAR_NAME, [], obj_type
)
info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)
# Add <, >, <=, >=, but only if the class has an eq method.
if decorator_arguments["order"]:
if not decorator_arguments["eq"]:
ctx.api.fail("eq must be True if order is True", ctx.cls)
for method_name in ["__lt__", "__gt__", "__le__", "__ge__"]:
# Like for __eq__ and __ne__, we want "other" to match
# the self type.
obj_type = ctx.api.named_type("__builtins__.object")
order_tvar_def = TypeVarDef(
SELF_TVAR_NAME,
info.fullname + "." + SELF_TVAR_NAME,
-1,
[],
obj_type,
)
# Backwards compatible with the removal of `TypeVarDef` in mypy 0.920.
if isinstance(order_tvar_def, TypeVarType):
order_other_type = order_tvar_def
else:
order_other_type = TypeVarType(order_tvar_def) # type: ignore
order_return_type = ctx.api.named_type("__builtins__.bool")
order_args = [
Argument(
Var("other", order_other_type), order_other_type, None, ARG_POS
)
]
existing_method = info.get(method_name)
if existing_method is not None and not existing_method.plugin_generated:
assert existing_method.node
ctx.api.fail(
"You may not have a custom %s method when order=True"
% method_name,
existing_method.node,
)
add_method(
ctx,
method_name,
args=order_args,
return_type=order_return_type,
self_type=order_other_type,
tvar_def=order_tvar_def,
)
if decorator_arguments["frozen"]:
self._freeze(attributes)
else:
self._propertize_callables(attributes)
self.reset_init_only_vars(info, attributes)
info.metadata["dataclass"] = {
"attributes": [attr.serialize() for attr in attributes],
"frozen": decorator_arguments["frozen"],
}
def reset_init_only_vars(
self, info: TypeInfo, attributes: List[DataclassAttribute]
) -> None:
"""Remove init-only vars from the class and reset init var declarations."""
for attr in attributes:
if attr.is_init_var:
if attr.name in info.names:
del info.names[attr.name]
else:
# Nodes of superclass InitVars not used in __init__
# cannot be reached.
assert attr.is_init_var
for stmt in info.defn.defs.body:
if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:
lvalue = stmt.lvalues[0]
if isinstance(lvalue, NameExpr) and lvalue.name == attr.name:
# Reset node so that another semantic analysis pass will
# recreate a symbol node for this attribute.
lvalue.node = None
def collect_attributes(self) -> Optional[List[DataclassAttribute]]:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
"""
# First, collect attributes belonging to the current class.
ctx = self._ctx
cls = self._ctx.cls
attrs: List[DataclassAttribute] = []
known_attrs: Set[str] = set()
for stmt in cls.defs.body:
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not (isinstance(stmt, AssignmentStmt) and stmt.new_syntax):
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
sym = cls.info.names.get(lhs.name)
if sym is None:
# This name is likely blocked by a star import. We don't need
# to defer because defer() is already called by mark_incomplete().
continue
node = sym.node
if isinstance(node, PlaceholderNode):
# This node is not ready yet.
return None
assert isinstance(node, Var)
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
node_type = get_proper_type(node.type)
if (
isinstance(node_type, Instance)
and node_type.type.fullname == "dataclasses.InitVar"
):
is_init_var = True
node.type = node_type.args[0]
has_field_call, field_args = _collect_field_args(ctx, stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = True
else:
is_in_init = bool(ctx.api.parse_bool(is_in_init_param))
# fields with a resolver are never put in the __init__ method
if "resolver" in field_args:
is_in_init = False
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = "default" in field_args or "default_factory" in field_args
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
if not has_default:
# Make all non-default attributes implicit because they are de-facto set
# on self in the generated __init__(), not in the class body.
sym.implicit = True
known_attrs.add(lhs.name)
params = dict(
name=lhs.name,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
type=sym.type,
)
# Support the addition of `info` in mypy 0.800 and `kw_only` in mypy 0.920
# without breaking backwards compatibility.
if MypyVersion.VERSION >= Decimal("0.800"):
params["info"] = cls.info
if MypyVersion.VERSION >= Decimal("0.920"):
params["kw_only"] = True
if MypyVersion.VERSION >= Decimal("1.1"):
params["alias"] = None
attribute = DataclassAttribute(**params)
attrs.append(attribute)
# Next, collect attributes belonging to any class in the MRO
# as long as those attributes weren't already collected. This
# makes it possible to overwrite attributes in subclasses.
# copy() because we potentially modify all_attrs below and if
# this code requires debugging we'll have unmodified attrs laying around.
all_attrs = attrs.copy()
for info in cls.info.mro[1:-1]:
if "dataclass" not in info.metadata:
continue
super_attrs = []
# Each class depends on the set of attributes in its dataclass ancestors.
ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
for data in info.metadata["dataclass"]["attributes"]:
name: str = data["name"]
if name not in known_attrs:
attr = DataclassAttribute.deserialize(info, data, ctx.api)
attr.expand_typevar_from_subtype(ctx.cls.info)
known_attrs.add(name)
super_attrs.append(attr)
elif all_attrs:
# How early in the attribute list an attribute appears is
# determined by the reverse MRO, not simply MRO.
# See https://docs.python.org/3/library/dataclasses.html#inheritance
# for details.
for attr in all_attrs:
if attr.name == name:
all_attrs.remove(attr)
super_attrs.append(attr)
break
all_attrs = super_attrs + all_attrs
return all_attrs
def _freeze(self, attributes: List[DataclassAttribute]) -> None:
"""Converts all attributes to @property methods in order to
emulate frozen classes.
"""
info = self._ctx.cls.info
for attr in attributes:
sym_node = info.names.get(attr.name)
if sym_node is not None:
var = sym_node.node
assert isinstance(var, Var)
var.is_property = True
else:
if MypyVersion.VERSION >= Decimal("1.0"):
var = attr.to_var(current_info=info)
else:
var = attr.to_var() # type: ignore
var.info = info
var.is_property = True
var._fullname = info.fullname + "." + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)
def _propertize_callables(self, attributes: List[DataclassAttribute]) -> None:
"""Converts all attributes with callable types to @property methods.
This avoids the typechecker getting confused and thinking that
`my_dataclass_instance.callable_attr(foo)` is going to receive a
`self` argument (it is not).
"""
info = self._ctx.cls.info
for attr in attributes:
if isinstance(get_proper_type(attr.type), CallableType):
if MypyVersion.VERSION >= Decimal("1.0"):
var = attr.to_var(current_info=info)
else:
var = attr.to_var() # type: ignore
var.info = info
var.is_property = True
var.is_settable_property = True
var._fullname = info.fullname + "." + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)
def custom_dataclass_class_maker_callback(ctx: ClassDefContext) -> None:
"""Hooks into the class typechecking process to add support for dataclasses."""
transformer = CustomDataclassTransformer(ctx)
transformer.transform()
class StrawberryPlugin(Plugin):
def get_dynamic_class_hook(
self, fullname: str
) -> Optional[Callable[[DynamicClassDefContext], None]]:
# TODO: investigate why we need this instead of `strawberry.union.union` on CI
# we have the same issue in the other hooks
if self._is_strawberry_union(fullname):
return union_hook
if self._is_strawberry_enum(fullname):
return enum_hook
if self._is_strawberry_scalar(fullname):
return scalar_hook
if self._is_strawberry_create_type(fullname):
return create_type_hook
return None
def get_function_hook(
self, fullname: str
) -> Optional[Callable[[FunctionContext], Type]]:
if self._is_strawberry_field(fullname):
return strawberry_field_hook
return None
def get_type_analyze_hook(self, fullname: str) -> Union[Callable[..., Type], None]:
if self._is_strawberry_lazy_type(fullname):
return lazy_type_analyze_callback
return None
def get_class_decorator_hook(
self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
if self._is_strawberry_decorator(fullname):
return custom_dataclass_class_maker_callback
if self._is_strawberry_pydantic_decorator(fullname):
return strawberry_pydantic_class_callback
return None
def _is_strawberry_union(self, fullname: str) -> bool:
return fullname == "strawberry.union.union" or fullname.endswith(
"strawberry.union"
)
def _is_strawberry_field(self, fullname: str) -> bool:
if fullname in {
"strawberry.field.field",
"strawberry.mutation.mutation",
"strawberry.federation.field",
}:
return True
return any(
fullname.endswith(decorator)
for decorator in {
"strawberry.field",
"strawberry.mutation",
"strawberry.federation.field",
}
)
def _is_strawberry_enum(self, fullname: str) -> bool:
return fullname == "strawberry.enum.enum" or fullname.endswith(
"strawberry.enum"
)
def _is_strawberry_scalar(self, fullname: str) -> bool:
return fullname == "strawberry.custom_scalar.scalar" or fullname.endswith(
"strawberry.scalar"
)
def _is_strawberry_lazy_type(self, fullname: str) -> bool:
return fullname == "strawberry.lazy_type.LazyType"
def _is_strawberry_decorator(self, fullname: str) -> bool:
if any(
strawberry_decorator in fullname
for strawberry_decorator in {
"strawberry.object_type.type",
"strawberry.federation.type",
"strawberry.federation.object_type.type",
"strawberry.federation.input",
"strawberry.federation.object_type.input",
"strawberry.federation.interface",
"strawberry.federation.object_type.interface",
"strawberry.schema_directive.schema_directive",
"strawberry.federation.schema_directive",
"strawberry.federation.schema_directive.schema_directive",
"strawberry.object_type.input",
"strawberry.object_type.interface",
}
):
return True
# in some cases `fullpath` is not what we would expect, this usually
# happens when `follow_imports` are disabled in mypy when you get a path
# that looks likes `some_module.types.strawberry.type`
return any(
fullname.endswith(decorator)
for decorator in {
"strawberry.type",
"strawberry.federation.type",
"strawberry.input",
"strawberry.interface",
"strawberry.schema_directive",
"strawberry.federation.schema_directive",
}
)
def _is_strawberry_create_type(self, fullname: str) -> bool:
# using endswith(.create_type) is not ideal as there might be
# other function called like that, but it's the best we can do
# when follow-imports is set to "skip". Hopefully in the future
# we can remove our custom hook for create type
return (
fullname == "strawberry.tools.create_type.create_type"
or fullname.endswith(".create_type")
)
def _is_strawberry_pydantic_decorator(self, fullname: str) -> bool:
if any(
strawberry_decorator in fullname
for strawberry_decorator in {
"strawberry.experimental.pydantic.object_type.type",
"strawberry.experimental.pydantic.object_type.input",
"strawberry.experimental.pydantic.object_type.interface",
"strawberry.experimental.pydantic.error_type",
}
):
return True
# in some cases `fullpath` is not what we would expect, this usually
# happens when `follow_imports` are disabled in mypy when you get a path
# that looks likes `some_module.types.strawberry.type`
return any(
fullname.endswith(decorator)
for decorator in {
"strawberry.experimental.pydantic.type",
"strawberry.experimental.pydantic.input",
"strawberry.experimental.pydantic.error_type",
}
)
def plugin(version: str) -> typing.Type[StrawberryPlugin]:
match = VERSION_RE.match(version)
if match:
MypyVersion.VERSION = Decimal(".".join(match.groups()))
else:
MypyVersion.VERSION = FALLBACK_VERSION
warnings.warn(
f"Mypy version {version} could not be parsed. Reverting to v0.800",
stacklevel=1,
)
return StrawberryPlugin
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/ext/mypy_plugin.py | mypy_plugin.py |
#
# This code is licensed under the Python Software Foundation License Version 2
#
from dataclasses import ( # type: ignore
_FIELD_INITVAR,
_HAS_DEFAULT_FACTORY,
_POST_INIT_NAME,
MISSING,
_create_fn,
_field_init,
_init_param,
)
from typing import Any
def dataclass_init_fn(fields, frozen, has_post_init, self_name, globals_) -> Any:
"""
We create a custom __init__ function for the dataclasses that back
Strawberry object types to only accept keyword arguments. This allows us to
avoid the problem where a type cannot define a field with a default value
before a field that doesn't have a default value.
An example of the problem:
https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses
Code is adapted from:
https://github.com/python/cpython/blob/v3.9.6/Lib/dataclasses.py#L489-L536
Note: in Python 3.10 and above we use the `kw_only` argument to achieve the
same result.
"""
# fields contains both real fields and InitVar pseudo-fields.
locals_ = {f"_type_{f.name}": f.type for f in fields}
locals_.update(
{
"MISSING": MISSING,
"_HAS_DEFAULT_FACTORY": _HAS_DEFAULT_FACTORY,
}
)
body_lines = []
for f in fields:
line = _field_init(f, frozen, locals_, self_name)
# line is None means that this field doesn't require
# initialization (it's a pseudo-field). Just skip it.
if line:
body_lines.append(line)
# Does this class have a post-init function?
if has_post_init:
params_str = ",".join(f.name for f in fields if f._field_type is _FIELD_INITVAR)
body_lines.append(f"{self_name}.{_POST_INIT_NAME}({params_str})")
# If no body lines, use 'pass'.
if not body_lines:
body_lines = ["pass"]
_init_params = [_init_param(f) for f in fields if f.init]
if len(_init_params) > 0:
_init_params = ["*", *_init_params]
return _create_fn(
"__init__",
[self_name, *_init_params],
body_lines,
locals=locals_,
globals=globals_,
return_type=None,
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/ext/dataclasses/dataclasses.py | dataclasses.py |
import copy
from typing import Any, Dict, List, Mapping
def replace_placeholders_with_files(
operations_with_placeholders: Dict[str, Any],
files_map: Mapping[str, List[str]],
files: Mapping[str, Any],
) -> Dict[str, Any]:
# TODO: test this with missing variables in operations_with_placeholders
operations = copy.deepcopy(operations_with_placeholders)
for multipart_form_field_name, operations_paths in files_map.items():
file_object = files[multipart_form_field_name]
for path in operations_paths:
operations_path_keys = path.split(".")
value_key = operations_path_keys.pop()
target_object = operations
for key in operations_path_keys:
if isinstance(target_object, list):
target_object = target_object[int(key)]
else:
target_object = target_object[key]
if isinstance(target_object, list):
target_object[int(value_key)] = file_object
else:
target_object[value_key] = file_object
return operations
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/file_uploads/utils.py | utils.py |
from typing import NewType
from ..custom_scalar import scalar
Upload = scalar(NewType("Upload", bytes), parse_value=lambda x: x)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/file_uploads/scalars.py | scalars.py |
from .scalars import Upload
__all__ = ["Upload"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/file_uploads/__init__.py | __init__.py |
from __future__ import annotations
import dataclasses
import re
from math import isfinite
from typing import TYPE_CHECKING, Any, Mapping, Optional, cast
from graphql.language import (
BooleanValueNode,
EnumValueNode,
FloatValueNode,
IntValueNode,
ListValueNode,
NameNode,
NullValueNode,
ObjectFieldNode,
ObjectValueNode,
StringValueNode,
)
from graphql.pyutils import Undefined, inspect, is_iterable
from graphql.type import (
GraphQLID,
is_enum_type,
is_input_object_type,
is_leaf_type,
is_list_type,
is_non_null_type,
)
if TYPE_CHECKING:
from graphql.language import ValueNode
from graphql.type import (
GraphQLInputObjectType,
GraphQLInputType,
GraphQLList,
GraphQLNonNull,
)
__all__ = ["ast_from_value"]
_re_integer_string = re.compile("^-?(?:0|[1-9][0-9]*)$")
def ast_from_leaf_type(
serialized: object, type_: Optional[GraphQLInputType]
) -> ValueNode:
# Others serialize based on their corresponding Python scalar types.
if isinstance(serialized, bool):
return BooleanValueNode(value=serialized)
# Python ints and floats correspond nicely to Int and Float values.
if isinstance(serialized, int):
return IntValueNode(value=str(serialized))
if isinstance(serialized, float) and isfinite(serialized):
value = str(serialized)
if value.endswith(".0"):
value = value[:-2]
return FloatValueNode(value=value)
if isinstance(serialized, str):
# Enum types use Enum literals.
if type_ and is_enum_type(type_):
return EnumValueNode(value=serialized)
# ID types can use Int literals.
if type_ is GraphQLID and _re_integer_string.match(serialized):
return IntValueNode(value=serialized)
return StringValueNode(value=serialized)
if isinstance(serialized, dict):
return ObjectValueNode(
fields=[
ObjectFieldNode(
name=NameNode(value=key),
value=ast_from_leaf_type(value, None),
)
for key, value in serialized.items()
]
)
raise TypeError(
f"Cannot convert value to AST: {inspect(serialized)}."
) # pragma: no cover
def ast_from_value(value: Any, type_: GraphQLInputType) -> Optional[ValueNode]:
# custom ast_from_value that allows to also serialize custom scalar that aren't
# basic types, namely JSON scalar types
if is_non_null_type(type_):
type_ = cast("GraphQLNonNull", type_)
ast_value = ast_from_value(value, type_.of_type)
if isinstance(ast_value, NullValueNode):
return None
return ast_value
# only explicit None, not Undefined or NaN
if value is None:
return NullValueNode()
# undefined
if value is Undefined:
return None
# Convert Python list to GraphQL list. If the GraphQLType is a list, but the value
# is not a list, convert the value using the list's item type.
if is_list_type(type_):
type_ = cast("GraphQLList", type_)
item_type = type_.of_type
if is_iterable(value):
maybe_value_nodes = (ast_from_value(item, item_type) for item in value)
value_nodes = tuple(node for node in maybe_value_nodes if node)
return ListValueNode(values=value_nodes)
return ast_from_value(value, item_type)
# Populate the fields of the input object by creating ASTs from each value in the
# Python dict according to the fields in the input type.
if is_input_object_type(type_):
# TODO: is this the right place?
if hasattr(value, "_type_definition"):
value = dataclasses.asdict(value)
if value is None or not isinstance(value, Mapping):
return None
type_ = cast("GraphQLInputObjectType", type_)
field_items = (
(field_name, ast_from_value(value[field_name], field.type))
for field_name, field in type_.fields.items()
if field_name in value
)
field_nodes = tuple(
ObjectFieldNode(name=NameNode(value=field_name), value=field_value)
for field_name, field_value in field_items
if field_value
)
return ObjectValueNode(fields=field_nodes)
if is_leaf_type(type_):
# Since value is an internally represented value, it must be serialized to an
# externally represented value before converting into an AST.
serialized = type_.serialize(value) # type: ignore
if serialized is None or serialized is Undefined:
return None # pragma: no cover
return ast_from_leaf_type(serialized, type_)
# Not reachable. All possible input types have been considered.
raise TypeError(f"Unexpected input type: {inspect(type_)}.") # pragma: no cover
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/printer/ast_from_value.py | ast_from_value.py |
from __future__ import annotations
import dataclasses
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Set,
Tuple,
TypeVar,
Union,
cast,
overload,
)
from graphql import is_union_type
from graphql.language.printer import print_ast
from graphql.type import (
is_enum_type,
is_input_type,
is_interface_type,
is_object_type,
is_scalar_type,
is_specified_directive,
)
from graphql.utilities.print_schema import (
is_defined_type,
print_block,
print_deprecated,
print_description,
print_implemented_interfaces,
print_specified_by_url,
)
from graphql.utilities.print_schema import print_type as original_print_type
from strawberry.custom_scalar import ScalarWrapper
from strawberry.enum import EnumDefinition
from strawberry.schema_directive import Location, StrawberrySchemaDirective
from strawberry.type import StrawberryContainer
from strawberry.unset import UNSET
from .ast_from_value import ast_from_value
if TYPE_CHECKING:
from graphql import (
GraphQLArgument,
GraphQLEnumType,
GraphQLEnumValue,
GraphQLScalarType,
GraphQLUnionType,
)
from graphql.type.directives import GraphQLDirective
from strawberry.field import StrawberryField
from strawberry.schema import BaseSchema
_T = TypeVar("_T")
@dataclasses.dataclass
class PrintExtras:
directives: Set[str] = dataclasses.field(default_factory=set)
types: Set[type] = dataclasses.field(default_factory=set)
@overload
def _serialize_dataclasses(value: Dict[_T, object]) -> Dict[_T, object]:
...
@overload
def _serialize_dataclasses(value: Union[List[object], Tuple[object]]) -> List[object]:
...
@overload
def _serialize_dataclasses(value: object) -> object:
...
def _serialize_dataclasses(value):
if dataclasses.is_dataclass(value):
return dataclasses.asdict(value)
if isinstance(value, (list, tuple)):
return [_serialize_dataclasses(v) for v in value]
if isinstance(value, dict):
return {k: _serialize_dataclasses(v) for k, v in value.items()}
return value
def print_schema_directive_params(
directive: GraphQLDirective, values: Dict[str, Any]
) -> str:
params = []
for name, arg in directive.args.items():
value = values.get(name, arg.default_value)
if value is UNSET:
value = None
else:
ast = ast_from_value(_serialize_dataclasses(value), arg.type)
value = ast and f"{name}: {print_ast(ast)}"
if value:
params.append(value)
if not params:
return ""
return "(" + ", ".join(params) + ")"
def print_schema_directive(
directive: Any, schema: BaseSchema, *, extras: PrintExtras
) -> str:
strawberry_directive = cast(
StrawberrySchemaDirective, directive.__class__.__strawberry_directive__
)
schema_converter = schema.schema_converter
gql_directive = schema_converter.from_schema_directive(directive.__class__)
params = print_schema_directive_params(
gql_directive,
{
schema.config.name_converter.get_graphql_name(f): getattr(
directive, f.python_name or f.name, UNSET
)
for f in strawberry_directive.fields
},
)
printed_directive = print_directive(gql_directive, schema=schema)
if printed_directive is not None:
extras.directives.add(printed_directive)
for field in strawberry_directive.fields:
f_type = field.type
while isinstance(f_type, StrawberryContainer):
f_type = f_type.of_type
if hasattr(f_type, "_type_definition"):
extras.types.add(cast(type, f_type))
if hasattr(f_type, "_scalar_definition"):
extras.types.add(cast(type, f_type))
if isinstance(f_type, EnumDefinition):
extras.types.add(cast(type, f_type))
return f" @{gql_directive.name}{params}"
def print_field_directives(
field: Optional[StrawberryField], schema: BaseSchema, *, extras: PrintExtras
) -> str:
if not field:
return ""
directives = (
directive
for directive in field.directives
if any(
location in [Location.FIELD_DEFINITION, Location.INPUT_FIELD_DEFINITION]
for location in directive.__strawberry_directive__.locations # type: ignore
)
)
return "".join(
print_schema_directive(directive, schema=schema, extras=extras)
for directive in directives
)
def print_argument_directives(
argument: GraphQLArgument, *, schema: BaseSchema, extras: PrintExtras
) -> str:
strawberry_type = argument.extensions.get("strawberry-definition")
directives = strawberry_type.directives if strawberry_type else []
return "".join(
print_schema_directive(directive, schema=schema, extras=extras)
for directive in directives
)
def print_args(
args: Dict[str, GraphQLArgument],
indentation: str = "",
*,
schema: BaseSchema,
extras: PrintExtras,
) -> str:
if not args:
return ""
# If every arg does not have a description, print them on one line.
if not any(arg.description for arg in args.values()):
return (
"("
+ ", ".join(
(
f"{print_input_value(name, arg)}"
f"{print_argument_directives(arg, schema=schema, extras=extras)}"
)
for name, arg in args.items()
)
+ ")"
)
return (
"(\n"
+ "\n".join(
print_description(arg, f" {indentation}", not i)
+ f" {indentation}"
+ print_input_value(name, arg)
+ print_argument_directives(arg, schema=schema, extras=extras)
for i, (name, arg) in enumerate(args.items())
)
+ f"\n{indentation})"
)
def print_fields(type_, schema: BaseSchema, *, extras: PrintExtras) -> str:
from strawberry.schema.schema_converter import GraphQLCoreConverter
fields = []
for i, (name, field) in enumerate(type_.fields.items()):
strawberry_field = field.extensions and field.extensions.get(
GraphQLCoreConverter.DEFINITION_BACKREF
)
args = (
print_args(field.args, " ", schema=schema, extras=extras)
if hasattr(field, "args")
else ""
)
fields.append(
print_description(field, " ", not i)
+ f" {name}"
+ args
+ f": {field.type}"
+ print_field_directives(strawberry_field, schema=schema, extras=extras)
+ print_deprecated(field.deprecation_reason)
)
return print_block(fields)
def print_scalar(
type_: GraphQLScalarType, *, schema: BaseSchema, extras: PrintExtras
) -> str:
# TODO: refactor this
strawberry_type = type_.extensions.get("strawberry-definition")
directives = strawberry_type.directives if strawberry_type else []
printed_directives = "".join(
print_schema_directive(directive, schema=schema, extras=extras)
for directive in directives
)
return (
print_description(type_)
+ f"scalar {type_.name}"
+ print_specified_by_url(type_)
+ printed_directives
).strip()
def print_enum_value(
name: str,
value: GraphQLEnumValue,
first_in_block,
*,
schema: BaseSchema,
extras: PrintExtras,
) -> str:
strawberry_type = value.extensions.get("strawberry-definition")
directives = strawberry_type.directives if strawberry_type else []
printed_directives = "".join(
print_schema_directive(directive, schema=schema, extras=extras)
for directive in directives
)
return (
print_description(value, " ", first_in_block)
+ f" {name}"
+ print_deprecated(value.deprecation_reason)
+ printed_directives
)
def print_enum(
type_: GraphQLEnumType, *, schema: BaseSchema, extras: PrintExtras
) -> str:
strawberry_type = type_.extensions.get("strawberry-definition")
directives = strawberry_type.directives if strawberry_type else []
printed_directives = "".join(
print_schema_directive(directive, schema=schema, extras=extras)
for directive in directives
)
values = [
print_enum_value(name, value, not i, schema=schema, extras=extras)
for i, (name, value) in enumerate(type_.values.items())
]
return (
print_description(type_)
+ f"enum {type_.name}"
+ printed_directives
+ print_block(values)
)
def print_extends(type_, schema: BaseSchema) -> str:
from strawberry.schema.schema_converter import GraphQLCoreConverter
strawberry_type = type_.extensions and type_.extensions.get(
GraphQLCoreConverter.DEFINITION_BACKREF
)
if strawberry_type and strawberry_type.extend:
return "extend "
return ""
def print_type_directives(type_, schema: BaseSchema, *, extras: PrintExtras) -> str:
from strawberry.schema.schema_converter import GraphQLCoreConverter
strawberry_type = type_.extensions and type_.extensions.get(
GraphQLCoreConverter.DEFINITION_BACKREF
)
if not strawberry_type:
return ""
allowed_locations = (
[Location.INPUT_OBJECT] if strawberry_type.is_input else [Location.OBJECT]
)
directives = (
directive
for directive in strawberry_type.directives or []
if any(
location in allowed_locations
for location in directive.__strawberry_directive__.locations
)
)
return "".join(
print_schema_directive(directive, schema=schema, extras=extras)
for directive in directives
)
def _print_object(type_, schema: BaseSchema, *, extras: PrintExtras) -> str:
return (
print_description(type_)
+ print_extends(type_, schema)
+ f"type {type_.name}"
+ print_implemented_interfaces(type_)
+ print_type_directives(type_, schema, extras=extras)
+ print_fields(type_, schema, extras=extras)
)
def _print_interface(type_, schema: BaseSchema, *, extras: PrintExtras) -> str:
return (
print_description(type_)
+ print_extends(type_, schema)
+ f"interface {type_.name}"
+ print_implemented_interfaces(type_)
+ print_type_directives(type_, schema, extras=extras)
+ print_fields(type_, schema, extras=extras)
)
def print_input_value(name: str, arg: GraphQLArgument) -> str:
default_ast = ast_from_value(arg.default_value, arg.type)
arg_decl = f"{name}: {arg.type}"
if default_ast:
arg_decl += f" = {print_ast(default_ast)}"
return arg_decl + print_deprecated(arg.deprecation_reason)
def _print_input_object(type_, schema: BaseSchema, *, extras: PrintExtras) -> str:
from strawberry.schema.schema_converter import GraphQLCoreConverter
fields = []
for i, (name, field) in enumerate(type_.fields.items()):
strawberry_field = field.extensions and field.extensions.get(
GraphQLCoreConverter.DEFINITION_BACKREF
)
fields.append(
print_description(field, " ", not i)
+ " "
+ print_input_value(name, field)
+ print_field_directives(strawberry_field, schema=schema, extras=extras)
)
return (
print_description(type_)
+ f"input {type_.name}"
+ print_type_directives(type_, schema, extras=extras)
+ print_block(fields)
)
def print_union(
type_: GraphQLUnionType, *, schema: BaseSchema, extras: PrintExtras
) -> str:
strawberry_type = type_.extensions.get("strawberry-definition")
directives = strawberry_type.directives if strawberry_type else []
printed_directives = "".join(
print_schema_directive(directive, schema=schema, extras=extras)
for directive in directives
)
types = type_.types
possible_types = " = " + " | ".join(t.name for t in types) if types else ""
return (
print_description(type_)
+ f"union {type_.name}{printed_directives}"
+ possible_types
)
def _print_type(type_, schema: BaseSchema, *, extras: PrintExtras) -> str:
# prevents us from trying to print a scalar as an input type
if is_scalar_type(type_):
return print_scalar(type_, schema=schema, extras=extras)
if is_enum_type(type_):
return print_enum(type_, schema=schema, extras=extras)
if is_object_type(type_):
return _print_object(type_, schema, extras=extras)
if is_input_type(type_):
return _print_input_object(type_, schema, extras=extras)
if is_interface_type(type_):
return _print_interface(type_, schema, extras=extras)
if is_union_type(type_):
return print_union(type_, schema=schema, extras=extras)
return original_print_type(type_)
def print_schema_directives(schema: BaseSchema, *, extras: PrintExtras) -> str:
directives = (
directive
for directive in schema.schema_directives
if any(
location in [Location.SCHEMA]
for location in directive.__strawberry_directive__.locations # type: ignore
)
)
return "".join(
print_schema_directive(directive, schema=schema, extras=extras)
for directive in directives
)
def _all_root_names_are_common_names(schema: BaseSchema) -> bool:
query = schema.query._type_definition
mutation = schema.mutation._type_definition if schema.mutation else None
subscription = schema.subscription._type_definition if schema.subscription else None
return (
query.name == "Query"
and (mutation is None or mutation.name == "Mutation")
and (subscription is None or subscription.name == "Subscription")
)
def print_schema_definition(
schema: BaseSchema, *, extras: PrintExtras
) -> Optional[str]:
# TODO: add support for description
if _all_root_names_are_common_names(schema) and not schema.schema_directives:
return None
query_type = schema.query._type_definition
operation_types = [f" query: {query_type.name}"]
if schema.mutation:
mutation_type = schema.mutation._type_definition
operation_types.append(f" mutation: {mutation_type.name}")
if schema.subscription:
subscription_type = schema.subscription._type_definition
operation_types.append(f" subscription: {subscription_type.name}")
directives = print_schema_directives(schema, extras=extras)
return f"schema{directives} {{\n" + "\n".join(operation_types) + "\n}"
def print_directive(
directive: GraphQLDirective, *, schema: BaseSchema
) -> Optional[str]:
strawberry_directive = directive.extensions["strawberry-definition"]
if (
isinstance(strawberry_directive, StrawberrySchemaDirective)
and not strawberry_directive.print_definition
):
return None
return (
print_description(directive)
+ f"directive @{directive.name}"
# TODO: add support for directives on arguments directives
+ print_args(directive.args, schema=schema, extras=PrintExtras())
+ (" repeatable" if directive.is_repeatable else "")
+ " on "
+ " | ".join(location.name for location in directive.locations)
)
def is_builtin_directive(directive: GraphQLDirective) -> bool:
# this allows to force print the builtin directives if there's a
# directive that was implemented using the schema_directive
if is_specified_directive(directive):
strawberry_definition = directive.extensions.get("strawberry-definition")
return strawberry_definition is None
return False
def print_schema(schema: BaseSchema) -> str:
graphql_core_schema = schema._schema # type: ignore
extras = PrintExtras()
directives = filter(
lambda n: not is_builtin_directive(n), graphql_core_schema.directives
)
type_map = graphql_core_schema.type_map
types = filter(is_defined_type, map(type_map.get, sorted(type_map)))
types_printed = [_print_type(type_, schema, extras=extras) for type_ in types]
schema_definition = print_schema_definition(schema, extras=extras)
directives = filter(
None, [print_directive(directive, schema=schema) for directive in directives]
)
def _name_getter(type_: Any):
if hasattr(type_, "name"):
return type_.name
if isinstance(type_, ScalarWrapper):
return type_._scalar_definition.name
return type_.__name__
return "\n\n".join(
chain(
sorted(extras.directives),
filter(None, [schema_definition]),
directives,
types_printed,
(
_print_type(
schema.schema_converter.from_type(type_), schema, extras=extras
)
# Make sure extra types are ordered for predictive printing
for type_ in sorted(extras.types, key=_name_getter)
),
)
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/printer/printer.py | printer.py |
from .printer import print_schema
__all__ = ["print_schema"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/printer/__init__.py | __init__.py |
from __future__ import annotations
from asyncio import ensure_future
from inspect import isawaitable
from typing import (
TYPE_CHECKING,
Awaitable,
Callable,
Iterable,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
cast,
)
from graphql import GraphQLError, parse
from graphql import execute as original_execute
from graphql.validation import validate
from strawberry.exceptions import MissingQueryError
from strawberry.extensions.runner import SchemaExtensionsRunner
from strawberry.types import ExecutionResult
from .exceptions import InvalidOperationTypeError
if TYPE_CHECKING:
from graphql import ExecutionContext as GraphQLExecutionContext
from graphql import ExecutionResult as GraphQLExecutionResult
from graphql import GraphQLSchema
from graphql.language import DocumentNode
from graphql.validation import ASTValidationRule
from strawberry.extensions import SchemaExtension
from strawberry.types import ExecutionContext
from strawberry.types.graphql import OperationType
def parse_document(query: str) -> DocumentNode:
return parse(query)
def validate_document(
schema: GraphQLSchema,
document: DocumentNode,
validation_rules: Tuple[Type[ASTValidationRule], ...],
) -> List[GraphQLError]:
return validate(
schema,
document,
validation_rules,
)
def _run_validation(execution_context: ExecutionContext) -> None:
# Check if there are any validation rules or if validation has
# already been run by an extension
if len(execution_context.validation_rules) > 0 and execution_context.errors is None:
assert execution_context.graphql_document
execution_context.errors = validate_document(
execution_context.schema._schema,
execution_context.graphql_document,
execution_context.validation_rules,
)
async def execute(
schema: GraphQLSchema,
*,
allowed_operation_types: Iterable[OperationType],
extensions: Sequence[Union[Type[SchemaExtension], SchemaExtension]],
execution_context: ExecutionContext,
execution_context_class: Optional[Type[GraphQLExecutionContext]] = None,
process_errors: Callable[[List[GraphQLError], Optional[ExecutionContext]], None],
) -> ExecutionResult:
extensions_runner = SchemaExtensionsRunner(
execution_context=execution_context,
extensions=list(extensions),
)
async with extensions_runner.operation():
# Note: In graphql-core the schema would be validated here but in
# Strawberry we are validating it at initialisation time instead
if not execution_context.query:
raise MissingQueryError()
async with extensions_runner.parsing():
try:
if not execution_context.graphql_document:
execution_context.graphql_document = parse_document(
execution_context.query
)
except GraphQLError as error:
execution_context.errors = [error]
process_errors([error], execution_context)
return ExecutionResult(
data=None,
errors=[error],
extensions=await extensions_runner.get_extensions_results(),
)
except Exception as error: # pragma: no cover
error = GraphQLError(str(error), original_error=error)
execution_context.errors = [error]
process_errors([error], execution_context)
return ExecutionResult(
data=None,
errors=[error],
extensions=await extensions_runner.get_extensions_results(),
)
if execution_context.operation_type not in allowed_operation_types:
raise InvalidOperationTypeError(execution_context.operation_type)
async with extensions_runner.validation():
_run_validation(execution_context)
if execution_context.errors:
process_errors(execution_context.errors, execution_context)
return ExecutionResult(data=None, errors=execution_context.errors)
async with extensions_runner.executing():
if not execution_context.result:
result = original_execute(
schema,
execution_context.graphql_document,
root_value=execution_context.root_value,
middleware=extensions_runner.as_middleware_manager(),
variable_values=execution_context.variables,
operation_name=execution_context.operation_name,
context_value=execution_context.context,
execution_context_class=execution_context_class,
)
if isawaitable(result):
result = await cast(Awaitable["GraphQLExecutionResult"], result)
result = cast("GraphQLExecutionResult", result)
execution_context.result = result
# Also set errors on the execution_context so that it's easier
# to access in extensions
if result.errors:
execution_context.errors = result.errors
# Run the `Schema.process_errors` function here before
# extensions have a chance to modify them (see the MaskErrors
# extension). That way we can log the original errors but
# only return a sanitised version to the client.
process_errors(result.errors, execution_context)
return ExecutionResult(
data=execution_context.result.data,
errors=execution_context.result.errors,
extensions=await extensions_runner.get_extensions_results(),
)
def execute_sync(
schema: GraphQLSchema,
*,
allowed_operation_types: Iterable[OperationType],
extensions: Sequence[Union[Type[SchemaExtension], SchemaExtension]],
execution_context: ExecutionContext,
execution_context_class: Optional[Type[GraphQLExecutionContext]] = None,
process_errors: Callable[[List[GraphQLError], Optional[ExecutionContext]], None],
) -> ExecutionResult:
extensions_runner = SchemaExtensionsRunner(
execution_context=execution_context,
extensions=list(extensions),
)
with extensions_runner.operation():
# Note: In graphql-core the schema would be validated here but in
# Strawberry we are validating it at initialisation time instead
if not execution_context.query:
raise MissingQueryError()
with extensions_runner.parsing():
try:
if not execution_context.graphql_document:
execution_context.graphql_document = parse_document(
execution_context.query
)
except GraphQLError as error:
execution_context.errors = [error]
process_errors([error], execution_context)
return ExecutionResult(
data=None,
errors=[error],
extensions=extensions_runner.get_extensions_results_sync(),
)
except Exception as error: # pragma: no cover
error = GraphQLError(str(error), original_error=error)
execution_context.errors = [error]
process_errors([error], execution_context)
return ExecutionResult(
data=None,
errors=[error],
extensions=extensions_runner.get_extensions_results_sync(),
)
if execution_context.operation_type not in allowed_operation_types:
raise InvalidOperationTypeError(execution_context.operation_type)
with extensions_runner.validation():
_run_validation(execution_context)
if execution_context.errors:
process_errors(execution_context.errors, execution_context)
return ExecutionResult(data=None, errors=execution_context.errors)
with extensions_runner.executing():
if not execution_context.result:
result = original_execute(
schema,
execution_context.graphql_document,
root_value=execution_context.root_value,
middleware=extensions_runner.as_middleware_manager(),
variable_values=execution_context.variables,
operation_name=execution_context.operation_name,
context_value=execution_context.context,
execution_context_class=execution_context_class,
)
if isawaitable(result):
result = cast(Awaitable["GraphQLExecutionResult"], result)
ensure_future(result).cancel()
raise RuntimeError(
"GraphQL execution failed to complete synchronously."
)
result = cast("GraphQLExecutionResult", result)
execution_context.result = result
# Also set errors on the execution_context so that it's easier
# to access in extensions
if result.errors:
execution_context.errors = result.errors
# Run the `Schema.process_errors` function here before
# extensions have a chance to modify them (see the MaskErrors
# extension). That way we can log the original errors but
# only return a sanitised version to the client.
process_errors(result.errors, execution_context)
return ExecutionResult(
data=execution_context.result.data,
errors=execution_context.result.errors,
extensions=extensions_runner.get_extensions_results_sync(),
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/execute.py | execute.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Union
from strawberry.scalars import is_scalar as is_strawberry_scalar
from strawberry.type import StrawberryType
# TypeGuard is only available in typing_extensions => 3.10, we don't want
# to force updates to the typing_extensions package so we only use it when
# TYPE_CHECKING is enabled.
if TYPE_CHECKING:
from typing_extensions import TypeGuard
from strawberry.custom_scalar import ScalarDefinition, ScalarWrapper
from strawberry.types.types import TypeDefinition
def is_input_type(type_: Union[StrawberryType, type]) -> TypeGuard[type]:
if not is_object_type(type_):
return False
type_definition: TypeDefinition = type_._type_definition # type: ignore
return type_definition.is_input
def is_interface_type(type_: Union[StrawberryType, type]) -> TypeGuard[type]:
if not is_object_type(type_):
return False
type_definition: TypeDefinition = type_._type_definition # type: ignore
return type_definition.is_interface
def is_scalar(
type_: Union[StrawberryType, type],
scalar_registry: Dict[object, Union[ScalarWrapper, ScalarDefinition]],
) -> TypeGuard[type]:
return is_strawberry_scalar(type_, scalar_registry)
def is_object_type(type_: Union[StrawberryType, type]) -> TypeGuard[type]:
return hasattr(type_, "_type_definition")
def is_enum(type_: Union[StrawberryType, type]) -> TypeGuard[type]:
return hasattr(type_, "_enum_definition")
def is_schema_directive(type_: Union[StrawberryType, type]) -> TypeGuard[type]:
return hasattr(type_, "__strawberry_directive__")
def is_generic(type_: Union[StrawberryType, type]) -> bool:
if hasattr(type_, "_type_definition"):
type_definition: TypeDefinition = type_._type_definition
return type_definition.is_generic
if isinstance(type_, StrawberryType):
return type_.is_generic
return False
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/compat.py | compat.py |
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional, Union, cast
from typing_extensions import Protocol
from strawberry.custom_scalar import ScalarDefinition
from strawberry.directive import StrawberryDirective
from strawberry.enum import EnumDefinition
from strawberry.lazy_type import LazyType
from strawberry.schema_directive import StrawberrySchemaDirective
from strawberry.type import StrawberryList, StrawberryOptional
from strawberry.types.types import TypeDefinition
from strawberry.union import StrawberryUnion
from strawberry.utils.str_converters import capitalize_first, to_camel_case
from strawberry.utils.typing import eval_type
if TYPE_CHECKING:
from strawberry.arguments import StrawberryArgument
from strawberry.field import StrawberryField
from strawberry.type import StrawberryType
class HasGraphQLName(Protocol):
python_name: str
graphql_name: Optional[str]
class NameConverter:
def __init__(self, auto_camel_case: bool = True) -> None:
self.auto_camel_case = auto_camel_case
def apply_naming_config(self, name: str) -> str:
if self.auto_camel_case:
name = to_camel_case(name)
return name
def from_type(
self,
type_: Union[StrawberryType, StrawberryDirective, StrawberryDirective],
) -> str:
if isinstance(type_, (StrawberryDirective, StrawberrySchemaDirective)):
return self.from_directive(type_)
if isinstance(type_, EnumDefinition): # TODO: Replace with StrawberryEnum
return self.from_enum(type_)
elif isinstance(type_, TypeDefinition):
if type_.is_input:
return self.from_input_object(type_)
if type_.is_interface:
return self.from_interface(type_)
return self.from_object(type_)
elif isinstance(type_, StrawberryUnion):
return self.from_union(type_)
elif isinstance(type_, ScalarDefinition): # TODO: Replace with StrawberryScalar
return self.from_scalar(type_)
else:
return str(type_)
def from_argument(self, argument: StrawberryArgument) -> str:
return self.get_graphql_name(argument)
def from_object(self, object_type: TypeDefinition) -> str:
if object_type.concrete_of:
return self.from_generic(
object_type, list(object_type.type_var_map.values())
)
return object_type.name
def from_input_object(self, input_type: TypeDefinition) -> str:
return self.from_object(input_type)
def from_interface(self, interface: TypeDefinition) -> str:
return self.from_object(interface)
def from_enum(self, enum: EnumDefinition) -> str:
return enum.name
def from_directive(
self, directive: Union[StrawberryDirective, StrawberrySchemaDirective]
) -> str:
name = self.get_graphql_name(directive)
if self.auto_camel_case:
# we don't want the first letter to be uppercase for directives
return name[0].lower() + name[1:]
return name
def from_scalar(self, scalar: ScalarDefinition) -> str:
return scalar.name
def from_field(self, field: StrawberryField) -> str:
return self.get_graphql_name(field)
def from_union(self, union: StrawberryUnion) -> str:
if union.graphql_name is not None:
return union.graphql_name
name = ""
for type_ in union.types:
if isinstance(type_, LazyType):
type_ = cast("StrawberryType", type_.resolve_type()) # noqa: PLW2901
if hasattr(type_, "_type_definition"):
type_name = self.from_type(type_._type_definition)
else:
# This should only be hit when generating names for type-related
# exceptions
type_name = self.from_type(type_)
name += type_name
return name
def from_generic(
self, generic_type: TypeDefinition, types: List[Union[StrawberryType, type]]
) -> str:
generic_type_name = generic_type.name
names: List[str] = []
for type_ in types:
name = self.get_from_type(type_)
names.append(name)
return "".join(names) + generic_type_name
def get_from_type(self, type_: Union[StrawberryType, type]) -> str:
type_ = eval_type(type_)
if isinstance(type_, LazyType):
name = type_.type_name
elif isinstance(type_, EnumDefinition):
name = type_.name
elif isinstance(type_, StrawberryUnion):
# TODO: test Generics with unnamed unions
assert type_.graphql_name
name = type_.graphql_name
elif isinstance(type_, StrawberryList):
name = self.get_from_type(type_.of_type) + "List"
elif isinstance(type_, StrawberryOptional):
name = self.get_from_type(type_.of_type) + "Optional"
elif hasattr(type_, "_scalar_definition"):
strawberry_type = type_._scalar_definition
name = strawberry_type.name
elif hasattr(type_, "_type_definition"):
strawberry_type = type_._type_definition
if (
strawberry_type.is_generic
and not strawberry_type.is_specialized_generic
):
types = type_.__args__
name = self.from_generic(strawberry_type, types)
elif (
strawberry_type.concrete_of
and not strawberry_type.is_specialized_generic
):
types = list(strawberry_type.type_var_map.values())
name = self.from_generic(strawberry_type, types)
else:
name = strawberry_type.name
else:
name = type_.__name__
return capitalize_first(name)
def get_graphql_name(self, obj: HasGraphQLName) -> str:
if obj.graphql_name is not None:
return obj.graphql_name
assert obj.python_name
return self.apply_naming_config(obj.python_name)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/name_converter.py | name_converter.py |
from __future__ import annotations
from dataclasses import InitVar, dataclass, field
from typing import Any, Callable
from .name_converter import NameConverter
@dataclass
class StrawberryConfig:
auto_camel_case: InitVar[bool] = None # pyright: reportGeneralTypeIssues=false
name_converter: NameConverter = field(default_factory=NameConverter)
default_resolver: Callable[[Any, str], object] = getattr
def __post_init__(
self,
auto_camel_case: bool,
):
if auto_camel_case is not None:
self.name_converter.auto_camel_case = auto_camel_case
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/config.py | config.py |
from __future__ import annotations
from abc import abstractmethod
from functools import lru_cache
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Type, Union
from typing_extensions import Protocol
from strawberry.utils.logging import StrawberryLogger
if TYPE_CHECKING:
from graphql import GraphQLError
from strawberry.custom_scalar import ScalarDefinition
from strawberry.directive import StrawberryDirective
from strawberry.enum import EnumDefinition
from strawberry.schema.schema_converter import GraphQLCoreConverter
from strawberry.types import ExecutionContext, ExecutionResult
from strawberry.types.graphql import OperationType
from strawberry.types.types import TypeDefinition
from strawberry.union import StrawberryUnion
from .config import StrawberryConfig
class BaseSchema(Protocol):
config: StrawberryConfig
schema_converter: GraphQLCoreConverter
query: Type
mutation: Optional[Type]
subscription: Optional[Type]
schema_directives: List[object]
@abstractmethod
async def execute(
self,
query: Optional[str],
variable_values: Optional[Dict[str, Any]] = None,
context_value: Optional[Any] = None,
root_value: Optional[Any] = None,
operation_name: Optional[str] = None,
allowed_operation_types: Optional[Iterable[OperationType]] = None,
) -> ExecutionResult:
raise NotImplementedError
@abstractmethod
def execute_sync(
self,
query: Optional[str],
variable_values: Optional[Dict[str, Any]] = None,
context_value: Optional[Any] = None,
root_value: Optional[Any] = None,
operation_name: Optional[str] = None,
allowed_operation_types: Optional[Iterable[OperationType]] = None,
) -> ExecutionResult:
raise NotImplementedError
@abstractmethod
async def subscribe(
self,
query: str,
variable_values: Optional[Dict[str, Any]] = None,
context_value: Optional[Any] = None,
root_value: Optional[Any] = None,
operation_name: Optional[str] = None,
) -> Any:
raise NotImplementedError
@abstractmethod
def get_type_by_name(
self, name: str
) -> Optional[
Union[TypeDefinition, ScalarDefinition, EnumDefinition, StrawberryUnion]
]:
raise NotImplementedError
@abstractmethod
@lru_cache()
def get_directive_by_name(self, graphql_name: str) -> Optional[StrawberryDirective]:
raise NotImplementedError
@abstractmethod
def as_str(self) -> str:
raise NotImplementedError
def process_errors(
self,
errors: List[GraphQLError],
execution_context: Optional[ExecutionContext] = None,
) -> None:
for error in errors:
StrawberryLogger.error(error, execution_context)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/base.py | base.py |
from __future__ import annotations
import warnings
from functools import lru_cache
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Dict,
Iterable,
List,
Optional,
Type,
Union,
cast,
)
from graphql import (
GraphQLNamedType,
GraphQLNonNull,
GraphQLSchema,
get_introspection_query,
parse,
validate_schema,
)
from graphql.subscription import subscribe
from graphql.type.directives import specified_directives
from strawberry.annotation import StrawberryAnnotation
from strawberry.extensions.directives import (
DirectivesExtension,
DirectivesExtensionSync,
)
from strawberry.schema.schema_converter import GraphQLCoreConverter
from strawberry.schema.types.scalar import DEFAULT_SCALAR_REGISTRY
from strawberry.types import ExecutionContext
from strawberry.types.graphql import OperationType
from strawberry.types.types import TypeDefinition
from ..printer import print_schema
from . import compat
from .base import BaseSchema
from .config import StrawberryConfig
from .execute import execute, execute_sync
if TYPE_CHECKING:
from graphql import ExecutionContext as GraphQLExecutionContext
from graphql import ExecutionResult as GraphQLExecutionResult
from strawberry.custom_scalar import ScalarDefinition, ScalarWrapper
from strawberry.directive import StrawberryDirective
from strawberry.enum import EnumDefinition
from strawberry.extensions import SchemaExtension
from strawberry.field import StrawberryField
from strawberry.types import ExecutionResult
from strawberry.union import StrawberryUnion
DEFAULT_ALLOWED_OPERATION_TYPES = {
OperationType.QUERY,
OperationType.MUTATION,
OperationType.SUBSCRIPTION,
}
class Schema(BaseSchema):
def __init__(
self,
# TODO: can we make sure we only allow to pass
# something that has been decorated?
query: Type,
mutation: Optional[Type] = None,
subscription: Optional[Type] = None,
directives: Iterable[StrawberryDirective] = (),
types=(),
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] = (),
):
self.query = query
self.mutation = mutation
self.subscription = subscription
self.extensions = extensions
self.execution_context_class = execution_context_class
self.config = config or StrawberryConfig()
SCALAR_OVERRIDES_DICT_TYPE = Dict[
object, Union["ScalarWrapper", "ScalarDefinition"]
]
scalar_registry: SCALAR_OVERRIDES_DICT_TYPE = {**DEFAULT_SCALAR_REGISTRY}
if scalar_overrides:
# TODO: check that the overrides are valid
scalar_registry.update(cast(SCALAR_OVERRIDES_DICT_TYPE, scalar_overrides))
self.schema_converter = GraphQLCoreConverter(self.config, scalar_registry)
self.directives = directives
self.schema_directives = list(schema_directives)
query_type = self.schema_converter.from_object(query._type_definition)
mutation_type = (
self.schema_converter.from_object(mutation._type_definition)
if mutation
else None
)
subscription_type = (
self.schema_converter.from_object(subscription._type_definition)
if subscription
else None
)
graphql_directives = [
self.schema_converter.from_directive(directive) for directive in directives
]
graphql_types = []
for type_ in types:
if compat.is_schema_directive(type_):
graphql_directives.append(
self.schema_converter.from_schema_directive(type_)
)
else:
if hasattr(type_, "_type_definition"):
if type_._type_definition.is_generic:
type_ = StrawberryAnnotation(type_).resolve() # noqa: PLW2901
graphql_type = self.schema_converter.from_maybe_optional(type_)
if isinstance(graphql_type, GraphQLNonNull):
graphql_type = graphql_type.of_type
if not isinstance(graphql_type, GraphQLNamedType):
raise TypeError(f"{graphql_type} is not a named GraphQL Type")
graphql_types.append(graphql_type)
try:
self._schema = GraphQLSchema(
query=query_type,
mutation=mutation_type,
subscription=subscription_type if subscription else None,
directives=specified_directives + tuple(graphql_directives),
types=graphql_types,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: self,
},
)
except TypeError as error:
# GraphQL core throws a TypeError if there's any exception raised
# during the schema creation, so we check if the cause was a
# StrawberryError and raise it instead if that's the case.
from strawberry.exceptions import StrawberryException
if isinstance(error.__cause__, StrawberryException):
raise error.__cause__ from None
raise
# attach our schema to the GraphQL schema instance
self._schema._strawberry_schema = self # type: ignore
self._warn_for_federation_directives()
# Validate schema early because we want developers to know about
# possible issues as soon as possible
errors = validate_schema(self._schema)
if errors:
formatted_errors = "\n\n".join(f"❌ {error.message}" for error in errors)
raise ValueError(f"Invalid Schema. Errors:\n\n{formatted_errors}")
def get_extensions(
self, sync: bool = False
) -> List[Union[Type[SchemaExtension], SchemaExtension]]:
extensions = list(self.extensions)
if self.directives:
extensions.append(DirectivesExtensionSync if sync else DirectivesExtension)
return extensions
@lru_cache()
def get_type_by_name(
self, name: str
) -> Optional[
Union[TypeDefinition, ScalarDefinition, EnumDefinition, StrawberryUnion]
]:
# TODO: respect auto_camel_case
if name in self.schema_converter.type_map:
return self.schema_converter.type_map[name].definition
return None
def get_field_for_type(
self, field_name: str, type_name: str
) -> Optional[StrawberryField]:
type_ = self.get_type_by_name(type_name)
if not type_:
return None # pragma: no cover
assert isinstance(type_, TypeDefinition)
return next(
(
field
for field in type_.fields
if self.config.name_converter.get_graphql_name(field) == field_name
),
None,
)
@lru_cache()
def get_directive_by_name(self, graphql_name: str) -> Optional[StrawberryDirective]:
return next(
(
directive
for directive in self.directives
if self.config.name_converter.from_directive(directive) == graphql_name
),
None,
)
async def execute(
self,
query: Optional[str],
variable_values: Optional[Dict[str, Any]] = None,
context_value: Optional[Any] = None,
root_value: Optional[Any] = None,
operation_name: Optional[str] = None,
allowed_operation_types: Optional[Iterable[OperationType]] = None,
) -> ExecutionResult:
if allowed_operation_types is None:
allowed_operation_types = DEFAULT_ALLOWED_OPERATION_TYPES
# Create execution context
execution_context = ExecutionContext(
query=query,
schema=self,
context=context_value,
root_value=root_value,
variables=variable_values,
provided_operation_name=operation_name,
)
result = await execute(
self._schema,
extensions=self.get_extensions(),
execution_context_class=self.execution_context_class,
execution_context=execution_context,
allowed_operation_types=allowed_operation_types,
process_errors=self.process_errors,
)
return result
def execute_sync(
self,
query: Optional[str],
variable_values: Optional[Dict[str, Any]] = None,
context_value: Optional[Any] = None,
root_value: Optional[Any] = None,
operation_name: Optional[str] = None,
allowed_operation_types: Optional[Iterable[OperationType]] = None,
) -> ExecutionResult:
if allowed_operation_types is None:
allowed_operation_types = DEFAULT_ALLOWED_OPERATION_TYPES
execution_context = ExecutionContext(
query=query,
schema=self,
context=context_value,
root_value=root_value,
variables=variable_values,
provided_operation_name=operation_name,
)
result = execute_sync(
self._schema,
extensions=self.get_extensions(sync=True),
execution_context_class=self.execution_context_class,
execution_context=execution_context,
allowed_operation_types=allowed_operation_types,
process_errors=self.process_errors,
)
return result
async def subscribe(
self,
# TODO: make this optional when we support extensions
query: str,
variable_values: Optional[Dict[str, Any]] = None,
context_value: Optional[Any] = None,
root_value: Optional[Any] = None,
operation_name: Optional[str] = None,
) -> Union[AsyncIterator[GraphQLExecutionResult], GraphQLExecutionResult]:
return await subscribe(
self._schema,
parse(query),
root_value=root_value,
context_value=context_value,
variable_values=variable_values,
operation_name=operation_name,
)
def _warn_for_federation_directives(self):
"""Raises a warning if the schema has any federation directives."""
from strawberry.federation.schema_directives import FederationDirective
all_types = self.schema_converter.type_map.values()
all_type_defs = (type_.definition for type_ in all_types)
all_directives = (
directive
for type_def in all_type_defs
for directive in (type_def.directives or [])
)
if any(
isinstance(directive, FederationDirective) for directive in all_directives
):
warnings.warn(
"Federation directive found in schema. "
"Use `strawberry.federation.Schema` instead of `strawberry.Schema`.",
UserWarning,
stacklevel=3,
)
def as_str(self) -> str:
return print_schema(self)
__str__ = as_str
def introspect(self) -> Dict[str, Any]:
"""Return the introspection query result for the current schema
Raises:
ValueError: If the introspection query fails due to an invalid schema
"""
introspection = self.execute_sync(get_introspection_query())
if introspection.errors or not introspection.data:
raise ValueError(f"Invalid Schema. Errors {introspection.errors!r}")
return introspection.data
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/schema.py | schema.py |
from __future__ import annotations
import dataclasses
import sys
from functools import partial, reduce
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from graphql import (
GraphQLArgument,
GraphQLDirective,
GraphQLEnumType,
GraphQLEnumValue,
GraphQLField,
GraphQLInputField,
GraphQLInputObjectType,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLUnionType,
Undefined,
)
from graphql.language.directive_locations import DirectiveLocation
from strawberry.annotation import StrawberryAnnotation
from strawberry.arguments import StrawberryArgument, convert_arguments
from strawberry.custom_scalar import ScalarWrapper
from strawberry.enum import EnumDefinition
from strawberry.exceptions import (
DuplicatedTypeName,
InvalidTypeInputForUnion,
InvalidUnionTypeError,
MissingTypesForGenericError,
ScalarAlreadyRegisteredError,
UnresolvedFieldTypeError,
)
from strawberry.field import UNRESOLVED
from strawberry.lazy_type import LazyType
from strawberry.private import is_private
from strawberry.schema.types.scalar import _make_scalar_type
from strawberry.type import StrawberryList, StrawberryOptional
from strawberry.types.info import Info
from strawberry.types.types import TypeDefinition
from strawberry.union import StrawberryUnion
from strawberry.unset import UNSET
from strawberry.utils.await_maybe import await_maybe
from ..extensions.field_extension import build_field_extension_resolvers
from . import compat
from .types.concrete_type import ConcreteType
if TYPE_CHECKING:
from graphql import (
GraphQLInputType,
GraphQLNullableType,
GraphQLOutputType,
GraphQLResolveInfo,
GraphQLScalarType,
ValueNode,
)
from strawberry.custom_scalar import ScalarDefinition
from strawberry.directive import StrawberryDirective
from strawberry.enum import EnumValue
from strawberry.field import StrawberryField
from strawberry.schema.config import StrawberryConfig
from strawberry.schema_directive import StrawberrySchemaDirective
from strawberry.type import StrawberryType
# graphql-core expects a resolver for an Enum type to return
# the enum's *value* (not its name or an instance of the enum). We have to
# subclass the GraphQLEnumType class to enable returning Enum members from
# resolvers.
class CustomGraphQLEnumType(GraphQLEnumType):
def __init__(self, enum: EnumDefinition, *args, **kwargs):
super().__init__(*args, **kwargs)
self.wrapped_cls = enum.wrapped_cls
def serialize(self, output_value: Any) -> str:
if isinstance(output_value, self.wrapped_cls):
return output_value.name
return super().serialize(output_value)
def parse_value(self, input_value: str) -> Any:
return self.wrapped_cls(super().parse_value(input_value))
def parse_literal(
self, value_node: ValueNode, _variables: Optional[Dict[str, Any]] = None
) -> Any:
return self.wrapped_cls(super().parse_literal(value_node, _variables))
class GraphQLCoreConverter:
# TODO: Make abstract
# Extension key used to link a GraphQLType back into the Strawberry definition
DEFINITION_BACKREF = "strawberry-definition"
def __init__(
self,
config: StrawberryConfig,
scalar_registry: Dict[object, Union[ScalarWrapper, ScalarDefinition]],
):
self.type_map: Dict[str, ConcreteType] = {}
self.config = config
self.scalar_registry = scalar_registry
def from_argument(self, argument: StrawberryArgument) -> GraphQLArgument:
argument_type = cast(
"GraphQLInputType", self.from_maybe_optional(argument.type)
)
default_value = Undefined if argument.default is UNSET else argument.default
return GraphQLArgument(
type_=argument_type,
default_value=default_value,
description=argument.description,
deprecation_reason=argument.deprecation_reason,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: argument,
},
)
def from_enum(self, enum: EnumDefinition) -> CustomGraphQLEnumType:
enum_name = self.config.name_converter.from_type(enum)
assert enum_name is not None
# Don't reevaluate known types
cached_type = self.type_map.get(enum_name, None)
if cached_type:
self.validate_same_type_definition(enum_name, enum, cached_type)
graphql_enum = cached_type.implementation
assert isinstance(graphql_enum, CustomGraphQLEnumType) # For mypy
return graphql_enum
graphql_enum = CustomGraphQLEnumType(
enum=enum,
name=enum_name,
values={item.name: self.from_enum_value(item) for item in enum.values},
description=enum.description,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: enum,
},
)
self.type_map[enum_name] = ConcreteType(
definition=enum, implementation=graphql_enum
)
return graphql_enum
def from_enum_value(self, enum_value: EnumValue) -> GraphQLEnumValue:
return GraphQLEnumValue(
enum_value.value,
deprecation_reason=enum_value.deprecation_reason,
description=enum_value.description,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: enum_value,
},
)
def from_directive(self, directive: StrawberryDirective) -> GraphQLDirective:
graphql_arguments = {}
for argument in directive.arguments:
argument_name = self.config.name_converter.from_argument(argument)
graphql_arguments[argument_name] = self.from_argument(argument)
directive_name = self.config.name_converter.from_type(directive)
return GraphQLDirective(
name=directive_name,
locations=directive.locations,
args=graphql_arguments,
description=directive.description,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: directive,
},
)
def from_schema_directive(self, cls: Type) -> GraphQLDirective:
strawberry_directive = cast(
"StrawberrySchemaDirective", cls.__strawberry_directive__
)
module = sys.modules[cls.__module__]
args: Dict[str, GraphQLArgument] = {}
for field in strawberry_directive.fields:
default = field.default
if default == dataclasses.MISSING:
default = UNSET
name = self.config.name_converter.get_graphql_name(field)
args[name] = self.from_argument(
StrawberryArgument(
python_name=field.python_name or field.name,
graphql_name=None,
type_annotation=StrawberryAnnotation(
annotation=field.type,
namespace=module.__dict__,
),
default=default,
)
)
return GraphQLDirective(
name=self.config.name_converter.from_directive(strawberry_directive),
locations=[
DirectiveLocation(loc.value) for loc in strawberry_directive.locations
],
args=args,
is_repeatable=strawberry_directive.repeatable,
description=strawberry_directive.description,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: strawberry_directive,
},
)
def from_field(self, field: StrawberryField) -> GraphQLField:
field_type = cast("GraphQLOutputType", self.from_maybe_optional(field.type))
resolver = self.from_resolver(field)
subscribe = None
if field.is_subscription:
subscribe = resolver
resolver = lambda event, *_, **__: event # noqa: E731
graphql_arguments = {}
for argument in field.arguments:
argument_name = self.config.name_converter.from_argument(argument)
graphql_arguments[argument_name] = self.from_argument(argument)
return GraphQLField(
type_=field_type,
args=graphql_arguments,
resolve=resolver,
subscribe=subscribe,
description=field.description,
deprecation_reason=field.deprecation_reason,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: field,
},
)
def from_input_field(self, field: StrawberryField) -> GraphQLInputField:
field_type = cast("GraphQLInputType", self.from_maybe_optional(field.type))
default_value: object
if field.default_value is UNSET or field.default_value is dataclasses.MISSING:
default_value = Undefined
else:
default_value = field.default_value
return GraphQLInputField(
type_=field_type,
default_value=default_value,
description=field.description,
deprecation_reason=field.deprecation_reason,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: field,
},
)
FieldType = TypeVar("FieldType", GraphQLField, GraphQLInputField)
@staticmethod
def _get_thunk_mapping(
type_definition: TypeDefinition,
name_converter: Callable[[StrawberryField], str],
field_converter: Callable[[StrawberryField], FieldType],
) -> Dict[str, FieldType]:
"""Create a GraphQL core `ThunkMapping` mapping of field names to field types.
This method filters out remaining `strawberry.Private` annotated fields that
could not be filtered during the initialization of a `TypeDefinition` due to
postponed type-hint evaluation (PEP-563). Performing this filtering now (at
schema conversion time) ensures that all types to be included in the schema
should have already been resolved.
Raises:
TypeError: If the type of a field in ``fields`` is `UNRESOLVED`
"""
thunk_mapping = {}
for field in type_definition.fields:
if field.type is UNRESOLVED:
raise UnresolvedFieldTypeError(type_definition, field)
if not is_private(field.type):
thunk_mapping[name_converter(field)] = field_converter(field)
return thunk_mapping
def get_graphql_fields(
self, type_definition: TypeDefinition
) -> Dict[str, GraphQLField]:
return self._get_thunk_mapping(
type_definition=type_definition,
name_converter=self.config.name_converter.from_field,
field_converter=self.from_field,
)
def get_graphql_input_fields(
self, type_definition: TypeDefinition
) -> Dict[str, GraphQLInputField]:
return self._get_thunk_mapping(
type_definition=type_definition,
name_converter=self.config.name_converter.from_field,
field_converter=self.from_input_field,
)
def from_input_object(self, object_type: type) -> GraphQLInputObjectType:
type_definition = object_type._type_definition # type: ignore
type_name = self.config.name_converter.from_type(type_definition)
# Don't reevaluate known types
cached_type = self.type_map.get(type_name, None)
if cached_type:
self.validate_same_type_definition(type_name, type_definition, cached_type)
graphql_object_type = self.type_map[type_name].implementation
assert isinstance(graphql_object_type, GraphQLInputObjectType) # For mypy
return graphql_object_type
graphql_object_type = GraphQLInputObjectType(
name=type_name,
fields=lambda: self.get_graphql_input_fields(type_definition),
description=type_definition.description,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: type_definition,
},
)
self.type_map[type_name] = ConcreteType(
definition=type_definition, implementation=graphql_object_type
)
return graphql_object_type
def from_interface(self, interface: TypeDefinition) -> GraphQLInterfaceType:
# TODO: Use StrawberryInterface when it's implemented in another PR
interface_name = self.config.name_converter.from_type(interface)
# Don't reevaluate known types
cached_type = self.type_map.get(interface_name, None)
if cached_type:
self.validate_same_type_definition(interface_name, interface, cached_type)
graphql_interface = cached_type.implementation
assert isinstance(graphql_interface, GraphQLInterfaceType) # For mypy
return graphql_interface
graphql_interface = GraphQLInterfaceType(
name=interface_name,
fields=lambda: self.get_graphql_fields(interface),
interfaces=list(map(self.from_interface, interface.interfaces)),
description=interface.description,
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: interface,
},
)
self.type_map[interface_name] = ConcreteType(
definition=interface, implementation=graphql_interface
)
return graphql_interface
def from_list(self, type_: StrawberryList) -> GraphQLList:
of_type = self.from_maybe_optional(type_.of_type)
return GraphQLList(of_type)
def from_object(self, object_type: TypeDefinition) -> GraphQLObjectType:
# TODO: Use StrawberryObjectType when it's implemented in another PR
object_type_name = self.config.name_converter.from_type(object_type)
# Don't reevaluate known types
cached_type = self.type_map.get(object_type_name, None)
if cached_type:
self.validate_same_type_definition(
object_type_name, object_type, cached_type
)
graphql_object_type = cached_type.implementation
assert isinstance(graphql_object_type, GraphQLObjectType) # For mypy
return graphql_object_type
def _get_is_type_of() -> Optional[Callable[[Any, GraphQLResolveInfo], bool]]:
if object_type.is_type_of:
return object_type.is_type_of
if not object_type.interfaces:
return None
def is_type_of(obj: Any, _info: GraphQLResolveInfo) -> bool:
if object_type.concrete_of and (
hasattr(obj, "_type_definition")
and obj._type_definition.origin is object_type.concrete_of.origin
):
return True
return isinstance(obj, object_type.origin)
return is_type_of
graphql_object_type = GraphQLObjectType(
name=object_type_name,
fields=lambda: self.get_graphql_fields(object_type),
interfaces=list(map(self.from_interface, object_type.interfaces)),
description=object_type.description,
is_type_of=_get_is_type_of(),
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: object_type,
},
)
self.type_map[object_type_name] = ConcreteType(
definition=object_type, implementation=graphql_object_type
)
return graphql_object_type
def from_resolver(
self, field: StrawberryField
) -> Callable: # TODO: Take StrawberryResolver
field.default_resolver = self.config.default_resolver
if field.is_basic_field:
def _get_basic_result(_source: Any, *args, **kwargs):
# Call `get_result` without an info object or any args or
# kwargs because this is a basic field with no resolver.
return field.get_result(_source, info=None, args=[], kwargs={})
_get_basic_result._is_default = True # type: ignore
return _get_basic_result
def _get_arguments(
source: Any,
info: Info,
kwargs: Dict[str, Any],
) -> Tuple[List[Any], Dict[str, Any]]:
kwargs = convert_arguments(
kwargs,
field.arguments,
scalar_registry=self.scalar_registry,
config=self.config,
)
# the following code allows to omit info and root arguments
# by inspecting the original resolver arguments,
# if it asks for self, the source will be passed as first argument
# if it asks for root, the source it will be passed as kwarg
# if it asks for info, the info will be passed as kwarg
args = []
if field.base_resolver:
if field.base_resolver.self_parameter:
args.append(source)
root_parameter = field.base_resolver.root_parameter
if root_parameter:
kwargs[root_parameter.name] = source
info_parameter = field.base_resolver.info_parameter
if info_parameter:
kwargs[info_parameter.name] = info
return args, kwargs
def _check_permissions(source: Any, info: Info, kwargs: Dict[str, Any]):
"""
Checks if the permission should be accepted and
raises an exception if not
"""
for permission_class in field.permission_classes:
permission = permission_class()
if not permission.has_permission(source, info, **kwargs):
message = getattr(permission, "message", None)
raise PermissionError(message)
async def _check_permissions_async(
source: Any, info: Info, kwargs: Dict[str, Any]
):
for permission_class in field.permission_classes:
permission = permission_class()
has_permission: bool
has_permission = await await_maybe(
permission.has_permission(source, info, **kwargs)
)
if not has_permission:
message = getattr(permission, "message", None)
raise PermissionError(message)
def _strawberry_info_from_graphql(info: GraphQLResolveInfo) -> Info:
return Info(
_raw_info=info,
_field=field,
)
def _get_result(_source: Any, info: Info, **kwargs):
field_args, field_kwargs = _get_arguments(
source=_source, info=info, kwargs=kwargs
)
return field.get_result(
_source, info=info, args=field_args, kwargs=field_kwargs
)
def wrap_field_extensions() -> Callable[..., Any]:
"""Wrap the provided field resolver with the middleware."""
if not field.extensions:
return _get_result
for extension in field.extensions:
extension.apply(field)
extension_functions = build_field_extension_resolvers(field)
return reduce(
lambda chained_fns, next_fn: partial(next_fn, chained_fns),
extension_functions,
_get_result,
)
_get_result_with_extensions = wrap_field_extensions()
def _resolver(_source: Any, info: GraphQLResolveInfo, **kwargs):
strawberry_info = _strawberry_info_from_graphql(info)
_check_permissions(_source, strawberry_info, kwargs)
return _get_result_with_extensions(_source, strawberry_info, **kwargs)
async def _async_resolver(_source: Any, info: GraphQLResolveInfo, **kwargs):
strawberry_info = _strawberry_info_from_graphql(info)
await _check_permissions_async(_source, strawberry_info, kwargs)
return await await_maybe(
_get_result_with_extensions(_source, strawberry_info, **kwargs)
)
if field.is_async:
_async_resolver._is_default = not field.base_resolver # type: ignore
return _async_resolver
else:
_resolver._is_default = not field.base_resolver # type: ignore
return _resolver
def from_scalar(self, scalar: Type) -> GraphQLScalarType:
scalar_definition: ScalarDefinition
if scalar in self.scalar_registry:
_scalar_definition = self.scalar_registry[scalar]
# TODO: check why we need the cast and we are not trying with getattr first
if isinstance(_scalar_definition, ScalarWrapper):
scalar_definition = _scalar_definition._scalar_definition
else:
scalar_definition = _scalar_definition
else:
scalar_definition = scalar._scalar_definition
scalar_name = self.config.name_converter.from_type(scalar_definition)
if scalar_name not in self.type_map:
implementation = (
scalar_definition.implementation
if scalar_definition.implementation is not None
else _make_scalar_type(scalar_definition)
)
self.type_map[scalar_name] = ConcreteType(
definition=scalar_definition, implementation=implementation
)
else:
other_definition = self.type_map[scalar_name].definition
# TODO: the other definition might not be a scalar, we should
# handle this case better, since right now we assume it is a scalar
if other_definition != scalar_definition:
other_definition = cast("ScalarDefinition", other_definition)
raise ScalarAlreadyRegisteredError(scalar_definition, other_definition)
implementation = cast(
"GraphQLScalarType", self.type_map[scalar_name].implementation
)
return implementation
def from_maybe_optional(
self, type_: Union[StrawberryType, type]
) -> Union[GraphQLNullableType, GraphQLNonNull]:
NoneType = type(None)
if type_ is None or type_ is NoneType:
return self.from_type(type_)
elif isinstance(type_, StrawberryOptional):
return self.from_type(type_.of_type)
else:
return GraphQLNonNull(self.from_type(type_))
def from_type(self, type_: Union[StrawberryType, type]) -> GraphQLNullableType:
if compat.is_generic(type_):
raise MissingTypesForGenericError(type_)
if isinstance(type_, EnumDefinition): # TODO: Replace with StrawberryEnum
return self.from_enum(type_)
elif compat.is_input_type(type_): # TODO: Replace with StrawberryInputObject
return self.from_input_object(type_)
elif isinstance(type_, StrawberryList):
return self.from_list(type_)
elif compat.is_interface_type(type_): # TODO: Replace with StrawberryInterface
type_definition: TypeDefinition = type_._type_definition # type: ignore
return self.from_interface(type_definition)
elif compat.is_object_type(type_): # TODO: Replace with StrawberryObject
type_definition: TypeDefinition = type_._type_definition # type: ignore
return self.from_object(type_definition)
elif compat.is_enum(type_): # TODO: Replace with StrawberryEnum
enum_definition: EnumDefinition = type_._enum_definition # type: ignore
return self.from_enum(enum_definition)
elif isinstance(type_, TypeDefinition): # TODO: Replace with StrawberryObject
return self.from_object(type_)
elif isinstance(type_, StrawberryUnion):
return self.from_union(type_)
elif isinstance(type_, LazyType):
return self.from_type(type_.resolve_type())
elif compat.is_scalar(
type_, self.scalar_registry
): # TODO: Replace with StrawberryScalar
return self.from_scalar(type_)
raise TypeError(f"Unexpected type '{type_}'")
def from_union(self, union: StrawberryUnion) -> GraphQLUnionType:
union_name = self.config.name_converter.from_type(union)
for type_ in union.types:
# This check also occurs in the Annotation resolving, but because of
# TypeVars, Annotations, LazyTypes, etc it can't perfectly detect issues at
# that stage
if not StrawberryUnion.is_valid_union_type(type_):
raise InvalidUnionTypeError(union_name, type_)
# Don't reevaluate known types
if union_name in self.type_map:
graphql_union = self.type_map[union_name].implementation
assert isinstance(graphql_union, GraphQLUnionType) # For mypy
return graphql_union
graphql_types: List[GraphQLObjectType] = []
for type_ in union.types:
graphql_type = self.from_type(type_)
if isinstance(graphql_type, GraphQLInputObjectType):
raise InvalidTypeInputForUnion(graphql_type)
assert isinstance(graphql_type, GraphQLObjectType)
graphql_types.append(graphql_type)
graphql_union = GraphQLUnionType(
name=union_name,
types=graphql_types,
description=union.description,
resolve_type=union.get_type_resolver(self.type_map),
extensions={
GraphQLCoreConverter.DEFINITION_BACKREF: union,
},
)
self.type_map[union_name] = ConcreteType(
definition=union, implementation=graphql_union
)
return graphql_union
def _get_is_type_of(
self,
object_type: TypeDefinition,
) -> Optional[Callable[[Any, GraphQLResolveInfo], bool]]:
if object_type.is_type_of:
return object_type.is_type_of
if object_type.interfaces:
def is_type_of(obj: Any, _info: GraphQLResolveInfo) -> bool:
if object_type.concrete_of and (
hasattr(obj, "_type_definition")
and obj._type_definition.origin is object_type.concrete_of.origin
):
return True
return isinstance(obj, object_type.origin)
return is_type_of
return None
def validate_same_type_definition(
self, name: str, type_definition: StrawberryType, cached_type: ConcreteType
) -> None:
# if the type definitions are the same we can return
if cached_type.definition == type_definition:
return
# otherwise we need to check if we are dealing with different instances
# of the same type generic type. This happens when using the same generic
# type in different places in the schema, like in the following example:
# >>> @strawberry.type
# >>> class A(Generic[T]):
# >>> a: T
# >>> @strawberry.type
# >>> class Query:
# >>> first: A[int]
# >>> second: A[int]
# in theory we won't ever have duplicated definitions for the same generic,
# but we are doing the check in an exhaustive way just in case we missed
# something.
# we only do this check for TypeDefinitions, as they are the only ones
# that can be generic.
# of they are of the same generic type, we need to check if the type
# var map is the same, in that case we can return
if (
isinstance(type_definition, TypeDefinition)
and isinstance(cached_type.definition, TypeDefinition)
and cached_type.definition.concrete_of is not None
and cached_type.definition.concrete_of == type_definition.concrete_of
and (
cached_type.definition.type_var_map.keys()
== type_definition.type_var_map.keys()
)
):
# manually compare type_var_maps while resolving any lazy types
# so that they're considered equal to the actual types they're referencing
equal = True
lazy_types = False
for type_var, type1 in cached_type.definition.type_var_map.items():
type2 = type_definition.type_var_map[type_var]
# both lazy types are always resolved because two different lazy types
# may be referencing the same actual type
if isinstance(type1, LazyType):
type1 = type1.resolve_type() # noqa: PLW2901
lazy_types = True
elif isinstance(type1, StrawberryOptional) and isinstance(
type1.of_type, LazyType
):
lazy_types = True
type1.of_type = type1.of_type.resolve_type()
if isinstance(type2, LazyType):
type2 = type2.resolve_type()
lazy_types = True
elif isinstance(type2, StrawberryOptional) and isinstance(
type2.of_type, LazyType
):
type2.of_type = type2.of_type.resolve_type()
lazy_types = True
if lazy_types and type1 != type2:
equal = False
break
if equal:
return
if isinstance(type_definition, TypeDefinition):
first_origin = type_definition.origin
elif isinstance(type_definition, EnumDefinition):
first_origin = type_definition.wrapped_cls
else:
first_origin = None
if isinstance(cached_type.definition, TypeDefinition):
second_origin = cached_type.definition.origin
elif isinstance(cached_type.definition, EnumDefinition):
second_origin = cached_type.definition.wrapped_cls
else:
second_origin = None
raise DuplicatedTypeName(first_origin, second_origin, name)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/schema_converter.py | schema_converter.py |
from .base import BaseSchema
from .schema import Schema
__all__ = ["BaseSchema", "Schema"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/__init__.py | __init__.py |
from strawberry.types.graphql import OperationType
class InvalidOperationTypeError(Exception):
def __init__(self, operation_type: OperationType):
self.operation_type = operation_type
def as_http_error_reason(self, method: str) -> str:
operation_type = {
OperationType.QUERY: "queries",
OperationType.MUTATION: "mutations",
OperationType.SUBSCRIPTION: "subscriptions",
}[self.operation_type]
return f"{operation_type} are not allowed when using {method}"
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/exceptions.py | exceptions.py |
import datetime
import decimal
from typing import Dict
from uuid import UUID
from graphql import (
GraphQLBoolean,
GraphQLFloat,
GraphQLID,
GraphQLInt,
GraphQLScalarType,
GraphQLString,
)
from strawberry.custom_scalar import ScalarDefinition
from strawberry.file_uploads.scalars import Upload
from strawberry.scalars import ID
from strawberry.schema.types import base_scalars
def _make_scalar_type(definition: ScalarDefinition) -> GraphQLScalarType:
from strawberry.schema.schema_converter import GraphQLCoreConverter
return GraphQLScalarType(
name=definition.name,
description=definition.description,
specified_by_url=definition.specified_by_url,
serialize=definition.serialize,
parse_value=definition.parse_value,
parse_literal=definition.parse_literal,
extensions={GraphQLCoreConverter.DEFINITION_BACKREF: definition},
)
def _make_scalar_definition(scalar_type: GraphQLScalarType) -> ScalarDefinition:
return ScalarDefinition(
name=scalar_type.name,
description=scalar_type.name,
specified_by_url=scalar_type.specified_by_url,
serialize=scalar_type.serialize,
parse_literal=scalar_type.parse_literal,
parse_value=scalar_type.parse_value,
implementation=scalar_type,
)
def _get_scalar_definition(scalar) -> ScalarDefinition:
return scalar._scalar_definition
DEFAULT_SCALAR_REGISTRY: Dict[object, ScalarDefinition] = {
type(None): _get_scalar_definition(base_scalars.Void),
None: _get_scalar_definition(base_scalars.Void),
str: _make_scalar_definition(GraphQLString),
int: _make_scalar_definition(GraphQLInt),
float: _make_scalar_definition(GraphQLFloat),
bool: _make_scalar_definition(GraphQLBoolean),
ID: _make_scalar_definition(GraphQLID),
UUID: _get_scalar_definition(base_scalars.UUID),
Upload: _get_scalar_definition(Upload),
datetime.date: _get_scalar_definition(base_scalars.Date),
datetime.datetime: _get_scalar_definition(base_scalars.DateTime),
datetime.time: _get_scalar_definition(base_scalars.Time),
decimal.Decimal: _get_scalar_definition(base_scalars.Decimal),
}
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/types/scalar.py | scalar.py |
import datetime
import decimal
import uuid
from operator import methodcaller
from typing import Callable
import dateutil.parser
from graphql import GraphQLError
from strawberry.custom_scalar import scalar
def wrap_parser(parser: Callable, type_: str) -> Callable:
def inner(value: str):
try:
return parser(value)
except ValueError as e:
raise GraphQLError(f'Value cannot represent a {type_}: "{value}". {e}')
return inner
def parse_decimal(value: object) -> decimal.Decimal:
try:
return decimal.Decimal(str(value))
except decimal.DecimalException:
raise GraphQLError(f'Value cannot represent a Decimal: "{value}".')
isoformat = methodcaller("isoformat")
Date = scalar(
datetime.date,
name="Date",
description="Date (isoformat)",
serialize=isoformat,
parse_value=wrap_parser(datetime.date.fromisoformat, "Date"),
)
DateTime = scalar(
datetime.datetime,
name="DateTime",
description="Date with time (isoformat)",
serialize=isoformat,
parse_value=wrap_parser(dateutil.parser.isoparse, "DateTime"),
)
Time = scalar(
datetime.time,
name="Time",
description="Time (isoformat)",
serialize=isoformat,
parse_value=wrap_parser(datetime.time.fromisoformat, "Time"),
)
Decimal = scalar(
decimal.Decimal,
name="Decimal",
description="Decimal (fixed-point)",
serialize=str,
parse_value=parse_decimal,
)
UUID = scalar(
uuid.UUID,
name="UUID",
serialize=str,
parse_value=wrap_parser(uuid.UUID, "UUID"),
)
def _verify_void(x) -> None:
if x is not None:
raise ValueError(f"Expected 'None', got '{x}'")
Void = scalar(
type(None),
name="Void",
serialize=_verify_void,
parse_value=_verify_void,
description="Represents NULL values",
)
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/types/base_scalars.py | base_scalars.py |
from .concrete_type import ConcreteType
__all__ = ["ConcreteType"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/types/__init__.py | __init__.py |
from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING, Dict, Union
from graphql import GraphQLField, GraphQLInputField, GraphQLType
if TYPE_CHECKING:
from strawberry.custom_scalar import ScalarDefinition
from strawberry.enum import EnumDefinition
from strawberry.types.types import TypeDefinition
from strawberry.union import StrawberryUnion
Field = Union[GraphQLInputField, GraphQLField]
@dataclasses.dataclass
class ConcreteType:
definition: Union[TypeDefinition, EnumDefinition, ScalarDefinition, StrawberryUnion]
implementation: GraphQLType
TypeMap = Dict[str, ConcreteType]
__all__ = ["ConcreteType", "Field", "GraphQLType", "TypeMap"]
| 564bff00ff-strawberry-graphql | /564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema/types/concrete_type.py | concrete_type.py |
# Pychess
[![Status][status badge]][status badge]
[![Tests][github actions badge]][github actions page]
[![Codecov][codecov badge]][codecov page]
[![Python Version][python version badge]][github page]
[![License][license badge]][license]
[code of conduct]: https://github.com/56kyle/pychess/blob/master/CODE_OF_CONDUCT.md
[codecov badge]: https://codecov.io/gh/56kyle/pychess/branch/master/graph/badge.svg?token=0QDENTNTN7
[codecov page]: https://app.codecov.io/gh/56kyle/pychess/branch/master
[contributor covenant badge]: https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg
[github actions badge]: https://github.com/56kyle/pychess/workflows/Tests/badge.svg
[github actions page]: https://github.com/56kyle/pychess/actions?workflow=Tests
[github page]: https://github.com/56kyle/pychess
[license badge]: https://img.shields.io/github/license/56kyle/pychess
[license]: https://opensource.org/licenses/MIT
[python version badge]: https://img.shields.io/pypi/pyversions/56kyle-pychess
[status badge]: https://img.shields.io/pypi/status/56kyle-pychess
A chess library written in Python.
[Pychess](#Pychess)
- [Description](#Description)
- [Installation](#Installation)
- [Usage](#Usage)
- [Game](#Game)
- [Board](#Board)
- [Move](#Move)
- [Piece](#Piece)
- [Player](#Player)
- [Square](#Square)
- [Contributing](#Contributing)
- [License](#License)
## Installation
```bash
# Install from PyPI
pip install 56kyle-pychess
# Install from poetry
poetry add 56kyle-pychess
```
## Description
The main purpose of this library is to try and practice constantly improving the quality of a codebase instead of allowing complexity to grow with time.
I was mainly inspired by the books "Clean Code" and "Clean Coder" both written by Robert C. Martin. Most of the code in this library is written with the principles of clean code in mind.
### General Design Decisions
- The Board class is immutable. This means that every time a move is made, a new board is created. This is to prevent the board from being in an invalid state.
- Moves and most geometry related classes are described in terms of Points and Lines
- Almost all iterables are sets to allow for hash comparisons of various frozen dataclass based objects
### Simplifications
- The board may not be infinite
- The board must be a rectangle
## Features
- [ ] API
- [ ] Game
- [x] Board
- [ ] Move
- [x] Piece
- [x] Player
- [x] Square
- [ ] Engine
- [ ] UCI
- [ ] GUI
- [ ] Documentation
## Usage
### Game
TODO
### Board
TODO
### Move
TODO
### Piece
TODO
### Player
TODO
### Square
TODO
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/README.md | README.md |
# -*- coding: utf-8 -*-
from setuptools import setup
packages = \
['chess']
package_data = \
{'': ['*']}
setup_kwargs = {
'name': '56kyle-pychess',
'version': '0.4.0',
'description': 'A python chess engine',
'long_description': '\n# Pychess\n\n[![Status][status badge]][status badge]\n[![Tests][github actions badge]][github actions page]\n[![Codecov][codecov badge]][codecov page]\n[![Python Version][python version badge]][github page]\n[![License][license badge]][license]\n\n[code of conduct]: https://github.com/56kyle/pychess/blob/master/CODE_OF_CONDUCT.md\n[codecov badge]: https://codecov.io/gh/56kyle/pychess/branch/master/graph/badge.svg?token=0QDENTNTN7\n[codecov page]: https://app.codecov.io/gh/56kyle/pychess/branch/master\n[contributor covenant badge]: https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg\n[github actions badge]: https://github.com/56kyle/pychess/workflows/Tests/badge.svg\n[github actions page]: https://github.com/56kyle/pychess/actions?workflow=Tests\n[github page]: https://github.com/56kyle/pychess\n[license badge]: https://img.shields.io/github/license/56kyle/pychess\n[license]: https://opensource.org/licenses/MIT\n[python version badge]: https://img.shields.io/pypi/pyversions/56kyle-pychess\n[status badge]: https://img.shields.io/pypi/status/56kyle-pychess\n\nA chess library written in Python.\n\n\n[Pychess](#Pychess)\n - [Description](#Description)\n - [Installation](#Installation)\n - [Usage](#Usage)\n - [Game](#Game)\n - [Board](#Board)\n - [Move](#Move)\n - [Piece](#Piece)\n - [Player](#Player)\n - [Square](#Square)\n - [Contributing](#Contributing)\n - [License](#License)\n\n\n## Installation\n \n ```bash\n # Install from PyPI\n pip install 56kyle-pychess\n\n # Install from poetry\n poetry add 56kyle-pychess\n ```\n\n## Description\nThe main purpose of this library is to try and practice constantly improving the quality of a codebase instead of allowing complexity to grow with time.\n\nI was mainly inspired by the books "Clean Code" and "Clean Coder" both written by Robert C. Martin. Most of the code in this library is written with the principles of clean code in mind.\n\n### General Design Decisions\n- The Board class is immutable. This means that every time a move is made, a new board is created. This is to prevent the board from being in an invalid state.\n- Moves and most geometry related classes are described in terms of Points and Lines\n- Almost all iterables are sets to allow for hash comparisons of various frozen dataclass based objects\n\n### Simplifications\n- The board may not be infinite\n- The board must be a rectangle\n\n\n## Features\n- [ ] API\n - [ ] Game\n - [x] Board\n - [ ] Move\n - [x] Piece\n - [x] Player\n - [x] Square\n- [ ] Engine\n- [ ] UCI\n- [ ] GUI\n- [ ] Documentation\n\n## Usage\n### Game\n TODO\n### Board\n TODO\n### Move\n TODO\n### Piece\n TODO\n### Player\n TODO\n### Square\n TODO\n \n\n\n \n\n\n\n',
'author': 'kyle',
'author_email': '56kyleoliver@gmail.com',
'maintainer': None,
'maintainer_email': None,
'url': 'https://github.com/56kyle/pychess',
'packages': packages,
'package_data': package_data,
'python_requires': '>=3.10,<4.0',
}
setup(**setup_kwargs)
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/setup.py | setup.py |
from dataclasses import dataclass, replace
from typing import Self, Tuple
from chess.line import Line
from chess.position import Position
@dataclass(frozen=True)
class Rect:
p1: Position
p2: Position
@classmethod
def from_line(cls, line: Line) -> Self:
return cls(p1=line.p1, p2=line.p2)
def __contains__(self, position: Position) -> bool:
return self._is_within_width(position=position) and self._is_within_height(position=position)
def _is_within_width(self, position: Position) -> bool:
return min(self.p1.file, self.p2.file) <= position.file <= max(self.p1.file, self.p2.file)
def _is_within_height(self, position: Position) -> bool:
return min(self.p1.rank, self.p2.rank) <= position.rank <= max(self.p1.rank, self.p2.rank)
@property
def width(self) -> int:
return abs(self.p2.file - self.p1.file) + 1
@property
def height(self) -> int:
return abs(self.p2.rank - self.p1.rank) + 1
def offset(self, dx: int = 0, dy: int = 0) -> Self:
return replace(self, p1=self.p1.offset(dx=dx, dy=dy), p2=self.p2.offset(dx=dx, dy=dy))
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/rect.py | rect.py |
from enum import Enum
class Side(Enum):
KING = 0
QUEEN = 1
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/side.py | side.py |
from dataclasses import dataclass, field, replace, make_dataclass
from typing import Set, Type
from chess.color import Color
from chess.line import Line
from chess.piece_type import PieceType
from chess.position import Position
@dataclass(frozen=True)
class Piece:
position: Position
color: Color
type: PieceType = PieceType
has_moved: bool = False
def move(self, position: Position) -> 'Piece':
return replace(self, position=position, has_moved=True)
def promote(self, promotion: Type['Piece']) -> 'Piece':
return replace(self, type=promotion.type)
def is_ally(self, piece: 'Piece') -> bool:
return self.color == piece.color
def is_enemy(self, piece: 'Piece') -> bool:
return self.color != piece.color
def get_move_lines(self) -> Set[Line]:
return self.adjust_lines_to_position(self.type.get_move_lines(
position=self.position,
color=self.color,
has_moved=self.has_moved
))
def get_capture_lines(self) -> Set[Line]:
return self.adjust_lines_to_position(self.type.get_capture_lines(
position=self.position,
color=self.color,
has_moved=self.has_moved
))
def get_en_passant_lines(self) -> Set[Line]:
return self.adjust_lines_to_position(self.type.get_en_passant_lines(
position=self.position,
color=self.color,
has_moved=self.has_moved
))
def get_castle_lines(self) -> Set[Line]:
return self.adjust_lines_to_position(self.type.get_castle_lines(
position=self.position,
color=self.color,
has_moved=self.has_moved
))
def adjust_lines_to_position(self, lines: Set[Line]) -> Set[Line]:
return {line.offset(dx=self.position.file, dy=self.position.rank) for line in lines}
def to_fen(self) -> str:
return f'{self._get_fen_letter()}{self.position.to_fen()}'
def _get_fen_letter(self) -> str:
return self.type.letter.lower() if self.color == Color.BLACK else self.type.letter.upper()
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/piece.py | piece.py |
from enum import StrEnum, auto
class Color(StrEnum):
WHITE = auto()
BLACK = auto()
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/color.py | color.py |
import math
from dataclasses import dataclass, field, replace
@dataclass(frozen=True)
class Direction:
"""A vector that represents a direction in a 2D plane."""
radians: float = field(compare=False)
def __eq__(self, other: 'Direction') -> bool:
return self._eq_same_theta(other=other)
def _eq_same_theta(self, other: 'Direction') -> bool:
return self.theta == other.theta
def _eq_opposite_theta(self, other: 'Direction') -> bool:
return self.theta == self.turn_180(theta=other.theta)
@staticmethod
def normalize_radians(radians: float) -> float:
"""Adjusts the angle to be between 0 and 2pi"""
return radians % (2 * math.pi)
def turn_180(self, theta: float) -> float:
return self.normalize_radians(radians=theta + math.pi)
@property
def theta(self) -> float:
return self.normalize_radians(self.radians)
@property
def opposite(self) -> 'Direction':
return replace(self, radians=self.turn_180(self.theta))
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/direction.py | direction.py |
from dataclasses import dataclass
from chess.line import Line
from chess.position import Position
@dataclass(frozen=True)
class Ray(Line):
"""A Line that extends only in the direction of the vector from p1 to p2."""
def __contains__(self, position: Position) -> bool:
return self.is_colinear(position=position) and self.is_on_or_beyond_ray(position=position)
def is_on_or_beyond_ray(self, position: Position) -> bool:
return self.is_between_p1_and_p2(position=position) or self.is_closer_to_p2_than_p1(position=position)
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/ray.py | ray.py |
from dataclasses import dataclass
from typing import Set
from chess.color import Color
from chess.line import Line
from chess.offset import Offset, UP, RIGHT, DOWN, LEFT
from chess.piece import Piece
from chess.piece_type import PieceType
class KnightType(PieceType):
name: str = 'Knight'
letter: str = 'N'
value: int = 3
symbol: str = '\u2658'
html_decimal: str = '♞'
html_hex: str = '♘'
offsets: Set[Offset] = {
UP * 2 + RIGHT,
UP * 2 + LEFT,
DOWN * 2 + RIGHT,
DOWN * 2 + LEFT,
RIGHT * 2 + UP,
RIGHT * 2 + DOWN,
LEFT * 2 + UP,
LEFT * 2 + DOWN,
}
move_lines: Set[Line] = {offset.as_segment() for offset in offsets}
capture_lines: Set[Line] = {offset.as_segment() for offset in offsets}
@dataclass(frozen=True)
class Knight(Piece):
type: KnightType = KnightType
@dataclass(frozen=True)
class WhiteKnight(Knight):
color: Color = Color.WHITE
@dataclass(frozen=True)
class BlackKnight(Knight):
color: Color = Color.BLACK
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/knight.py | knight.py |
from dataclasses import dataclass, field
from typing import Set, Type, Self
from chess.piece_type import PieceType
from chess.position import Position
from chess.piece import Piece
@dataclass(frozen=True)
class Move:
piece: Piece
origin: Position
destination: Position
captures: Set[Piece]
promotion: PieceType | None = None
additional_moves: Set[Self] = field(default_factory=set)
def is_promotion(self) -> bool:
return self.promotion is not None
def is_capture(self) -> bool:
return len(self.captures) > 0
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/move.py | move.py |
from dataclasses import dataclass
@dataclass(frozen=True)
class Rules:
pass
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/rules.py | rules.py |
from dataclasses import dataclass
from typing import Set
from chess.color import Color
from chess.line import Line
from chess.offset import OMNI
from chess.piece import Piece
from chess.piece_type import PieceType
class QueenType(PieceType):
name: str = 'Queen'
letter: str = 'Q'
value: int = 9
symbol: str = '♛'
html_decimal: str = '♛'
html_hex: str = '♛'
move_lines: Set[Line] = {offset.as_ray() for offset in OMNI}
capture_lines: Set[Line] = {offset.as_ray() for offset in OMNI}
@dataclass(frozen=True)
class Queen(Piece):
type: QueenType = QueenType
@dataclass(frozen=True)
class WhiteQueen(Queen):
color: Color = Color.WHITE
@dataclass(frozen=True)
class BlackQueen(Queen):
color: Color = Color.BLACK
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/queen.py | queen.py |
from dataclasses import dataclass, field
from chess.position import Position
@dataclass(frozen=True)
class Size:
width: int
height: int
def __contains__(self, position: Position) -> bool:
return self._is_within_width(position=position) and self._is_within_height(position=position)
def _is_within_width(self, position: Position) -> bool:
return 1 <= position.file <= self.width
def _is_within_height(self, position: Position) -> bool:
return 1 <= position.rank <= self.height
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/size.py | size.py |
from dataclasses import dataclass
from typing import Set
from chess.color import Color
from chess.line import Line
from chess.offset import VERTICAL, DIAGONAL
from chess.piece import Piece
from chess.piece_type import PieceType
from chess.position import Position
class PawnType(PieceType):
name: str = 'Pawn'
letter: str = 'P'
value: int = 1
symbol: str = '\u2659'
html_decimal: str = '♙'
html_hex: str = '♙'
move_lines: Set[Line] = {offset.as_segment() for offset in VERTICAL}
first_move_lines: Set[Line] = {(offset * 2).as_segment() for offset in VERTICAL}
capture_lines: Set[Line] = {offset.as_segment() for offset in DIAGONAL}
en_passant_lines: Set[Line] = {offset.as_segment() for offset in DIAGONAL}
@staticmethod
def filter_lines_to_color(lines: Set[Line], color: Color) -> Set[Line]:
if color == Color.WHITE:
return {line for line in lines if line.dy > 0}
else:
return {line for line in lines if line.dy < 0}
@classmethod
def get_move_lines(cls, position: Position, color: Color, has_moved: bool):
if has_moved:
return cls.filter_lines_to_color(cls.move_lines, color)
else:
return cls.filter_lines_to_color(cls.move_lines | cls.first_move_lines, color)
@classmethod
def get_capture_lines(cls, position: Position, color: Color, has_moved: bool) -> Set[Line]:
return cls.filter_lines_to_color(cls.capture_lines, color)
@classmethod
def get_en_passant_lines(cls, position: Position, color: Color, has_moved: bool) -> Set[Line]:
return cls.filter_lines_to_color(cls.en_passant_lines, color)
@dataclass(frozen=True)
class Pawn(Piece):
type: PawnType = PawnType
@dataclass(frozen=True)
class WhitePawn(Pawn):
color: Color = Color.WHITE
@dataclass(frozen=True)
class BlackPawn(Pawn):
color: Color = Color.BLACK
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/pawn.py | pawn.py |
from chess.position import Position
# Default board positions
A1 = Position(file=1, rank=1)
A2 = Position(file=1, rank=2)
A3 = Position(file=1, rank=3)
A4 = Position(file=1, rank=4)
A5 = Position(file=1, rank=5)
A6 = Position(file=1, rank=6)
A7 = Position(file=1, rank=7)
A8 = Position(file=1, rank=8)
B1 = Position(file=2, rank=1)
B2 = Position(file=2, rank=2)
B3 = Position(file=2, rank=3)
B4 = Position(file=2, rank=4)
B5 = Position(file=2, rank=5)
B6 = Position(file=2, rank=6)
B7 = Position(file=2, rank=7)
B8 = Position(file=2, rank=8)
C1 = Position(file=3, rank=1)
C2 = Position(file=3, rank=2)
C3 = Position(file=3, rank=3)
C4 = Position(file=3, rank=4)
C5 = Position(file=3, rank=5)
C6 = Position(file=3, rank=6)
C7 = Position(file=3, rank=7)
C8 = Position(file=3, rank=8)
D1 = Position(file=4, rank=1)
D2 = Position(file=4, rank=2)
D3 = Position(file=4, rank=3)
D4 = Position(file=4, rank=4)
D5 = Position(file=4, rank=5)
D6 = Position(file=4, rank=6)
D7 = Position(file=4, rank=7)
D8 = Position(file=4, rank=8)
E1 = Position(file=5, rank=1)
E2 = Position(file=5, rank=2)
E3 = Position(file=5, rank=3)
E4 = Position(file=5, rank=4)
E5 = Position(file=5, rank=5)
E6 = Position(file=5, rank=6)
E7 = Position(file=5, rank=7)
E8 = Position(file=5, rank=8)
F1 = Position(file=6, rank=1)
F2 = Position(file=6, rank=2)
F3 = Position(file=6, rank=3)
F4 = Position(file=6, rank=4)
F5 = Position(file=6, rank=5)
F6 = Position(file=6, rank=6)
F7 = Position(file=6, rank=7)
F8 = Position(file=6, rank=8)
G1 = Position(file=7, rank=1)
G2 = Position(file=7, rank=2)
G3 = Position(file=7, rank=3)
G4 = Position(file=7, rank=4)
G5 = Position(file=7, rank=5)
G6 = Position(file=7, rank=6)
G7 = Position(file=7, rank=7)
G8 = Position(file=7, rank=8)
H1 = Position(file=8, rank=1)
H2 = Position(file=8, rank=2)
H3 = Position(file=8, rank=3)
H4 = Position(file=8, rank=4)
H5 = Position(file=8, rank=5)
H6 = Position(file=8, rank=6)
H7 = Position(file=8, rank=7)
H8 = Position(file=8, rank=8)
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/position_constants.py | position_constants.py |
from dataclasses import dataclass
from typing import Set
from chess.color import Color
from chess.line import Line
from chess.offset import LINEAR
from chess.piece import Piece
from chess.piece_type import PieceType
class RookType(PieceType):
name: str = 'Rook'
letter: str = 'R'
value: int = 5
symbol: str = '♜'
html_decimal: str = '♜'
html_hex: str = '♜'
move_lines: Set[Line] = {offset.as_ray() for offset in LINEAR}
capture_lines: Set[Line] = {offset.as_ray() for offset in LINEAR}
@dataclass(frozen=True)
class Rook(Piece):
type: RookType = RookType
@dataclass(frozen=True)
class WhiteRook(Rook):
color: Color = Color.WHITE
@dataclass(frozen=True)
class BlackRook(Rook):
color: Color = Color.BLACK
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/rook.py | rook.py |
from dataclasses import dataclass
from chess.position import ZERO
from chess.ray import Ray
from chess.segment import Segment
@dataclass(frozen=True)
class Offset:
dx: int = 0
dy: int = 0
def __iter__(self):
return iter((self.dx, self.dy))
def __add__(self, other):
if isinstance(other, Offset):
return Offset(dx=self.dx + other.dx, dy=self.dy + other.dy)
else:
return Offset(dx=self.dx + int(other), dy=self.dy + int(other))
def __sub__(self, other):
if isinstance(other, Offset):
return Offset(dx=self.dx - other.dx, dy=self.dy - other.dy)
else:
return Offset(dx=self.dx - int(other), dy=self.dy - int(other))
def __mul__(self, other):
if isinstance(other, Offset):
return Offset(dx=self.dx * other.dx, dy=self.dy * other.dy)
else:
return Offset(dx=self.dx * int(other), dy=self.dy * int(other))
def is_linear(self) -> bool:
return self.dx == 0 or self.dy == 0
def is_diagonal(self) -> bool:
return self.dx != 0 and self.dy != 0
def as_ray(self) -> 'Ray':
return Ray(p1=ZERO, p2=ZERO.offset(dx=self.dx, dy=self.dy))
def as_segment(self) -> 'Segment':
return Segment(p1=ZERO, p2=ZERO.offset(dx=self.dx, dy=self.dy))
UP = Offset(dx=0, dy=-1)
DOWN = Offset(dx=0, dy=1)
LEFT = Offset(dx=-1, dy=0)
RIGHT = Offset(dx=1, dy=0)
UP_LEFT = UP + LEFT
UP_RIGHT = UP + RIGHT
DOWN_LEFT = DOWN + LEFT
DOWN_RIGHT = DOWN + RIGHT
VERTICAL = {UP, DOWN}
HORIZONTAL = {LEFT, RIGHT}
LINEAR = VERTICAL | HORIZONTAL
DIAGONAL = {UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT}
OMNI = LINEAR | DIAGONAL
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/offset.py | offset.py |
from dataclasses import dataclass
from chess.color import Color
from chess.position import Position
from chess.side import Side
@dataclass(frozen=True)
class CastleRight:
color: Color
rook_origin: Position
rook_destination: Position
king_origin: Position
king_destination: Position
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/castle_right.py | castle_right.py |
from dataclasses import dataclass
from typing import Set
from chess.color import Color
from chess.line import Line
from chess.offset import DIAGONAL
from chess.piece import Piece
from chess.piece_type import PieceType
class BishopType(PieceType):
name: str = 'Bishop'
letter: str = 'B'
value: int = 3
symbol: str = '♝'
html_decimal: str = '♝'
html_hex: str = '♝'
move_lines: Set[Line] = {offset.as_ray() for offset in DIAGONAL}
capture_lines: Set[Line] = {offset.as_ray() for offset in DIAGONAL}
@dataclass(frozen=True)
class Bishop(Piece):
type: BishopType = BishopType
@dataclass(frozen=True)
class WhiteBishop(Bishop):
color: Color = Color.WHITE
@dataclass(frozen=True)
class BlackBishop(Bishop):
color: Color = Color.BLACK
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/bishop.py | bishop.py |
from dataclasses import dataclass
from typing import Set
from chess.color import Color
from chess.line import Line
from chess.offset import HORIZONTAL, OMNI
from chess.piece import Piece
from chess.piece_type import PieceType
from chess.position import Position
class KingType(PieceType):
name: str = 'King'
letter: str = 'K'
value: int = 0
symbol: str = '♚'
html_decimal: str = '♚'
html_hex: str = '♚'
move_lines: Set[Line] = {offset.as_segment() for offset in OMNI}
capture_lines: Set[Line] = move_lines
castle_lines: Set[Line] = {(offset*2).as_segment() for offset in HORIZONTAL} |\
{(offset*3).as_segment() for offset in HORIZONTAL}
def get_castle_lines(self, position: Position, color: Color, has_moved: bool) -> Set[Line]:
return set() if has_moved else self.castle_lines
@dataclass(frozen=True)
class King(Piece):
type: KingType = KingType
@dataclass(frozen=True)
class WhiteKing(King):
color: Color = Color.WHITE
@dataclass(frozen=True)
class BlackKing(King):
color: Color = Color.BLACK
| 56kyle-pychess | /56kyle-pychess-0.4.0.tar.gz/56kyle-pychess-0.4.0/chess/king.py | king.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.