graphql-python / gql

A GraphQL client in Python
https://gql.readthedocs.io
MIT License
1.56k stars 180 forks source link

"Transport is already connected" error when using Python Client in Multithreaded environment #493

Closed lgnashold closed 4 months ago

lgnashold commented 4 months ago

Describe the bug I am creating a CLI tool, which under the hood uses the graphql-python library to send GraphQL requests to a server.

A user of my CLI tool may want to send requests from a multithreaded environment. However, when I try to do this, I get the following error:

To Reproduce

# CLI Code 
client_ = None

def get_client():
    global client_

    transport = AIOHTTPTransport(
        url=f"{http://localhost:8000/graphql/"
    )
    client_ = Client(transport=transport, fetch_schema_from_transport=True)
    return client_

def my_cli_function():

    query = gql(
        f"""
        query MyQuery {{
            testQuery() {{
                 result
            }}
        }}
        """
    )
    results = get_client().execute(query)
    return results["result"]

# User Code 

from concurrent.futures import ThreadPoolExecutor

thread_pool = ThreadPoolExecutor(max_workers=4)

def f():
    return my_cli_function()

results = []
for i in range(5):
    results.append(thread_pool.submit(f))

for result in results:
    print(result.result())

Expected behavior I would expect there to be a transport option that works with multithreading, or an alternative pattern I should use.

System info (please complete the following information):

leszekhanusz commented 4 months ago

See related issue #314 and my comment.

leszekhanusz commented 4 months ago

You might also be interested in an async permanent session?