graphql-python/gql

Modify a query

Hadevmin opened this issue · 2 comments

Hi!

How to modify a query on exception? Take this code like example:

async with Client(transport=transport) as s:
	query = gql("""
		query example{
			first {example1}
			second {example2}
		}
	""")
	try:
		result = await s.execute(query)
	except TransportQueryError:
		# remove 'second {example2}' in query
		result = await s.execute(query)

My query is very long and I don't want to rewrite the same query with less lines by recreating a query=gql() variable when the error occurs.
I don't know if it's the best way to bypass the error, but I would like to remove 'second {example2}' when TransportQueryError is rise to retry the request and get the result without error.

Thanks

You could use the DSL module.
The problem is that there is no methods to unselect a field, you can only add them.

One way to do this would be:

  1. create the query with only the first part with the DSL module
  2. use the print_ast method of graphql on the result of the dsl_gql method to save the query as a string.
  3. add the second part to the query using select to have your complete query
  4. execute the complete query
  5. If an exception is received, then use the gql method on the query saved previously as a string and execute it

Thanks you @leszekhanusz !
This is a very good method!
Thanks, you save me from duplicating code!