def document_from_string(self, schema, document_string): """Parse string and setup request document for execution. Args: schema (graphql.GraphQLSchema): Schema definition object document_string (str): Request query/mutation/subscription document. Returns: graphql.GraphQLDocument """ if isinstance(document_string, ast.Document): document_ast = document_string document_string = print_ast(document_ast) else: if not isinstance(document_string, str): logger.error("The query must be a string") document_ast = parse(document_string) return GraphQLDocument( schema=schema, document_string=document_string, document_ast=document_ast, execute=partial(execute_and_validate_and_strip, schema, document_ast, **self.execute_params), )
def setUp(self): super().setUp() self.assertCountEqual(self.gql_bot.keys(), self.operations_bot) for x in self.gql_bot: definition = parse(self.gql_bot[x]).definitions[0] if definition.operation != 'query': assert definition.selection_set.selections[ 0].name.value in settings.BOT_GAS_MUTATION self.bot = models.Bot.objects.create( username='******', password='******', first_name='Bot', last_name='McBotFace', email='*****@*****.**', ) self.bot.gid = to_global_id('PersonNode', self.bot.id) models.Deposit.objects.create( user=self.bot, amount=300, payment_id='unique_bot_1', category=models.DepositCategory.objects.first(), )
def parse_schema_to_gql(schema_str=None, directory=None): gqls = Source(schema_str) gqld = parse(gqls) schema = build_ast_schema(gqld) q_tpl = '{} {}{} {{\n{}\n}}' if directory: path = pathlib.Path(directory) if not path.is_absolute(): path = pathlib.Path(path.cwd(), path) pathlib.Path(path, 'query').mkdir(parents=True, exist_ok=True) pathlib.Path(path, 'mutation').mkdir(parents=True, exist_ok=True) pathlib.Path(path, 'subscription').mkdir(parents=True, exist_ok=True) print(path) if schema.get_query_type(): for field in schema.get_query_type().fields: qstr, arg_dict = gen_query(schema, field, 'Query') vars_types_str = vars_to_types_str(arg_dict) if vars_types_str: vars_types_str = '({})'.format(vars_types_str) q_str = q_tpl.format('query', field, vars_types_str, qstr) if directory: file_path = pathlib.Path(path, 'query', "{}.graphql".format(field)) print(file_path) with open(file_path, 'w+') as f: f.write(q_str) else: print(q_str)
def build_query(self, query): validation_errors = validate(self.schema, parse(query)) if validation_errors: raise GraphQLError(validation_errors) def execute(*, context=None, **variables): return self.execute_query(query, context, variables=variables) return execute
def document_from_string(self, schema, document_string): # type: (GraphQLSchema, Union[Document, str]) -> GraphQLDocument if isinstance(document_string, ast.Document): document_ast = document_string document_string = print_ast(document_ast) else: assert isinstance(document_string, string_types), "The query must be a string" document_ast = parse(document_string) return GraphQLDocument( schema=schema, document_string=document_string, document_ast=document_ast, execute=partial(execute_and_validate, schema, document_ast, **self.execute_params), )
def middleware(request): if not models.Bot.objects.filter(id=request.user.id).exists(): return get_response(request) bot = models.Bot.objects.get(id=request.user.id) if bot.gas < 0: if bot.balance() >= bot.tank / settings.BOT_GAS_PRICE: models.Donation.create( user=bot, target=models.Nonprofit.objects.get( username=settings.ROOT_NONPROFIT_USERNAME), amount=bot.tank / settings.GAS_PRICE, ) else: raise GraphQLError('Bot has no money left for gas') response = get_response(request) if request.method == 'POST' and 'graphql' in request.path: try: body = json.loads(request.body.decode()) definition = parse(body['query']).definitions[0] except RawPostDataException: return response if definition.operation == 'query': bot.gas -= settings.BOT_GAS_QUERY_FIXED + \ settings.BOT_GAS_QUERY_VARIABLE * len(response.content) elif response.status_code == 200: # only charge if successful try: bot.gas -= settings.BOT_GAS_MUTATION[ definition.selection_set.selections[0].name.value] except KeyError: bot.gas -= max(settings.BOT_GAS_MUTATION.values()) bot.save() return response