sasctl.core#

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

Bases: AuthBase

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:
  • obj (RestObj) – An instance of RestObj containing any initial items and a link to retrieve additional items.

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

  • threads (int) – Number of threads allocated to downloading additional pages.

Yields:

list of 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:
  • obj (RestObj) – An instance of RestObj containing any initial items and a link to retrieve additional items.

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

  • threads (int) – Number of threads allocated to downloading additional items.

Yields:

RestObj

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.

See also

PageIterator

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

Bases: list

List that dynamically loads items from the server.

Parameters:
  • obj (RestObj) – An instance of RestObj containing any initial items and a link to retrieve additional items.

  • session (Session, optional) – The Session instance to use for requesting additional items. Defaults to current_session()

  • threads (int, 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.

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

Bases: object

Iterates over an instance of PagedList

Parameters:

l (list)

class sasctl.core.RestObj[source]#

Bases: dict

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

Bases: HTTPAdapter

HTTPAdapter that uses the default SSL context on the machine.

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:
  • hostname (str or swat.cas.connection.CAS) – Name of the server to connect to or an established CAS session.

  • username (str, 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.

  • password (str, optional) – Password for authentication. Not required when host is a CAS connection, authinfo is provided, token is provided, or Kerberos is used.

  • authinfo (str, optional) – Path to a .authinfo or .netrc file from which credentials should be pulled.

  • protocol (str) – Choose from {'http', 'https'}. Whether to use HTTP or HTTPS connections. Defaults to https.

  • port (int, optional) – Port number for the connection if a non-standard port is used. Defaults to 80 or 443 depending on protocol.

  • verify_ssl (bool, optional) – Whether server-side SSL certificates should be verified. Defaults to true. Ignored for HTTP connections.

  • token (str, optional) – OAuth token to use for authorization.

  • client_id (str, optional) – Client ID requesting access. Use if connection to Viya should be made using “client_credentials” method.

  • client_secret (str, optional) – Client secret for client requesting access. Required if client_id is provided.

Variables:
  • message_log (logging.Logger) – A log to which all REST request and response messages will be sent. Attach a handler using add_logger() to capture these messages.

  • filters (list 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.

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

Log session requests and responses.

Parameters:
  • handler (logging.Handler) – A Handler instance to use for logging the requests and responses.

  • level (int, optional) – The logging level to assign to the handler. Ignored if handler’s logging level is already set. Defaults to logging.DEBUG.

Returns:

logging.Handler

Added in version 1.2.0.

add_stderr_logger(level=None)[source]#

Log session requests and responses to stderr.

Parameters:

level (int, 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:
  • server (str, optional) – The logical name of the CAS server, not the hostname. Defaults to “cas-shared-default”.

  • **kwargs – 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.connection.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)])

Added in version 1.5.4.

cache_token(token, path)[source]#

Write an OAuth2 token to the cache.

Parameters:
  • token (OAuth2Token) – Token to be cached.

  • path (str) – 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:

path (str) – 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.

  • hooks – (optional) Dictionary mapping hook name to one event or list of events, event must be callable.

  • 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(req, **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:
  • major (int) – Major version number (e.g. 3 for Viya 3.5 or 4 for Viya 4.0)

  • minor (int) – Minor version number (e.g. 5 for Viya 3.5 or 0 for Viya 4.0)

  • cadence (str, optional) – Release cadence for Viya 4. Should be one of ‘stable’ or ‘LTS’.

  • release (str, 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.

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:
  • *args

  • **kwargs

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:
  • path (str) – The path portion of the URL.

  • **kwargs – Passed to request().

Returns:

RestObj

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

Send a GET request.

Parameters:
  • path (str) – The path portion of the URL.

  • **kwargs – Passed to request().

Returns:

RestObj or None – The results or None if the resource was not found.

Get link information from a resource.

Parameters:
Returns:

dict

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

Send a HEAD request.

Parameters:
  • path (str) – The path portion of the URL.

  • **kwargs – 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:

str – SAS Viya version number ‘3.5’ or ‘4.0’

Added in version 1.5.6.

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

Send a POST request.

Parameters:
  • path (str) – The path portion of the URL.

  • **kwargs – Passed to request().

Returns:

RestObj

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

Send a PUT request.

Parameters:
  • path (str) – The path portion of the URL.

  • item (RestObj, optional) – A existing object to PUT. If provided, ETag and Content-Type headers will automatically be specified.

  • **kwargs – Passed to request().

Returns:

RestObj

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

Send an HTTP request with a session.

Parameters:
Returns:

str, bytes, or requests.Response

Request a link from a resource.

Parameters:
Returns:

RestObj

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

Get the URI of a resource in string format.

Parameters:

obj (str 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