Skip to content

Commit e7c9fa5

Browse files
committed
Clean-up, reduce line lengths to 88 (used by black)
1 parent eb207a1 commit e7c9fa5

20 files changed

+239
-183
lines changed

gql-checker/gql_checker/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def get_schema(self):
7676
introspection_schema = json.load(data_file)
7777
return build_client_schema(introspection_schema)
7878
except IOError as e:
79-
raise Exception("Cannot find the provided introspection schema. {}".format(str(e)))
79+
raise Exception(f"Cannot find the provided introspection schema. {e}")
8080

8181
schema = self.options.get('schema')
8282
assert schema, 'Need to provide schema'

gql-checker/gql_checker/flake8_linter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def parse_options(cls, options):
4343

4444
def error(self, node, code, message):
4545
lineno, col_offset = node.lineno, node.col_offset
46-
return (lineno, col_offset, '{0} {1}'.format(code, message), Linter)
46+
return lineno, col_offset, f'{code} {message}', Linter
4747

4848
def run(self):
4949
for error in self.check_gql():

gql/client.py

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
from inspect import isawaitable
23
from typing import Any, AsyncGenerator, Dict, Generator, Optional, Union, cast
34

45
from graphql import (
@@ -87,16 +88,18 @@ def execute(self, document: DocumentNode, *args, **kwargs) -> Dict:
8788
This function WILL BLOCK until the result is received from the server.
8889
8990
Either the transport is sync and we execute the query synchronously directly
90-
OR the transport is async and we execute the query in the asyncio loop (blocking here until answer)
91+
OR the transport is async and we execute the query in the asyncio loop
92+
(blocking here until answer).
9193
"""
9294

9395
if isinstance(self.transport, AsyncTransport):
9496

9597
loop = asyncio.get_event_loop()
9698

97-
assert (
98-
not loop.is_running()
99-
), "Cannot run client.execute if an asyncio loop is running. Use execute_async instead"
99+
assert not loop.is_running(), (
100+
"Cannot run client.execute if an asyncio loop is running."
101+
" Use execute_async instead."
102+
)
100103

101104
data: Dict[Any, Any] = loop.run_until_complete(
102105
self.execute_async(document, *args, **kwargs)
@@ -109,9 +112,12 @@ def execute(self, document: DocumentNode, *args, **kwargs) -> Dict:
109112
if self.schema:
110113
self.validate(document)
111114

112-
assert self.transport is not None, "Cant execute without a tranport"
115+
assert self.transport is not None, "Cannot execute without a transport"
116+
117+
result = self.transport.execute(document, *args, **kwargs)
113118

114-
result: ExecutionResult = self.transport.execute(document, *args, **kwargs)
119+
assert not isawaitable(result), "Transport returned an awaitable result."
120+
result = cast(ExecutionResult, result)
115121

116122
if result.errors:
117123
raise TransportQueryError(str(result.errors[0]))
@@ -146,9 +152,10 @@ def subscribe(
146152

147153
loop = asyncio.get_event_loop()
148154

149-
assert (
150-
not loop.is_running()
151-
), "Cannot run client.subscribe if an asyncio loop is running. Use subscribe_async instead"
155+
assert not loop.is_running(), (
156+
"Cannot run client.subscribe if an asyncio loop is running."
157+
" Use subscribe_async instead."
158+
)
152159

153160
try:
154161
while True:
@@ -191,15 +198,20 @@ def __exit__(self, *args):
191198

192199

193200
class ClientSession:
194-
""" An instance of this class is created when using 'async with' on the client.
201+
"""An instance of this class is created when using 'async with' on the client.
195202
196-
It contains the async methods (execute, subscribe) to send queries with the async transports"""
203+
It contains the async methods (execute, subscribe) to send queries
204+
with the async transports.
205+
"""
197206

198207
def __init__(self, client: Client):
199208
self.client = client
200209

201210
async def validate(self, document: DocumentNode):
202-
""" Fetch schema from transport if needed and validate document if schema is present """
211+
"""Fetch schema from transport if needed and validate document.
212+
213+
If no schema is present, the validation will be skipped.
214+
"""
203215

204216
# Get schema from transport if needed
205217
if self.client.fetch_schema_from_transport and not self.client.schema:
@@ -213,7 +225,7 @@ async def subscribe(
213225
self, document: DocumentNode, *args, **kwargs
214226
) -> AsyncGenerator[Dict, None]:
215227

216-
# Fetch schema from transport if needed and validate document if schema is present
228+
# Fetch schema from transport if needed and validate document if possible
217229
await self.validate(document)
218230

219231
# Subscribe to the transport and yield data or raise error
@@ -224,7 +236,7 @@ async def subscribe(
224236
async for result in self._generator:
225237
if result.errors:
226238
# Note: we need to run generator.aclose() here or the finally block in
227-
# the transport.subscribe will not be reached in pypy3 (python version 3.6.1)
239+
# transport.subscribe will not be reached in pypy3 (py 3.6.1)
228240
await self._generator.aclose()
229241

230242
raise TransportQueryError(str(result.errors[0]))
@@ -234,7 +246,7 @@ async def subscribe(
234246

235247
async def execute(self, document: DocumentNode, *args, **kwargs) -> Dict:
236248

237-
# Fetch schema from transport if needed and validate document if schema is present
249+
# Fetch schema from transport if needed and validate document if possible
238250
await self.validate(document)
239251

240252
# Execute the query with the transport with a timeout

gql/dsl.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,7 @@ def get_field(self, name):
6565
if camel_cased_name in self.type.fields:
6666
return camel_cased_name, self.type.fields[camel_cased_name]
6767

68-
raise KeyError(
69-
"Field {} does not exist in type {}.".format(name, self.type.name)
70-
)
68+
raise KeyError(f"Field {name} does not exist in type {self.type.name}.")
7169

7270

7371
def selections(*fields):
@@ -126,7 +124,7 @@ def selection_field(field):
126124
if isinstance(field, DSLField):
127125
return field
128126

129-
raise Exception('Received incompatible query field: "{}".'.format(field))
127+
raise Exception(f'Received incompatible query field: "{field}".')
130128

131129

132130
def query(*fields, **kwargs):
@@ -145,9 +143,9 @@ def query(*fields, **kwargs):
145143

146144

147145
def serialize_list(serializer, list_values):
148-
assert isinstance(list_values, Iterable), 'Expected iterable, received "{}"'.format(
149-
repr(list_values)
150-
)
146+
assert isinstance(
147+
list_values, Iterable
148+
), f'Expected iterable, received "{list_values!r}".'
151149
return ListValueNode(values=FrozenList(serializer(v) for v in list_values))
152150

153151

gql/transport/aiohttp.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def __init__(
4242
:param cookies: Dict of HTTP cookies.
4343
:param auth: BasicAuth object to enable Basic HTTP auth if needed
4444
:param ssl: ssl_context of the connection. Use ssl=False to disable encryption
45-
:param client_session_args: Dict of extra parameters passed to aiohttp.ClientSession
45+
:param client_session_args: Dict of extra args passed to aiohttp.ClientSession
4646
"""
4747
self.url: str = url
4848
self.headers: Optional[LooseHeaders] = headers
@@ -96,9 +96,10 @@ async def execute(
9696
extra_args: Dict[str, Any] = {},
9797
) -> ExecutionResult:
9898
"""Execute the provided document AST against the configured remote server.
99-
This uses the aiohttp library to perform a HTTP POST request asynchronously to the remote server.
99+
This uses the aiohttp library to perform a HTTP POST request asynchronously
100+
to the remote server.
100101
101-
The result is sent as an ExecutionResult object
102+
The result is sent as an ExecutionResult object.
102103
"""
103104

104105
query_str = print_ast(document)
@@ -126,7 +127,7 @@ async def execute(
126127
# We raise a TransportProtocolError in the other cases
127128

128129
try:
129-
# Raise a ClientResponseError if the response status is 400 or higher
130+
# Raise a ClientResponseError if response status is 400 or higher
130131
resp.raise_for_status()
131132

132133
except ClientResponseError as e:

gql/transport/exceptions.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,23 @@ class TransportError(Exception):
33

44

55
class TransportProtocolError(TransportError):
6-
""" An answer received from the server does not correspond to the transport protocol"""
6+
"""Transport protocol error.
7+
8+
The answer received from the server does not correspond to the transport protocol.
9+
"""
710

811

912
class TransportServerError(TransportError):
10-
""" The server returned a global error
13+
"""The server returned a global error.
1114
12-
This exception will close the transport connection
15+
This exception will close the transport connection.
1316
"""
1417

1518

1619
class TransportQueryError(Exception):
17-
""" The server returned an error for a specific query
20+
"""The server returned an error for a specific query.
1821
19-
This exception should not close the transport connection
22+
This exception should not close the transport connection.
2023
"""
2124

2225
def __init__(self, msg, query_id=None):
@@ -25,10 +28,16 @@ def __init__(self, msg, query_id=None):
2528

2629

2730
class TransportClosed(TransportError):
28-
""" Exception generated when the client is trying to use the transport
29-
while the transport was previously closed """
31+
"""Transport is already closed.
32+
33+
This exception is generated when the client is trying to use the transport
34+
while the transport was previously closed.
35+
"""
3036

3137

3238
class TransportAlreadyConnected(TransportError):
33-
""" Exception generated when the client is trying to connect to the transport
34-
while the transport is already connected """
39+
"""Transport is already connected.
40+
41+
Exception generated when the client is trying to connect to the transport
42+
while the transport is already connected.
43+
"""

gql/transport/local_schema.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Awaitable, Union
2+
13
from graphql import DocumentNode, ExecutionResult, GraphQLSchema, execute
24

35
from gql.transport import Transport
@@ -15,12 +17,14 @@ def __init__(
1517
"""
1618
self.schema = schema
1719

18-
def execute(self, document: DocumentNode, *args, **kwargs) -> ExecutionResult:
20+
def execute(
21+
self, document: DocumentNode, *args, **kwargs
22+
) -> Union[ExecutionResult, Awaitable[ExecutionResult]]:
1923
"""Execute the given document against the configured local schema.
2024
2125
:param document: GraphQL query as AST Node object.
22-
:param args: Positional options for execute method from graphql-core library.
23-
:param kwargs: Keyword options passed to execute method from graphql-core library.
24-
:return: Either ExecutionResult or a Promise that resolves to ExecutionResult object.
26+
:param args: Positional options for execute method from graphql-core.
27+
:param kwargs: Keyword options passed to execute method from graphql-core.
28+
:return: ExecutionResult (either as value or awaitable)
2529
"""
26-
return execute(self.schema, document, *args, **kwargs) # type: ignore
30+
return execute(self.schema, document, *args, **kwargs)

gql/transport/requests.py

Lines changed: 31 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,33 +16,37 @@ class RequestsHTTPTransport(Transport):
1616
"""
1717

1818
def __init__(
19-
self, # type: RequestsHTTPTransport
20-
url, # type: str
21-
headers=None, # type: Dict[str, Any]
22-
cookies=None, # type: Union[Dict[str, Any], RequestsCookieJar]
23-
auth=None, # type: AuthBase
24-
use_json=True, # type: bool
25-
timeout=None, # type: int
26-
verify=True, # type: bool
27-
retries=0, # type: int
28-
method="POST", # type: str
29-
**kwargs # type: Any
19+
self,
20+
url: str,
21+
headers: Optional[Dict[str, Any]] = None,
22+
cookies: Optional[Union[Dict[str, Any], RequestsCookieJar]] = None,
23+
auth: Optional[AuthBase] = None,
24+
use_json: bool = True,
25+
timeout: Optional[int] = None,
26+
verify: bool = True,
27+
retries: int = 0,
28+
method: str = "POST",
29+
**kwargs: Any
3030
):
3131
"""Initialize the transport with the given request parameters.
3232
3333
:param url: The GraphQL server URL.
34-
:param headers: Dictionary of HTTP Headers to send with the :class:`Request` (Default: None).
35-
:param cookies: Dict or CookieJar object to send with the :class:`Request` (Default: None).
36-
:param auth: Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth (Default: None).
37-
:param use_json: Send request body as JSON instead of form-urlencoded (Default: False).
34+
:param headers: Dictionary of HTTP Headers to send with the :class:`Request`
35+
(Default: None).
36+
:param cookies: Dict or CookieJar object to send with the :class:`Request`
37+
(Default: None).
38+
:param auth: Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth
39+
(Default: None).
40+
:param use_json: Send request body as JSON instead of form-urlencoded
41+
(Default: True).
3842
:param timeout: Specifies a default timeout for requests (Default: None).
3943
:param verify: Either a boolean, in which case it controls whether we verify
4044
the server's TLS certificate, or a string, in which case it must be a path
4145
to a CA bundle to use. (Default: True).
4246
:param retries: Pre-setup of the requests' Session for performing retries
4347
:param method: HTTP method used for requests. (Default: POST).
44-
:param kwargs: Optional arguments that ``request`` takes. These can be seen at the :requests_: source code
45-
or the official :docs_:
48+
:param kwargs: Optional arguments that ``request`` takes.
49+
These can be seen at the :requests_: source code or the official :docs_:
4650
4751
.. _requests: https://github.com/psf/requests/blob/master/requests/api.py
4852
.. _docs: https://requests.readthedocs.io/en/master/
@@ -78,14 +82,17 @@ def execute( # type: ignore
7882
variable_values: Optional[Dict[str, Any]] = None,
7983
timeout: Optional[int] = None,
8084
) -> ExecutionResult:
81-
"""Execute the provided document AST against the configured remote server.
82-
This uses the requests library to perform a HTTP POST request to the remote server.
85+
"""Execute GraphQL query.
86+
87+
Execute the provided document AST against the configured remote server. This
88+
uses the requests library to perform a HTTP POST request to the remote server.
8389
8490
:param document: GraphQL query as AST Node object.
8591
:param variable_values: Dictionary of input parameters (Default: None).
8692
:param timeout: Specifies a default timeout for requests (Default: None).
87-
:return: The result of execution. `data` is the result of executing the query, `errors` is null if no errors
88-
occurred, and is a non-empty array if an error occurred.
93+
:return: The result of execution.
94+
`data` is the result of executing the query, `errors` is null
95+
if no errors occurred, and is a non-empty array if an error occurred.
8996
"""
9097
query_str = print_ast(document)
9198
payload = {"query": query_str, "variables": variable_values or {}}
@@ -104,7 +111,9 @@ def execute( # type: ignore
104111
post_args.update(self.kwargs)
105112

106113
# Using the created session to perform requests
107-
response = self.session.request(self.method, self.url, **post_args) # type: ignore
114+
response = self.session.request(
115+
self.method, self.url, **post_args # type: ignore
116+
)
108117
try:
109118
result = response.json()
110119
if not isinstance(result, dict):

gql/transport/transport.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,20 @@
11
import abc
2+
from typing import Awaitable, Union
23

34
from graphql import DocumentNode, ExecutionResult
45

56

67
class Transport:
78
@abc.abstractmethod
8-
def execute(self, document: DocumentNode, *args, **kwargs) -> ExecutionResult:
9-
"""Execute the provided document AST for either a remote or local GraphQL Schema.
9+
def execute(
10+
self, document: DocumentNode, *args, **kwargs
11+
) -> Union[ExecutionResult, Awaitable[ExecutionResult]]:
12+
"""Execute GraphQL query.
13+
14+
Execute the provided document AST for either a remote or local GraphQL Schema.
1015
1116
:param document: GraphQL query as AST Node or Document object.
12-
:return: Either ExecutionResult or a Promise that resolves to ExecutionResult object.
17+
:return: ExecutionResult (either as value or awaitable)
1318
"""
1419
raise NotImplementedError(
1520
"Any Transport subclass must implement execute method"
@@ -18,8 +23,8 @@ def execute(self, document: DocumentNode, *args, **kwargs) -> ExecutionResult:
1823
def close(self):
1924
"""Close the transport
2025
21-
This method doesn't have to be implemented unless the transport would benefit from it.
22-
This is currently used by the RequestsHTTPTransport transport to close the session's
23-
connection pool.
26+
This method doesn't have to be implemented unless the transport would benefit
27+
from it. This is currently used by the RequestsHTTPTransport transport to close
28+
the session's connection pool.
2429
"""
2530
pass

0 commit comments

Comments
 (0)