sasctl.core#

class sasctl.core.OAuth2Token(access_token, refresh_token=None, expiration=None, expires_in=None, **kwargs)[source]#

Bases: AuthBase

Attributes:
is_expired

Methods

__call__(r)

Call self as a function.

property is_expired#
class sasctl.core.PageIterator(obj, session=None, threads=4)[source]#

Bases: object

Iterates through a collection that must be “paged” from the server.

Pages contain a batch of items from the overall collection. Iterates the series of pages and returns a single batch of items each time next() is called.

Parameters:
objRestObj

An instance of RestObj containing any initial items and a link to retrieve additional items.

sessionSession

The Session instance to use for requesting additional items. Defaults to current_session()

threadsint

Number of threads allocated to downloading additional pages.

Yields:
List[RestObj]

Items contained in the current page

class sasctl.core.PagedItemIterator(obj, session=None, threads=4)[source]#

Bases: object

Iterates through a collection that must be “paged” from the server.

Uses PageIterator to transparently download pages of items from the server as needed.

Parameters:
objRestObj

An instance of RestObj containing any initial items and a link to retrieve additional items.

sessionSession

The Session instance to use for requesting additional items. Defaults to current_session()

threadsint

Number of threads allocated to downloading additional items.

Yields:
RestObj

See also

PageIterator

Notes

Value returned by len() is an approximate count of the items available. The actual number of items returned may be greater than or less than this number.

class sasctl.core.PagedList(obj, session=None, threads=4)[source]#

Bases: list

List that dynamically loads items from the server.

Parameters:
objRestObj

An instance of RestObj containing any initial items and a link to retrieve additional items.

sessionSession, optional

The Session instance to use for requesting additional items. Defaults to current_session()

threadsint, optional

Number of threads allocated to loading additional items.

Notes

Value returned by len() is an approximate count of the items available. The actual length is not known until all items have been pulled from the server.

Methods

append(object, /)

Append object to the end of the list.

clear(/)

Remove all items from list.

copy(/)

Return a shallow copy of the list.

count(value, /)

Return number of occurrences of value.

extend(iterable, /)

Extend list by appending elements from the iterable.

index(value[, start, stop])

Return first index of value.

insert(index, object, /)

Insert object before index.

pop([index])

Remove and return item at index (default last).

remove(value, /)

Remove first occurrence of value.

reverse(/)

Reverse IN PLACE.

sort(*[, key, reverse])

Sort the list in ascending order and return None.

class sasctl.core.PagedListIterator(l)[source]#

Bases: object

Iterates over an instance of PagedList

Parameters:
llist-like
class sasctl.core.RestObj[source]#

Bases: dict

Methods

clear()

copy()

fromkeys(iterable[, value])

Create a new dictionary with keys from iterable and values set to value.

get(key[, default])

Return the value for key if key is in the dictionary, else default.

items()

keys()

pop(key[, default])

If key is not found, default is returned if given, otherwise KeyError is raised

popitem(/)

Remove and return a (key, value) pair as a 2-tuple.

setdefault(key[, default])

Insert key with a value of default if key is not in the dictionary.

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()

class sasctl.core.SSLContextAdapter(*args, **kwargs)[source]#

Bases: HTTPAdapter

HTTPAdapter that uses the default SSL context on the machine.

Methods

add_headers(request, **kwargs)

Add any headers needed by the connection.

build_response(req, resp)

Builds a Response object from a urllib3 response.

cert_verify(conn, url, verify, cert)

Verify a SSL certificate.

close()

Disposes of any internal state.

get_connection(url[, proxies])

Returns a urllib3 connection for the given URL.

init_poolmanager(*args, **kwargs)

Initializes a urllib3 PoolManager.

proxy_headers(proxy)

Returns a dictionary of the headers to add to any request sent through a proxy.

proxy_manager_for(proxy, **proxy_kwargs)

Return urllib3 ProxyManager for the given proxy.

request_url(request, proxies)

Obtain the url to use when making the final request.

send(request[, stream, timeout, verify, ...])

Sends PreparedRequest object.

init_poolmanager(*args, **kwargs)[source]#

Initializes a urllib3 PoolManager.

This method should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.

Parameters:
  • connections – The number of urllib3 connection pools to cache.

  • maxsize – The maximum number of connections to save in the pool.

  • block – Block when no free connections are available.

  • pool_kwargs – Extra keyword arguments used to initialize the Pool Manager.

class sasctl.core.Session(hostname, username=None, password=None, authinfo=None, protocol=None, port=None, verify_ssl=None, token=None, client_id=None, client_secret=None, consul_token=None)[source]#

Bases: Session

Establish a connection to a SAS Viya server.

Parameters:
hostnamestr or swat.CAS

Name of the server to connect to or an established swat.CAS session.

usernamestr, optional

Username for authentication. Not required if host is a CAS connection, if Kerberos is used, or if token is provided. If using Kerberos and an explicit username is desired, maybe be a string in ‘user@REALM’ format.

passwordstr, optional

Password for authentication. Not required when host is a CAS connection, authinfo is provided, token is provided, or Kerberos is used.

authinfostr, optional

Path to a .authinfo or .netrc file from which credentials should be pulled.

protocol{‘http’, ‘https’}

Whether to use HTTP or HTTPS connections. Defaults to https.

portint, optional

Port number for the connection if a non-standard port is used. Defaults to 80 or 443 depending on protocol.

verify_sslbool, optional

Whether server-side SSL certificates should be verified. Defaults to true. Ignored for HTTP connections.

tokenstr, optional

OAuth token to use for authorization.

client_idstr, optional

Client ID requesting access. Use if connection to Viya should be made using client_credentials method.

client_secretstr, optional

Client secret for client requesting access. Required if client_id is provided.

Attributes:
message_loglogging.Logger

A log to which all REST request and response messages will be sent. Attach a handler using add_logger() to capture these messages.

filterslist of callable

A collection of functions that will be called with each request and response object prior to logging the messages, allowing any sensitive information to be removed first.

Methods

add_logger(handler[, level])

Log session requests and responses.

add_stderr_logger([level])

Log session requests and responses to stderr.

as_swat([server])

Create a SWAT connection to a CAS server.

cache_token(token, path)

Write an OAuth2 token to the cache.

close()

Closes all adapters and as such the session

delete(url, **kwargs)

Sends a DELETE request.

get(url, **kwargs)

Sends a GET request.

get_adapter(url)

Returns the appropriate connection adapter for the given URL.

get_redirect_target(resp)

Receives a Response.

head(url, **kwargs)

Sends a HEAD request.

merge_environment_settings(url, proxies, ...)

Check the environment and merge it with some settings.

mount(prefix, adapter)

Registers a connection adapter to a prefix.

options(url, **kwargs)

Sends a OPTIONS request.

patch(url[, data])

Sends a PATCH request.

post(url, **kwargs)

Sends a POST request.

prepare_request(request)

Constructs a PreparedRequest for transmission and returns it.

put(url, **kwargs)

Sends a PUT request.

read_cached_token(path)

Read any cached access tokens from disk

rebuild_auth(prepared_request, response)

When being redirected we may want to strip authentication from the request to avoid leaking credentials.

rebuild_method(prepared_request, response)

When being redirected we may want to change the method of the request based on certain specs or browser behavior.

rebuild_proxies(prepared_request, proxies)

This method re-evaluates the proxy configuration by considering the environment variables.

request(method, url[, params, data, ...])

Constructs a Request, prepares it and sends it.

resolve_redirects(resp, req[, stream, ...])

Receives a Response.

send(request, **kwargs)

Send a given PreparedRequest.

should_strip_auth(old_url, new_url)

Decide whether Authorization header should be removed when redirecting

version_info()

Get version information from the connected SAS Viya environment

PROFILE_PATH = '~/.sas/viya-api-profiles.yaml'#
add_logger(handler, level=None)[source]#

Log session requests and responses.

Parameters:
handlerlogging.Handler

A Handler instance to use for logging the requests and responses.

levelint, optional

The logging level to assign to the handler. Ignored if handler’s logging level is already set. Defaults to DEBUG.

Returns:
handler

New in version 1.2.0: ..

add_stderr_logger(level=None)[source]#

Log session requests and responses to stderr.

Parameters:
levelint, optional

The logging level of the handler. Defaults to logging.DEBUG

Returns:
logging.StreamHandler
as_swat(server=None, **kwargs)[source]#

Create a SWAT connection to a CAS server.

Uses the authentication information from the session to establish a CAS connection using SWAT.

Parameters:
serverstr, optional

The logical name of the CAS server, not the hostname. Defaults to “cas-shared-default”.

kwargsany

Additional arguments to pass to the swat.CAS constructor. Can be used to override this method’s default behavior or customize the CAS session.

Returns:
swat.CAS

An active SWAT connection

Raises:
RuntimeError

If swat package is not available.

Examples

>>> sess = Session('example.sas.com')
>>> with sess.as_swat() as conn:
...    conn.listnodes()
CASResults([('nodelist', Node List
              name        role connected   IP Address
0  example.sas.com  controller       Yes  127.0.0.1)])

New in version 1.5.4.

cache_token(token, path)[source]#

Write an OAuth2 token to the cache.

Parameters:
tokenOAuth2Token

Token to be cached.

pathstr

Path to file containing cached tokens.

Returns:
None
delete(url, **kwargs)[source]#

Sends a DELETE request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

get(url, **kwargs)[source]#

Sends a GET request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

head(url, **kwargs)[source]#

Sends a HEAD request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

property hostname#
post(url, **kwargs)[source]#

Sends a POST request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

put(url, **kwargs)[source]#

Sends a PUT request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

read_cached_token(path)[source]#

Read any cached access tokens from disk

Parameters:
pathstr

Path to file containing cached tokens.

Returns:
OAuth2Token or None
request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None)[source]#

Constructs a Request, prepares it and sends it. Returns Response object.

Parameters:
  • method – method for the new Request object.

  • url – URL for the new Request object.

  • params – (optional) Dictionary or bytes to be sent in the query string for the Request.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • headers – (optional) Dictionary of HTTP Headers to send with the Request.

  • cookies – (optional) Dict or CookieJar object to send with the Request.

  • files – (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.

  • auth – (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.

  • timeout (float or tuple) – (optional) How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.

  • allow_redirects (bool) – (optional) Set to True by default.

  • proxies – (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy.

  • stream – (optional) whether to immediately download the response content. Defaults to False.

  • verify – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True. When set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to False may be useful during local development or testing.

  • cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

Return type:

requests.Response

send(request, **kwargs)[source]#

Send a given PreparedRequest.

Return type:

requests.Response

property username#
version_info()[source]#

Get version information from the connected SAS Viya environment

Returns:
VersionInfo

Notes

The resulting version information is cached and returned on any subsequent calls. This allows repeatedly checking version information without making redundant network calls to the SAS Viya server.

class sasctl.core.VersionInfo(major, minor=None, cadence=None, release=None)[source]#

Bases: object

Stores the version information for a SAS Viya environment.

Parameters:
majorint

Major version number (e.g. 3 for Viya 3.5 or 4 for Viya 4.0)

minorint

Minor version number (e.g. 5 for Viya 3.5 or 0 for Viya 4.0)

cadencestr, optional

Release cadence for Viya 4. Should be one of ‘stable’ or ‘LTS’.

releasestr, optional
Release number for Viya 4. Two formats are currently possible:
  • YYYY.R.U where R is the LTS release number in YYYY and U is the updates since R

  • YYYY.MM where MM is the month of the release.

Attributes:
cadence
major
minor
release
property cadence#
property major#
property minor#
property release#
sasctl.core.current_session(*args, **kwargs)[source]#

Gets and sets the current session.

If call with no arguments, the current session instance is returned, or None if no session has been created yet. If called with an existing session instance, that session will be set as the default. Otherwise, a new Session is instantiated using the provided arguments and set as the default.

Parameters:
argsany
kwargsany
Returns:
Session

Examples

Get the current session

>>> current_session()
<sasctl.core.Session object at 0x1393fc550>

Clear the current session

>>> current_session(None)

Make a new session current

>>> current_session('example.com', 'knight', 'Ni!')
<sasctl.core.Session object at 0x15a9df491>
sasctl.core.delete(path, **kwargs)[source]#

Send a DELETE request.

Parameters:
pathstr

The path portion of the URL.

kwargsany

Passed to request.

Returns:
RestObj
sasctl.core.get(path, **kwargs)[source]#

Send a GET request.

Parameters:
pathstr

The path portion of the URL.

kwargsany

Passed to request.

Returns:
RestObj or None

The results or None if the resource was not found.

Get link information from a resource.

Parameters:
objdict
relstr
Returns:
dict
sasctl.core.head(path, **kwargs)[source]#

Send a HEAD request.

Parameters:
pathstr

The path portion of the URL.

kwargsany

Passed to request.

Returns:
RestObj
sasctl.core.is_uuid(id_)[source]#
sasctl.core.platform_version()[source]#

Get the version of the SAS Viya platform to which sasctl is connected.

Returns:
string{‘3.5’, ‘4.0’}

SAS Viya version number

New in version 1.5.6: ..

sasctl.core.post(path, **kwargs)[source]#

Send a POST request.

Parameters:
pathstr

The path portion of the URL.

kwargsany

Passed to request.

Returns:
RestObj
sasctl.core.put(path, item=None, **kwargs)[source]#

Send a PUT request.

Parameters:
pathstr

The path portion of the URL.

itemRestObj, optional

A existing object to PUT. If provided, ETag and Content-Type headers will automatically be specified.

kwargsany

Passed to request.

Returns:
RestObj
sasctl.core.request(verb, path, session=None, format='auto', **kwargs)[source]#

Send an HTTP request with a session.

Parameters:
verbstr

A valid HTTP request verb.

pathstr

Path portion of URL to request.

sessionSession, optional

Defaults to current_session().

format{‘auto’, ‘rest’, ‘response’, ‘content’, ‘json’, ‘text’}

The format of the return response. Defaults to auto. rest: RestObj constructed from JSON. response: the raw Response object. content: Response.content json: Response.json() text: Response.text auto: RestObj constructed from JSON if possible, otherwise same as

text.

kwargsany

Additional arguments are passed to the session request method.

Returns:

Request a link from a resource.

Parameters:
objdict
relstr
kwargsany

Passed to :function:`request`

Returns:
sasctl.core.uri_as_str(obj)[source]#

Get the URI of a resource in string format.

Parameters:
objstr or dict

Strings are assumed to be URIs and are returned as is. Dictionary objects will be checked for a self URI and returned if found.

Returns:
str

Resource URI or None if not found