sgqlc.endpoint.base module¶
Base Endpoint¶
Base interface for endpoints.
See concrete implementations:
sgqlc.endpoint.http.HTTPEndpoint
usingurllib.request.urlopen()
.
sgqlc.endpoint.websocket.WebSocketEndpoint
usingwebsocket._core.create_connection()
.
Example using sgqlc.endpoint.http.HTTPEndpoint
:
#!/usr/bin/env python3
import sys
import json
from sgqlc.endpoint.http import HTTPEndpoint
try:
token, repo = sys.argv[1:]
except ValueError:
raise SystemExit('Usage: <token> <team/repo>')
query = '''
query GitHubRepoIssues($repoOwner: String!, $repoName: String!) {
repository(owner: $repoOwner, name: $repoName) {
issues(first: 100) {
nodes {
number
title
}
}
}
}
'''
owner, name = repo.split('/', 1)
variables = {
'repoOwner': owner,
'repoName': name,
}
url = 'https://api.github.com/graphql'
headers = {
'Authorization': 'bearer ' + token,
}
endpoint = HTTPEndpoint(url, headers)
data = endpoint(query, variables)
json.dump(data, sys.stdout, sort_keys=True, indent=2, default=str)
See more examples.
- license:
ISC
- class sgqlc.endpoint.base.BaseEndpoint[source]¶
Bases:
object
GraphQL endpoint access.
The user of this class should create GraphQL queries and interpret the resulting object, created from JSON data, with top level properties:
- Data:
object matching the GraphQL requests, or
null
if only errors were returned.- Errors:
list of errors, which are objects with the key “message” and optionally others, such as “location” (for errors matching GraphQL input). Instead of raising exceptions, such as
json.JSONDecodeError
those are stored in the “exception” key. Subclasses should extend errors providing meaningful messages and extra payload.
Note
Both
data
anderrors
may be returned, for instance if a null-able field fails, it will be returned as null (PythonNone
) in data the associated error in the array.The class has its own
logging.Logger
which is used to debug, info, warning and errors. Note that subclasses may override this logger. Error logging and conversion to uniform data structure similar to GraphQL, with{"errors": [...]}
is done byBaseEndpoint._log_json_error()
andBaseEndpoint._log_graphql_error()
methods. This last one will show the snippets of GraphQL that failed execution.- __call__(query, variables=None, operation_name=None)[source]¶
Calls the GraphQL endpoint.
- Parameters:
query (
str
orbytes
.) – the GraphQL query or mutation to execute. Note that this is converted usingbytes()
, thus one may pass an object implementing__bytes__()
method to return the query, eventually in more compact form (no indentation, etc).variables (dict) – variables (dict) to use with
query
. This is only useful if the query or mutation contains$variableName
. Must be a plain JSON-serializeable object (dict with string keys and values being one of dict, list, tuple, str, int, float, bool, None… –json.dumps()
is used) and the keys must match exactly the variable names (no name conversion is done, no dollar-sign prefix$
should be used).operation_name (str) – if more than one operation is listed in
query
, then it should specify the one to be executed.
- Returns:
dict with optional fields
data
containing the GraphQL returned data as nested dict anderrors
with an array of errors. Note that bothdata
anderrors
may be returned!- Return type:
Note
Subclasses must implement this method, should respect this base signature and may extend with extra parameters such as timeout, extra headers and so on.
- __weakref__¶
list of weak references to the object (if defined)
- _fixup_graphql_error(data)[source]¶
Given a possible GraphQL error payload, make sure it’s in shape.
This will ensure the given
data
is in the shape:{"errors": [{"message": "some string"}]}
If
errors
is not an array, it will be made into a single element array, with the object in that format, with its string representation being the message.If an element of the
errors
array is not in the format, then it’s converted to the format, with its string representation being the message.The input object is not changed, a copy is made if needed.
- Returns:
the given
data
formatted to the correct shape, a copy is made and returned if any fix up was needed.- Return type:
- _log_json_error(body, exc)[source]¶
Log a
json.JSONDecodeError
, converting to GraphQL’s{"data": null, "errors": [{"message": str(exc)...}]}
- Parameters:
body (str) – the string with JSON document.
exc (
json.JSONDecodeError
) – thejson.JSONDecodeError
- Returns:
GraphQL-compliant dict with keys
data
anderrors
.- Return type:
- static snippet(code, locations, sep=' | ', colmark=('-', '^'), context=5)[source]¶
Given a code and list of locations, convert to snippet lines.
return will include line number, a separator (
sep
), then line contents.At most
context
lines are shown before each location line.After each location line, the column is marked using
colmark
. The first character is repeated up to column, the second character is used only once.- Returns:
list of lines of sources or column markups.
- Return type: