From f796702a7c398c785223eb2569b2cc69c95cbf92 Mon Sep 17 00:00:00 2001 From: James Date: Fri, 4 Sep 2015 14:37:55 +0700 Subject: [PATCH] Add docstring for all classes and methods. Fix bug with docs generator --- DOCUMENTATION.md | 159 +++++++++++++------------- __init__.py | 0 docs/doc2md.py | 2 - resin/__init__.py | 31 +++++ resin/auth.py | 128 +++++++++++++++++++++ resin/exceptions.py | 150 ++++++++++++++++++++++++ resin/logs.py | 77 ++++++++++++- resin/models/device.py | 2 +- resin/models/environment_variables.py | 7 +- resin/resources.py | 2 +- resin/settings.py | 4 +- resin/token.py | 120 +++++++++++++++++++ 12 files changed, 589 insertions(+), 93 deletions(-) create mode 100644 __init__.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 920af1ec..71a960d9 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -1,10 +1,8 @@ -## Resin Python SDK +## Resin Python SDK Welcome to the Resin Python SDK documentation. - This document aims to describe all the functions supported by the SDK, as well as showing examples of their expected usage. - If you feel something is missing, not clear or could be improved, please don't hesitate to open an issue in GitHub, we'll be happy to help. @@ -23,11 +21,10 @@ hesitate to open an issue in GitHub, we'll be happy to help. - [Logs](#logs) - [Settings](#settings) -## Models +## Models This module implements all models for Resin Python SDK. - -## Application +## Application This class implements application model for Resin Python SDK. ### Function: create(name, device_type) @@ -115,7 +112,7 @@ Restart application. #### Raises: ApplicationNotFound: if application couldn't be found. -## Device +## Device This class implements device model for Resin Python SDK. ### Function: generate_uuid() @@ -297,7 +294,7 @@ Register a new device with a Resin.io application. dict: dictionary contains device info. ### Function: remove(uuid) -Removea device. +Remove a device. #### Args: uuid (str): device uuid. @@ -311,12 +308,12 @@ Rename a device. #### Raises: DeviceNotFound: if device couldn't be found. -## Config +## Config This class implements configuration model for Resin Python SDK. #### Attributes: - _config (dict): caching configuration. + _config (dict): caching configuration. ### Function: get_all() Get all configuration. @@ -335,7 +332,7 @@ Get PubNub keys from configuration. #### Returns: dict: including PubNub subscribe_key and publish_key. -## DeviceOs +## DeviceOs This class implements device os model for Resin Python SDK. ### Function: download(raw) @@ -348,12 +345,12 @@ Download an OS image. Details about os parameters can be found in parse_params function #### Returns: - object: + object: If raw is True, urllib3.HTTPResponse object is returned. If raw is False, original response object is returned. -#### Notes: - default OS image file name can be found in response headers. +#### Notes: + default OS image file name can be found in response headers. ### Function: parse_params() Validate parameters for downloading device OS image. @@ -362,16 +359,16 @@ Validate parameters for downloading device OS image. **parameters: os parameters keyword arguments. #### Returns: - dict: validated parameters. + dict: validated parameters. -Raise: + Raise: MissingOption: if mandatory option are missing. InvalidOption: if appId or network are invalid (appId is not a number or parseable string. network is not in NETWORK_TYPES) - NonAllowedOption: if a non supported option is passed. -## EnvironmentVariable + NonAllowedOption: if a non supported option is passed. +## EnvironmentVariable This class is a wrapper for device and application environment variable models. -## ApplicationEnvVariable +## ApplicationEnvVariable This class implements application environment variable model for Resin Python SDK. @@ -420,7 +417,7 @@ Update an environment variable value for application. #### Args: var_id (str): environment variable id. value (str): new environment variable value. -## DeviceEnvVariable +## DeviceEnvVariable This class implements device environment variable model for Resin Python SDK. ### Function: create(uuid, name, value) @@ -456,7 +453,7 @@ Update a device environment variable. #### Args: var_id (str): environment variable id. value (str): new environment variable value. -## Key +## Key This class implements ssh key model for Resin Python SDK. ### Function: create(title, key) @@ -489,11 +486,11 @@ Get all ssh keys. list: list of ssh keys. ### Function: remove(id) -REmove a ssh key. +Remove a ssh key. #### Args: id (str): key id. -## Auth +## Auth This class implements all authentication functions for Resin Python SDK. ### Function: authenticate() @@ -502,105 +499,105 @@ This function authenticates provided credentials information. You should use Auth.login when possible, as it takes care of saving the Auth Token and username as well. #### Args: - **credentials: credentials keyword arguments. - username (str): Resin.io username. - password (str): Password. + **credentials: credentials keyword arguments. + username (str): Resin.io username. + password (str): Password. #### Returns: - str: Auth Token, + str: Auth Token, #### Raises: - LoginFailed: if the username or password is invalid. + LoginFailed: if the username or password is invalid. ### Function: get_email() This function retrieves current logged in user's get_email #### Returns: - str: user email. + str: user email. #### Raises: - InvalidOption: if not logged in. + InvalidOption: if not logged in. ### Function: get_token() This function retrieves Auth Token. #### Returns: - str: Auth Token. + str: Auth Token. #### Raises: - InvalidOption: if not logged in and there is no token in Settings. + InvalidOption: if not logged in and there is no token in Settings. ### Function: get_user_id() This function retrieves current logged in user's id. #### Returns: - str: user id. + str: user id. #### Raises: - InvalidOption: if not logged in. + InvalidOption: if not logged in. ### Function: is_logged_in() This function checks if you're logged in #### Returns: - bool: True if logged in, False otherwise. + bool: True if logged in, False otherwise. ### Function: log_out() This function is used for logging out from Resin.io. #### Returns: - bool: True if successful, False otherwise. + bool: True if successful, False otherwise. ### Function: login() This function is used for logging into Resin.io using username and password. #### Args: - **credentials: credentials keyword arguments. - username (str): Resin.io username. - password (str): Password. + **credentials: credentials keyword arguments. + username (str): Resin.io username. + password (str): Password. #### Returns: - This functions saves Auth Token to Settings and returns nothing. + This functions saves Auth Token to Settings and returns nothing. #### Raises: - LoginFailed: if the username or password is invalid. + LoginFailed: if the username or password is invalid. ### Function: login_with_token(token) This function is used for logging into Resin.io using Auth Token. Auth Token can be found in Preferences section on Resin.io Dashboard. #### Args: - token (str): Auth Token. + token (str): Auth Token. #### Returns: - This functions saves Auth Token to Settings and returns nothing. + This functions saves Auth Token to Settings and returns nothing. #### Raises: - MalformedToken: if token is invalid. + MalformedToken: if token is invalid. ### Function: register() This function is used for registering to Resin.io. #### Args: - **credentials: credentials keyword arguments. - email (str): email to register. - password (str): Password. + **credentials: credentials keyword arguments. + email (str): email to register. + password (str): Password. #### Returns: - str: Auth Token for new account. + str: Auth Token for new account. #### Raises: - RequestError: if error occurs during registration. + RequestError: if error occurs during registration. ### Function: who_am_i() This function retrieves username of logged in user. #### Returns: - str: username. + str: username. #### Raises: - NotLoggedIn: if there is no user logged in. -## Logs + NotLoggedIn: if there is no user logged in. +## Logs This class implements functions that allow processing logs from device. @@ -612,43 +609,43 @@ For more details about pubnub, please visit: https://www.pubnub.com/docs/python/ This function allows fetching historical device logs. #### Args: - uuid (str): device uuid. - callback (function): this callback is called on receiving a message from the channel. - error (function): this callback is called on an error event. - For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#history + uuid (str): device uuid. + callback (function): this callback is called on receiving a message from the channel. + error (function): this callback is called on an error event. + For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#history #### Examples: ```python def callback(message): - print(message) +print(message) ``` ```python def error(message): - print('Error:'+ str(message)) +print('Error:'+ str(message)) ``` - Logs.history(uuid=uuid, callback=callback, error=error) + Logs.history(uuid=uuid, callback=callback, error=error) ### Function: subscribe() This function allows subscribing to device logs. Testing #### Args: - uuid (str): device uuid. - callback (function): this callback is called on receiving a message from the channel. - error (function): this callback is called on an error event. - For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#subscribe + uuid (str): device uuid. + callback (function): this callback is called on receiving a message from the channel. + error (function): this callback is called on an error event. + For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#subscribe #### Examples: ```python def callback(message, channel): - print(message) +print(message) ``` ```python def error(message): - print('Error:'+ str(message)) +print('Error:'+ str(message)) ``` ```python @@ -659,56 +656,56 @@ Logs.subscribe(uuid=uuid, callback=callback, error=error) This function allows unsubscribing to device logs. #### Args: - uuid (str): device uuid. -## Settings + uuid (str): device uuid. +## Settings This class handles settings for Resin Python SDK. #### Attributes: - HOME_DIRECTORY (str): home directory path. - CONFIG_SECTION (str): section name in configuration file. - CONFIG_FILENAME (str): configuration file name. - _setting (dict): default value to settings. + HOME_DIRECTORY (str): home directory path. + CONFIG_SECTION (str): section name in configuration file. + CONFIG_FILENAME (str): configuration file name. + _setting (dict): default value to settings. ### Function: get(key) Get a setting value. #### Args: - key (str): setting. + key (str): setting. #### Returns: - str: setting value. + str: setting value. #### Raises: - InvalidOption: If getting a non-existent setting. + InvalidOption: If getting a non-existent setting. ### Function: get_all() Get all settings. #### Returns: - dict: all settings. + dict: all settings. ### Function: has(key) Check if a setting exists. #### Args: - key (str): setting. + key (str): setting. #### Returns: - bool: True if exists, False otherwise. + bool: True if exists, False otherwise. ### Function: remove(key) Remove a setting. #### Args: - key (str): setting. + key (str): setting. #### Returns: - bool: True if successful, False otherwise. + bool: True if successful, False otherwise. ### Function: set(key, value) Set value for a setting. #### Args: - key (str): setting. - value (str): setting value. + key (str): setting. + value (str): setting value. diff --git a/__init__.py b/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/docs/doc2md.py b/docs/doc2md.py index 9aa470bf..2851c6f5 100644 --- a/docs/doc2md.py +++ b/docs/doc2md.py @@ -19,7 +19,6 @@ INDENT = " " NEW_LINE = "" -LINK = '' # Level for each section in class CLASS_NAME = 2 @@ -164,7 +163,6 @@ def doc2md(docstr, title, type=0): intro, contents = _get_class_intro(lines) if type == 0: level = CLASS_NAME - title = LINK.format(name=title.lower())+title if type == 1: level = FUNCTION_NAME title = 'Function: {func_name}'.format(func_name=title) diff --git a/resin/__init__.py b/resin/__init__.py index e69de29b..37875c39 100644 --- a/resin/__init__.py +++ b/resin/__init__.py @@ -0,0 +1,31 @@ +""" +Welcome to the Resin Python SDK documentation. +This document aims to describe all the functions supported by the SDK, as well as +showing examples of their expected usage. +If you feel something is missing, not clear or could be improved, please don't +hesitate to open an issue in GitHub, we'll be happy to help. +""" + +from .base_request import BaseRequest +from .auth import Auth +from .token import Token +from .logs import Logs +from .settings import Settings +from .models import Models + +class Resin(object): + """ + This class implements all functions supported by the Python SDK. + Attributes: + settings (Settings): configuration settings for Resin Python SDK. + logs (Logs): logs from devices working on Resin. + auth (Auth): authentication handling. + models (Models): all models in Resin Python SDK. + + """ + + def __init__(self): + self.settings = Settings() + self.logs = Logs() + self.auth = Auth() + self.models = Models() diff --git a/resin/auth.py b/resin/auth.py index eee1c054..97965b14 100644 --- a/resin/auth.py +++ b/resin/auth.py @@ -5,6 +5,10 @@ class Auth(object): + """ + This class implements all authentication functions for Resin Python SDK. + + """ def __init__(self): self.base_request = BaseRequest() @@ -12,6 +16,22 @@ def __init__(self): self.token = Token() def login(self, **credentials): + """ + This function is used for logging into Resin.io using username and password. + + Args: + **credentials: credentials keyword arguments. + username (str): Resin.io username. + password (str): Password. + + Returns: + This functions saves Auth Token to Settings and returns nothing. + + Raises: + LoginFailed: if the username or password is invalid. + + """ + token = self.authenticate(**credentials) if self.token.is_valid_token(token): self.token.set(token) @@ -19,36 +39,144 @@ def login(self, **credentials): raise exceptions.LoginFailed() def login_with_token(self, token): + """ + This function is used for logging into Resin.io using Auth Token. + Auth Token can be found in Preferences section on Resin.io Dashboard. + + Args: + token (str): Auth Token. + + Returns: + This functions saves Auth Token to Settings and returns nothing. + + Raises: + MalformedToken: if token is invalid. + + """ + if self.token.is_valid_token(token): self.token.set(token) else: raise exceptions.MalformedToken(token) def who_am_i(self): + """ + This function retrieves username of logged in user. + + Returns: + str: username. + + Raises: + NotLoggedIn: if there is no user logged in. + + """ + return self.token.get_username() def authenticate(self, **credentials): + """ + This function authenticates provided credentials information. + You should use Auth.login when possible, as it takes care of saving the Auth Token and username as well. + + Args: + **credentials: credentials keyword arguments. + username (str): Resin.io username. + password (str): Password. + + Returns: + str: Auth Token, + + Raises: + LoginFailed: if the username or password is invalid. + + """ + return self.base_request.request( 'login_', 'POST', data=credentials, endpoint=self.settings.get('api_endpoint'), auth=False ) def is_logged_in(self): + """ + This function checks if you're logged in + + Returns: + bool: True if logged in, False otherwise. + + """ + return self.token.has() def get_token(self): + """ + This function retrieves Auth Token. + + Returns: + str: Auth Token. + + Raises: + InvalidOption: if not logged in and there is no token in Settings. + + """ + return self.token.get() def get_user_id(self): + """ + This function retrieves current logged in user's id. + + Returns: + str: user id. + + Raises: + InvalidOption: if not logged in. + + """ + return self.token.get_user_id() def get_email(self): + """ + This function retrieves current logged in user's get_email + + Returns: + str: user email. + + Raises: + InvalidOption: if not logged in. + + """ + return self.token.get_email() def log_out(self): + """ + This function is used for logging out from Resin.io. + + Returns: + bool: True if successful, False otherwise. + + """ + return self.token.remove() def register(self, **credentials): + """ + This function is used for registering to Resin.io. + + Args: + **credentials: credentials keyword arguments. + email (str): email to register. + password (str): Password. + + Returns: + str: Auth Token for new account. + + Raises: + RequestError: if error occurs during registration. + + """ + return self.base_request.request( 'user/register', 'POST', data=credentials, endpoint=self.settings.get('api_endpoint'), auth=False diff --git a/resin/exceptions.py b/resin/exceptions.py index 59d8cf25..3d594191 100644 --- a/resin/exceptions.py +++ b/resin/exceptions.py @@ -3,6 +3,19 @@ class MissingOption(Exception): + """ + Exception type for missing option in settings or auth token. + + Args: + option (str): option name. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self, option): self.code = 'MissingOption' self.exit_code = 1 @@ -10,6 +23,19 @@ def __init__(self, option): class InvalidOption(Exception): + """ + Exception type for invalid option in settings or auth token. + + Args: + option (str): option name. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self, option): self.code = 'InvalidOption' self.exit_code = 1 @@ -17,6 +43,19 @@ def __init__(self, option): class NonAllowedOption(Exception): + """ + Exception type for non allowed option in parameters for downloading device OS. + + Args: + option (str): option name. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self, option): self.code = 'NonAllowedOption' self.exit_code = 1 @@ -24,6 +63,19 @@ def __init__(self, option): class InvalidDeviceType(Exception): + """ + Exception type for invalid device type. + + Args: + dev_type (str): device type. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self, dev_type): self.code = 'InvalidDeviceType' self.exit_code = 1 @@ -31,6 +83,19 @@ def __init__(self, dev_type): class MalformedToken(Exception): + """ + Exception type for malformed token. + + Args: + token (str): token. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self, token): self.code = 'MalformedToken' self.exit_code = 1 @@ -38,6 +103,19 @@ def __init__(self, token): class ApplicationNotFound(Exception): + """ + Exception type for application not found. + + Args: + application (str): application detail (application name or id). + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self, application): self.code = 'ApplicationNotFound' self.exit_code = 1 @@ -46,6 +124,19 @@ def __init__(self, application): class DeviceNotFound(Exception): + """ + Exception type for device not found. + + Args: + device (str): device detail (device uuid or device name). + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self): self.code = 'DeviceNotFound' self.exit_code = 1 @@ -53,6 +144,19 @@ def __init__(self): class KeyNotFound(Exception): + """ + Exception type for ssh key not found. + + Args: + key (str): ssh key id. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self, key): self.code = 'KeyNotFound' self.exit_code = 1 @@ -60,6 +164,19 @@ def __init__(self, key): class RequestError(Exception): + """ + Exception type for request error. + + Args: + body (str): response body. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self, body): self.code = 'RequestError' self.exit_code = 1 @@ -67,6 +184,16 @@ def __init__(self, body): class NotLoggedIn(Exception): + """ + Exception when no user logged in. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self): self.code = 'NotLoggedIn' self.exit_code = 1 @@ -74,6 +201,16 @@ def __init__(self): class LoginFailed(Exception): + """ + Exception when login unsuccessful. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self): self.code = 'LoginFailed' self.exit_code = 1 @@ -81,6 +218,19 @@ def __init__(self): class DeviceOffline(Exception): + """ + Exception when a device is offline. + + Args: + uuid (str): device uuid. + + Attributes: + code (str): exception code. + exit_code (int): program exit code. + message (str): error message. + + """ + def __init__(self, uuid): self.code = 'DeviceOffline' self.exit_code = 1 diff --git a/resin/logs.py b/resin/logs.py index a36107cd..beac014e 100644 --- a/resin/logs.py +++ b/resin/logs.py @@ -1,14 +1,25 @@ from pubnub import Pubnub +from functools import wraps from .base_request import BaseRequest from .models.config import Config class Logs(object): + """ + This class implements functions that allow processing logs from device. + + This class is implemented using pubnub python sdk. + + For more details about pubnub, please visit: https://www.pubnub.com/docs/python/pubnub-python-sdk + + """ + def __init__(self): self.config = Config() - def init_pubnub(func): + def _init_pubnub(func): + @wraps(func) def wrapper(self, *args, **kwargs): if not hasattr(self, 'pubnub'): pubnub_key = self.config.get_pubnub_keys() @@ -19,21 +30,81 @@ def wrapper(self, *args, **kwargs): return func(self, *args, **kwargs) return wrapper - @init_pubnub + @_init_pubnub def subscribe(self, uuid, callback, error): + """ + This function allows subscribing to device logs. + Testing + + Args: + uuid (str): device uuid. + callback (function): this callback is called on receiving a message from the channel. + error (function): this callback is called on an error event. + For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#subscribe + + Examples: + >>> def callback(message, channel): + ... print(message) + + >>> def error(message): + ... print('Error:'+ str(message)) + + >>> Logs.subscribe(uuid=uuid, callback=callback, error=error) + + """ + channel = self.get_channel(uuid) self.pubnub.subscribe(channels=channel, callback=callback, error=error) - @init_pubnub + @_init_pubnub def history(self, uuid, callback, error): + """ + This function allows fetching historical device logs. + + Args: + uuid (str): device uuid. + callback (function): this callback is called on receiving a message from the channel. + error (function): this callback is called on an error event. + For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#history + + Examples: + >>> def callback(message): + ... print(message) + + >>> def error(message): + ... print('Error:'+ str(message)) + + Logs.history(uuid=uuid, callback=callback, error=error) + + """ + channel = self.get_channel(uuid) self.pubnub.history(channel=channel, callback=callback, error=error) def unsubscribe(self, uuid): + """ + This function allows unsubscribing to device logs. + + Args: + uuid (str): device uuid. + + """ + if hasattr(self, 'pubnub'): channel = self.get_channel(uuid) self.pubnub.unsubscribe(channel=channel) @staticmethod def get_channel(uuid): + """ + This function returns pubnub channel for a specific device. + + Args: + uuid (str): device uuid. + + Returns: + str: device channel. + + """ + return 'device-{uuid}-logs'.format(uuid=uuid) diff --git a/resin/models/device.py b/resin/models/device.py index ec6deba6..4b0b0953 100644 --- a/resin/models/device.py +++ b/resin/models/device.py @@ -455,7 +455,7 @@ def register(self, app_name, uuid): 'user': user_id, 'application': application['id'], 'device_type': application['device_type'], - 'registered_at': now.total_seconds() + 'registered_at': now.total_seconds(), 'uuid': uuid } diff --git a/resin/models/environment_variables.py b/resin/models/environment_variables.py index aaa831e7..cfcba849 100644 --- a/resin/models/environment_variables.py +++ b/resin/models/environment_variables.py @@ -112,6 +112,9 @@ def remove(self, var_id): return self.base_request.request( 'device_environment_variable', 'DELETE', params=params, endpoint=self.settings.get('pine_endpoint') + ) + +class ApplicationEnvVariable(object): """ This class implements application environment variable model for Resin Python SDK. @@ -121,10 +124,6 @@ def remove(self, var_id): """ - ) - - -class ApplicationEnvVariable(object): SYSTEM_VARIABLE_RESERVED_NAMES = ['RESIN', 'USER'] OTHER_RESERVED_NAMES_START = 'RESIN_' diff --git a/resin/resources.py b/resin/resources.py index 1abf2351..0ef063d9 100644 --- a/resin/resources.py +++ b/resin/resources.py @@ -7,7 +7,7 @@ class Message(object): """ Message templates """ - + # Exception Error Message NOT_LOGGED_IN = "You have to log in" REQUEST_ERROR = "Request error: {body}" diff --git a/resin/settings.py b/resin/settings.py index 92d7bbdd..988f3234 100644 --- a/resin/settings.py +++ b/resin/settings.py @@ -4,6 +4,8 @@ from . import exceptions + +class Settings(object): """ This class handles settings for Resin Python SDK. @@ -14,7 +16,7 @@ _setting (dict): default value to settings. """ -class Settings(object): + HOME_DIRECTORY = Path.expanduser('~') CONFIG_SECTION = 'Settings' CONFIG_FILENAME = 'resin.cfg' diff --git a/resin/token.py b/resin/token.py index 372aca75..d7c2a39c 100644 --- a/resin/token.py +++ b/resin/token.py @@ -8,6 +8,10 @@ class Token(object): + """ + This class provides Auth Token utilities for Resin Python SDK. + This is low level class and is not meant to be used by end users directly. + """ def __init__(self): self.settings = Settings() @@ -19,6 +23,17 @@ def __parse_token(self, token): raise exceptions.MalformedToken(token) def is_valid_token(self, token): + """ + Check if an auth token is valid. + + Args: + token (str): auth token. + + Returns: + bool: True if the token is valid, False otherwise. + + """ + try: self.__parse_token(token) return True @@ -26,25 +41,86 @@ def is_valid_token(self, token): return False def set(self, token): + """ + Set auth token. + + Args: + token (str): auth token. + + """ + if self.is_valid_token(token): self.settings.set(TOKEN_KEY, token) def get(self): + """ + Get auth token. + + Returns: + bool: True if the token is valid, False otherwise. + + Raises: + InvalidOption: if auth token is not set. + + """ + return self.settings.get(TOKEN_KEY) def has(self): + """ + Check if auth token is exist. + + Returns: + bool: True if the auth token exists, False otherwise. + + """ + return self.settings.has(TOKEN_KEY) def remove(self): + """ + Remove auth token. + + Returns: + bool: True if successful, False otherwise. + + """ + return self.settings.remove(TOKEN_KEY) def get_data(self): + """ + Read encoded information in the auth token. + + Returns: + dict: auth token data. + + Raises: + NotLoggedIn: if there is no user logged in. + + """ + if self.has(): return self.__parse_token(self.settings.get(TOKEN_KEY)) else: raise exceptions.NotLoggedIn() def get_property(self, element): + """ + Get a property from auth token data. + + Args: + element (str): property name. + + Returns: + str: property value. + + Raises: + InvalidOption: If getting a non-existent property. + NotLoggedIn: if there is no user logged in. + + """ + token_data = self.get_data() if element in token_data: return token_data[element] @@ -52,15 +128,59 @@ def get_property(self, element): raise exceptions.InvalidOption(element) def get_username(self): + """ + Get username from auth token data. + + Returns: + str: username. + + Raises: + NotLoggedIn: if there is no user logged in. + + """ + return self.get_property('username') def get_user_id(self): + """ + Get user id from auth token data. + + Returns: + str: user id. + + Raises: + NotLoggedIn: if there is no user logged in. + + """ + return self.get_property('id') def get_email(self): + """ + Get email from auth token data. + + Returns: + str: email. + + Raises: + NotLoggedIn: if there is no user logged in. + + """ + return self.get_property('email') def get_age(self): + """ + Get age of the auth token data. + + Returns: + int: age in milliseconds. + + Raises: + NotLoggedIn: if there is no user logged in. + + """ + # dt will be the same as Date.now() in Javascript but converted to # milliseconds for consistency with js/sc sdk dt = (datetime.utcnow() - datetime.utcfromtimestamp(0)).total_seconds()