From 59c01172bb03641b18489d2a3e036a6353d2506d Mon Sep 17 00:00:00 2001 From: lilac-supernova-2 <143229315+lilac-supernova-2@users.noreply.github.com> Date: Sat, 26 Aug 2023 03:56:25 -0400 Subject: [PATCH] Refactor execute_graphql_request function to reduce complexity --- graphene_django/views.py | 57 +++++++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 21 deletions(-) diff --git a/graphene_django/views.py b/graphene_django/views.py index de5dfab..d83d7c4 100644 --- a/graphene_django/views.py +++ b/graphene_django/views.py @@ -284,6 +284,25 @@ class GraphQLView(View): return {} + def validate_query_request_type( + self, request, document, operation_name, show_graphiql + ): + if request.method.lower() == "get": + operation_ast = get_operation_ast(document, operation_name) + if ( + operation_ast + and operation_ast.operation != OperationType.QUERY + and not show_graphiql + ): + raise HttpError( + HttpResponseNotAllowed( + ["POST"], + "Can only perform a {} operation from a POST request.".format( + operation_ast.operation.value + ), + ) + ) + def execute_graphql_request( self, request, data, query, variables, operation_name, show_graphiql=False ): @@ -297,20 +316,12 @@ class GraphQLView(View): except Exception as e: return ExecutionResult(errors=[e]) - if request.method.lower() == "get": - operation_ast = get_operation_ast(document, operation_name) - if operation_ast and operation_ast.operation != OperationType.QUERY: - if show_graphiql: - return None + self.validate_query_request_type( + request, document, operation_name, show_graphiql + ) + if show_graphiql: + return None - raise HttpError( - HttpResponseNotAllowed( - ["POST"], - "Can only perform a {} operation from a POST request.".format( - operation_ast.operation.value - ), - ) - ) try: extra_options = {} if self.execution_context_class: @@ -327,14 +338,7 @@ class GraphQLView(View): options.update(extra_options) operation_ast = get_operation_ast(document, operation_name) - if ( - operation_ast - and operation_ast.operation == OperationType.MUTATION - and ( - graphene_settings.ATOMIC_MUTATIONS is True - or connection.settings_dict.get("ATOMIC_MUTATIONS", False) is True - ) - ): + if self.is_atomic_mutation_enabled(operation_ast, connection): with transaction.atomic(): result = self.schema.execute(**options) if getattr(request, MUTATION_ERRORS_FLAG, False) is True: @@ -399,3 +403,14 @@ class GraphQLView(View): meta = request.META content_type = meta.get("CONTENT_TYPE", meta.get("HTTP_CONTENT_TYPE", "")) return content_type.split(";", 1)[0].lower() + + @staticmethod + def is_atomic_mutation_enabled(operation_ast, connection): + return ( + operation_ast + and operation_ast.operation == OperationType.MUTATION + and ( + graphene_settings.ATOMIC_MUTATIONS is True + or connection.settings_dict.get("ATOMIC_MUTATIONS", False) is True + ) + )