Skip to content

Session, Authentication and low–level graph operations

Marcus Klemm edited this page Apr 5, 2019 · 29 revisions

Authentication

⚠️ HIRO Version 6.0 RC0 and newer support only graphit.GraphitAppAuth, graphit.WSO2AuthClientCredentials and graphit.WSO2AuthUserCredentials are deprecated!

❗️ graphit.GraphitAppAuth works mostly like graphit.WSO2AuthUserCredentials, the main difference is that baseurl has to point to the HIRO Graph API's URL, not WSO2's.

class graphit.GraphitAppAuth

An authentication handler for Requests that implements the OAuth2 Password grant type.

Public API

__init__(baseurl, client_id, client_secret, username, password, verify=True)

Returns an authentication handler that can be passed to a GraphitSession. It will get an authentication Token, include it in every request as header _TOKEN and renew it automatically if it is about to expire.

Parameters:
  • baseurl: A str containing the base URL of the HIRO Graph API, including port.
  • client_id: A str's containing the OAuth2 ClientID.
  • client_secret: A str's containing the OAuth2 ClientSecret.
  • username: A str's containing the account name of the user.
  • password: A str's containing the password of the user.
  • verify: Whether to validate the TLS certificate of a HTTPS connection. The following values are valid:
    • A str containing the path to a PEM file. The remote server's certificate will be validated against that PEM.
    • True: Validate the certificate against the operating system's keychain.
    • False: Do not validate the certificate.
Exceptions:

class graphit.WSO2AuthClientCredentials

⚠️ Deprecated in HIRO 6.0 RC0 and newer.

An authentication handler for Requests that implements the Client Credentials OAuth2 grant type for WSO2IS.

Public API

__init__(baseurl, client, verify=True)

Returns an authentication handler that can be passed to a GraphitSession. It will get a Token from WSO2, include it in every request as header _TOKEN and renew it automatically if it is about to expire.

Parameters:
  • baseurl: A str containing the base URL of the WSO2 identity server, including port.
  • client: A tuple (client_id, client_secret) of str's containing the OAuth2 Client Credentials.
  • verify: Whether to validate the TLS certificate of a HTTPS connection. The following values are valid:
    • A str containing the path to a PEM file. The remote server's certificate will be validated against that PEM.
    • True: Validate the certificate against the operating system's keychain.
    • False: Do not validate the certificate.
Exceptions:

token (@property)

Returns the access token

__str__()

Returns a str of format "Token <TOKEN> expires in <N> seconds."

Low–level graph operations

class graphit.GraphitSession

A subclass of Request's Session object, implementing all low–level HIRO Graph operations.

Public API

__init__(baseurl, auth=None, verify=True, *args, **kwargs)

Parameters:
  • baseurl: A str containing the base URL of the HIRO Graph, including port.
  • auth: An authentication handler.
  • verify: Whether to validate the TLS certificate of a HTTPS connection. The following values are valid:
    • A str containing the path to a PEM file. The remote server's certificate will be validated against that PEM.
    • True: Validate the certificate against the operating system's keychain.
    • False: Do not validate the certificate.
  • *args and **kwargs: will be passed to the requests.Session superclass.

request(method, resource, params=None, data=None)

Make a HTTP request to resource using method. Returns a requests.Response object.

Parameters:
  • method: A str containing the HTTP method (GET, POST, PUT, DELETE etc.) to be used in the request.
  • resource: A str containing the path to the (REST–) resource, relative to baseurl of the session. Usually starts with a /.
  • params: A dict containing additional URL parameters, see Passing Parameters In URLs for more information.
  • data: Any JSON–serializable object, will be sent in the body of the request.
Exceptions:

The following methods are wrappers around request to make the most common operations more convenient. Their accepted parameters are the same as for request and in case of errors they raise the same Exceptions. All of these methods used the json() method of requests.Response to decode the response's body.

get(resource, params=None)

Equivalent to: request('GET', resource, params).json()

update(resource, data, params=None)

Equivalent to: request('POST', resource, data, params).json()

replace(resource, data, params=None)

