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:
- 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:
- 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
- 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 tocurrent_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.
See also
- class sasctl.core.PagedListIterator(l)[source]#
Bases:
object
Iterates over an instance of
PagedList
- Parameters:
l (list)
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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. ReturnsResponse
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 toFalse
, 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 toFalse
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:
- 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.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.request(verb, path, session=None, format='auto', **kwargs)[source]#
Send an HTTP request with a session.
- Parameters:
verb (str) – A valid HTTP request verb.
path (str) – Path portion of URL to request.
session (Session, optional) – Defaults to current_session().
format (str) –
The format of the return response. Defaults to auto.
rest:
RestObj
constructed from JSON.response: the raw
requests.Response
object.content:
requests.Response.content
json:
requests.Response.json()
text:
requests.Response.text
auto:
RestObj
constructed from JSON if possible, otherwise same as text.
**kwargs – Additional arguments are passed to the session
Session.request()
method.
- Returns:
str, bytes, or requests.Response