Equivalent to: request('PUT', resource, data, params).json()

delete(resource)

Equivalent to: request('DELETE', resource).json()

connect(ogit_type, in_id, out_id)

Create an edge between two nodes identified by in_id and out_id.

create(ogit_type, data)

Create a new Vertex of type ogit/_type with data data.

Parameters:

  • ogit_type: Type of the new vertex.
  • data: A dict or dict-like object with the vertex data as key–value–pairs. Must not include ogit/_id.
Exceptions:

query(query, query_type=None, limit=-1, offset=0, fields=None, count=False)

Perform a query. Returns a generator which will yield dicts representing the query results. You can process them directly or pass them to the graphit.GraphitNode constructor in order to get graphit.GraphitNode instances to work with.

Parameters:
  • query: An object who's string representation str(query) is a valid query string for the chosen query type.
  • query_type: The type of the Query, one of vertices (ElasticSearch), gremlin, verb or ids. Can be omitted if query is one of the specialized query classes EESQuery, GremlinQuery, VerbQuery or IDQuery.
  • limit: Only return the first limit results, int.
  • offset: Skip the first offset number of results, int.
  • fields: list of fields/attributes to return. If set to None (default), all attributes will be returned.
  • count: Don't return the actual results, only the number of results, bool
Exceptions:

__str__()

Returns a str of format "GraphIT at <BASE_URL>".

Examples

Create a session

import graphit

# HIRO 5, HIRO 6.0 Beta
auth = graphit.WSO2AuthClientCredentials(
	"https://example-iam.ai-projects.co:9443",
	client = ("<CLIENT_ID>", "<CLIENT_SECRET>"),
	verify=False
)

# HIRO 6.0 RC0 and newer
auth = graphit.GraphitAppAuth(
        # Caution, authentication uses the HIRO Graph API now, too!
	"https://example-graph.ai-projects.co:8443",
	client_id = "<CLIENT_ID>", 
        client_secret = "<CLIENT_SECRET>",
        username = "<USERNAME>",
        password = "<PASSWORD>",
	verify=False
)

session = graphit.GraphitSession(
	"https://example-graph.ai-projects.co:8443",
	auth=auth,
	verify=False
)

Create and update a vertex of type ogit/Project/Project

data = {
	"/someAttribute": "some value"
}
my_project = session.create("ogit/Project/Project", data=data)

new_data = {
	"/anotherAttribute": "another value"
}
session.update("/{id}".format(id=my_project["ogit/_id"]), data=new_data)

Get a vertex from the graph:

print(my_project["ogit/_id"])

cjkck3wm8uai9yd33iq6d5sl4

print(session.get("/cjkck3wm8uai9yd33iq6d5sl4"))

{"ogit/_id": "cjkck3wm8uai9yd33iq6d5sl4", "ogit/_type": "ogit/Project/Project", "ogit/_owner": "arago.de", "ogit/_created-on": "1533475059312", "ogit/_creator": "arago.de", "ogit/_creator-app": "graphit-tool", "ogit/_graphtype": "vertex", "ogit/_is-deleted": "false", "ogit/_modified-by": "arago.de", "ogit/_modified-by-app": "graphit-tool", "ogit/_modified-on": "1533475079615", "ogit/_v": "2", "ogit/_version": "2.19.0.287", "/someAttribute": "some value", "/anotherAttribute": "another value"}

Run an ElasticSearch query and connect all results to the ogit/Project/Project

# Create 10 vertices of type ogit/BusinessProcess/DataObject
for i in range(10):
	session.create("ogit/Project/Milestone", data={"/Key":"<SOMETHING_UNIQUE>"})

# Perform an ElasticSearchQuery that should find (only) these 10 `ogit/Project/Milestone` vertices and iterate
# over the results, connecting them to the `ogit/Project/Project` with the "ogit/belongs" verb
for item in session.query('+\/Key:"<SOMETHING_UNIQUE>"', query_type="vertices"):
	session.connect("ogit/belongs", in_id=my_project["ogit/_id"], out_id=item["ogit/_id"])