signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def findall(self, query):
return list(self._finder(filter, query))<EOL>
Finds all cells matching the query. :param query: A literal string to match or compiled regular expression. :type query: str, :py:class:`re.RegexObject`
f1323:c1:m27
def export(self, format):
import warnings<EOL>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning,<EOL>stacklevel=<NUM_LIT:2><EOL>)<EOL>
.. deprecated:: 2.0 This feature is not supported in Sheets API v4.
f1323:c1:m28
def duplicate(<EOL>self,<EOL>insert_sheet_index=None,<EOL>new_sheet_id=None,<EOL>new_sheet_name=None<EOL>):
return self.spreadsheet.duplicate_sheet(<EOL>self.id,<EOL>insert_sheet_index,<EOL>new_sheet_id,<EOL>new_sheet_name<EOL>)<EOL>
Duplicate the sheet. :param int insert_sheet_index: (optional) The zero-based index where the new sheet should be inserted. The index of all sheets after this are incremented. :param int new_sheet_id: (optional) The ID of the new sheet. If not set, an ID is chosen. If set, the ID must not conflict with any existing sheet ID. If set, it must be non-negative. :param str new_sheet_name: (optional) The name of the new sheet. If empty, a new name is chosen for you. :returns: a newly created :class:`<gspread.models.Worksheet>`. .. versionadded:: 3.1.0
f1323:c1:m29
@property<EOL><INDENT>def row(self):<DEDENT>
return self._row<EOL>
Row number of the cell.
f1323:c2:m2
@property<EOL><INDENT>def col(self):<DEDENT>
return self._col<EOL>
Column number of the cell.
f1323:c2:m3
@property<EOL><INDENT>def input_value(self):<DEDENT>
import warnings<EOL>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning,<EOL>stacklevel=<NUM_LIT:2><EOL>)<EOL>
.. deprecated:: 2.0 This feature is not supported in Sheets API v4.
f1323:c2:m5
@property<EOL><INDENT>def session(self):<DEDENT>
return vishnu.get_session()<EOL>
:return: the current vishnu session :rtype: vishnu.session.Session
f1329:c0:m0
@property<EOL><INDENT>def session(self):<DEDENT>
return vishnu.get_session()<EOL>
:return: the current vishnu session :rtype: vishnu.session.Session
f1333:c0:m0
def google_app_engine_ndb_delete_expired_sessions(dormant_for=<NUM_LIT>, limit=<NUM_LIT>):
from vishnu.backend.client.google_app_engine_ndb import VishnuSession<EOL>from google.appengine.ext import ndb<EOL>from datetime import datetime<EOL>from datetime import timedelta<EOL>now = datetime.utcnow()<EOL>last_accessed = now - timedelta(seconds=dormant_for)<EOL>query = VishnuSession.query(ndb.OR(<EOL>ndb.AND(VishnuSession.expires <= now, VishnuSession.expires != None),<EOL>VishnuSession.last_accessed <= last_accessed<EOL>))<EOL>results = query.fetch(keys_only=True, limit=limit)<EOL>ndb.delete_multi(results)<EOL>return len(results) < limit<EOL>
Deletes expired sessions A session is expired if it expires date is set and has passed or if it has not been accessed for a given period of time. :param dormant_for: seconds since last access to delete sessions, defaults to 24 hours. :type dormant_for: int :param limit: amount to delete in one call of the method, the maximum and default for this is the NDB fetch limit of 500 :type limit: int
f1350:m0
def google_cloud_datastore_delete_expired_sessions(dormant_for=<NUM_LIT>, limit=<NUM_LIT>):
from vishnu.backend.client.google_cloud_datastore import TABLE_NAME<EOL>from google.cloud import datastore<EOL>from datetime import datetime<EOL>from datetime import timedelta<EOL>now = datetime.utcnow()<EOL>last_accessed = now - timedelta(seconds=dormant_for)<EOL>client = datastore.Client()<EOL>accessed_query = client.query(kind=TABLE_NAME)<EOL>accessed_query.add_filter("<STR_LIT>", "<STR_LIT>", last_accessed)<EOL>accessed_results = accessed_query.fetch(limit=limit)<EOL>expires_query = client.query(kind=TABLE_NAME)<EOL>expires_query.add_filter("<STR_LIT>", "<STR_LIT>", now)<EOL>expires_results = expires_query.fetch(limit=limit)<EOL>keys = list()<EOL>for result in accessed_results:<EOL><INDENT>keys.append(result.key)<EOL><DEDENT>for result in expires_results:<EOL><INDENT>if result.key not in keys:<EOL><INDENT>keys.append(result.key)<EOL><DEDENT><DEDENT>client.delete_multi(keys)<EOL>return len(keys) < limit<EOL>
Deletes expired sessions A session is expired if it expires date is set and has passed or if it has not been accessed for a given period of time. :param dormant_for: seconds since last access to delete sessions, defaults to 24 hours. :type dormant_for: int :param limit: amount to delete in one call of the method, the maximum and default for this is the NDB fetch limit of 500 :type limit: int
f1350:m2
def get_session():
return _thread_local.session<EOL>
Returns the session for the current request
f1352:m0
def save(self, sync_only=False):
entity = datastore.Entity(key=self._key)<EOL>entity["<STR_LIT>"] = self.last_accessed<EOL>entity["<STR_LIT:data>"] = self._data<EOL>if self.expires:<EOL><INDENT>entity["<STR_LIT>"] = self.expires<EOL><DEDENT>self._client.put(entity)<EOL>
:param sync_only: :type: bool
f1353:c0:m3
@property<EOL><INDENT>def host(self):<DEDENT>
return self._host<EOL>
:return: the host of the memcache instance :rtype: string
f1362:c0:m1
@property<EOL><INDENT>def port(self):<DEDENT>
return self._port<EOL>
:return: the port of the memcache instance :rtype: integer
f1362:c0:m2
@property<EOL><INDENT>def host(self):<DEDENT>
return self._host<EOL>
:return: the host of the memcache instance :rtype: string
f1363:c0:m1
@property<EOL><INDENT>def port(self):<DEDENT>
return self._port<EOL>
:return: the port of the memcache instance :rtype: integer
f1363:c0:m2
@property<EOL><INDENT>def host(self):<DEDENT>
return self._host<EOL>
:return: the host of the memcache instance :rtype: string
f1364:c0:m1
@property<EOL><INDENT>def port(self):<DEDENT>
return self._port<EOL>
:return: the port of the memcache instance :rtype: integer
f1364:c0:m2
def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT, db=DEFAULT_DB):
super(Config, self).__init__()<EOL>if not isinstance(host, str):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self._host = host<EOL>if not isinstance(port, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if port < <NUM_LIT:0>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self._port = port<EOL>if not isinstance(db, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if db < <NUM_LIT:0>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self._db = db<EOL>
:param host: host on which redis is available :rtype: string :param port: port on which redis is running :rtype: int :param db: db :rtype: int
f1367:c0:m0
@property<EOL><INDENT>def host(self):<DEDENT>
return self._host<EOL>
:return: the host of the redis instance :rtype: string
f1367:c0:m1
@property<EOL><INDENT>def port(self):<DEDENT>
return self._port<EOL>
:return: the port of the redis instance :rtype: integer
f1367:c0:m2
@property<EOL><INDENT>def db(self):<DEDENT>
return self._db<EOL>
:return: the db of the redis instance :rtype: integer
f1367:c0:m3
@property<EOL><INDENT>def secret(self):<DEDENT>
return self._secret<EOL>
:return: secret used for HMAC signature :rtype: string
f1372:c0:m1
@property<EOL><INDENT>def cookie_name(self):<DEDENT>
return self._cookie_name<EOL>
:return: the name for the cookie :rtype: string
f1372:c0:m2
@property<EOL><INDENT>def encrypt_key(self):<DEDENT>
return self._encrypt_key<EOL>
:return: key to use for encryption :rtype: string
f1372:c0:m3
@property<EOL><INDENT>def secure(self):<DEDENT>
return self._secure<EOL>
:return: whether the cookie can only be transmitted over HTTPS :rtype: boolean
f1372:c0:m4
@property<EOL><INDENT>def domain(self):<DEDENT>
return self._domain<EOL>
:return: the domain the cookie is valid for :rtype: string
f1372:c0:m5
@property<EOL><INDENT>def path(self):<DEDENT>
return self._path<EOL>
:return: the path the cookie is valid for :rtype: string
f1372:c0:m6
@property<EOL><INDENT>def http_only(self):<DEDENT>
return self._http_only<EOL>
:return: whether the cookie should only be sent over HTTP/HTTPS :rtype: boolean
f1372:c0:m7
@property<EOL><INDENT>def auto_save(self):<DEDENT>
return self._auto_save<EOL>
:return: whether this session should auto save :rtype: boolean
f1372:c0:m8
@property<EOL><INDENT>def backend(self):<DEDENT>
return self._backend<EOL>
:return: config for desired backend :rtype: vishnu.backend.config.Base
f1372:c0:m11
@classmethod<EOL><INDENT>def generate_sid(cls):<DEDENT>
return uuid.uuid4().hex<EOL>
:return: generates a unique ID for use by a session :rtype: string
f1372:c1:m1
@property<EOL><INDENT>def started(self):<DEDENT>
return self._started<EOL>
Has the session been started? - True if autosave is on and session has been modified - True if autosave is off if session has been saved at least once - True is a matching persistent session was found
f1372:c1:m2
@property<EOL><INDENT>def needs_save(self):<DEDENT>
return self._needs_save<EOL>
Does this session need to be saved.
f1372:c1:m4
@property<EOL><INDENT>def timeout(self):<DEDENT>
return self._config.timeout<EOL>
Fetch the current timeout value for this session
f1372:c1:m5
@timeout.setter<EOL><INDENT>def timeout(self, value):<DEDENT>
if value == TIMEOUT_SESSION:<EOL><INDENT>self._config.timeout = None<EOL>self._backend_client.expires = None<EOL><DEDENT>else:<EOL><INDENT>self._config.timeout = value<EOL>self._calculate_expires()<EOL><DEDENT>
Sets a custom timeout value for this session
f1372:c1:m6
def _calculate_expires(self):
self._backend_client.expires = None<EOL>now = datetime.utcnow()<EOL>self._backend_client.expires = now + timedelta(seconds=self._config.timeout)<EOL>
Calculates the session expiry using the timeout
f1372:c1:m7
def _load_cookie(self):
cookie = SimpleCookie(self._environ.get('<STR_LIT>'))<EOL>vishnu_keys = [key for key in cookie.keys() if key == self._config.cookie_name]<EOL>if not vishnu_keys:<EOL><INDENT>return<EOL><DEDENT>morsel = cookie[vishnu_keys[<NUM_LIT:0>]]<EOL>morsel_value = morsel.value<EOL>if self._config.encrypt_key:<EOL><INDENT>cipher = AESCipher(self._config.encrypt_key)<EOL>morsel_value = cipher.decrypt(morsel_value)<EOL><DEDENT>received_sid = Session.decode_sid(self._config.secret, morsel_value)<EOL>if received_sid:<EOL><INDENT>self._sid = received_sid<EOL><DEDENT>else:<EOL><INDENT>logging.warn("<STR_LIT>")<EOL><DEDENT>
Loads HTTP Cookie from environ
f1372:c1:m8
def header(self):
if self._send_cookie:<EOL><INDENT>morsel = Morsel()<EOL>cookie_value = Session.encode_sid(self._config.secret, self._sid)<EOL>if self._config.encrypt_key:<EOL><INDENT>cipher = AESCipher(self._config.encrypt_key)<EOL>cookie_value = cipher.encrypt(cookie_value)<EOL>if sys.version_info > (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>cookie_value = cookie_value.decode()<EOL><DEDENT><DEDENT>morsel.set(self._config.cookie_name, cookie_value, cookie_value)<EOL>if self._config.domain:<EOL><INDENT>morsel["<STR_LIT>"] = self._config.domain<EOL><DEDENT>if self._config.path:<EOL><INDENT>morsel["<STR_LIT:path>"] = self._config.path<EOL><DEDENT>if self._expire_cookie:<EOL><INDENT>morsel["<STR_LIT>"] = "<STR_LIT>"<EOL><DEDENT>elif self._backend_client.expires:<EOL><INDENT>morsel["<STR_LIT>"] = self._backend_client.expires.strftime(EXPIRES_FORMAT)<EOL><DEDENT>if self._config.secure:<EOL><INDENT>morsel["<STR_LIT>"] = True<EOL><DEDENT>if self._config.http_only:<EOL><INDENT>morsel["<STR_LIT>"] = True<EOL><DEDENT>return morsel.OutputString()<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Generates HTTP header for this cookie.
f1372:c1:m9
@classmethod<EOL><INDENT>def encode_sid(cls, secret, sid):<DEDENT>
secret_bytes = secret.encode("<STR_LIT:utf-8>")<EOL>sid_bytes = sid.encode("<STR_LIT:utf-8>")<EOL>sig = hmac.new(secret_bytes, sid_bytes, hashlib.sha512).hexdigest()<EOL>return "<STR_LIT>" % (sig, sid)<EOL>
Computes the HMAC for the given session id.
f1372:c1:m10
@classmethod<EOL><INDENT>def is_signature_equal(cls, sig_a, sig_b):<DEDENT>
if len(sig_a) != len(sig_b):<EOL><INDENT>return False<EOL><DEDENT>invalid_chars = <NUM_LIT:0><EOL>for char_a, char_b in zip(sig_a, sig_b):<EOL><INDENT>if char_a != char_b:<EOL><INDENT>invalid_chars += <NUM_LIT:1><EOL><DEDENT><DEDENT>return invalid_chars == <NUM_LIT:0><EOL>
Compares two signatures using a constant time algorithm to avoid timing attacks.
f1372:c1:m11
@classmethod<EOL><INDENT>def decode_sid(cls, secret, cookie_value):<DEDENT>
if len(cookie_value) > SIG_LENGTH + SID_LENGTH:<EOL><INDENT>logging.warn("<STR_LIT>")<EOL>return None<EOL><DEDENT>cookie_sig = cookie_value[:SIG_LENGTH]<EOL>cookie_sid = cookie_value[SIG_LENGTH:]<EOL>secret_bytes = secret.encode("<STR_LIT:utf-8>")<EOL>cookie_sid_bytes = cookie_sid.encode("<STR_LIT:utf-8>")<EOL>actual_sig = hmac.new(secret_bytes, cookie_sid_bytes, hashlib.sha512).hexdigest()<EOL>if not Session.is_signature_equal(cookie_sig, actual_sig):<EOL><INDENT>return None<EOL><DEDENT>return cookie_sid<EOL>
Decodes a cookie value and returns the sid if value or None if invalid.
f1372:c1:m12
def terminate(self):
self._backend_client.clear()<EOL>self._needs_save = False<EOL>self._started = False<EOL>self._expire_cookie = True<EOL>self._send_cookie = True<EOL>
Terminates an active session
f1372:c1:m14
def get(self, key):
self._started = self._backend_client.load()<EOL>self._needs_save = True<EOL>return self._backend_client.get(key)<EOL>
Retrieve a value from the session dictionary
f1372:c1:m15
def __setitem__(self, key, value):
self._started = self._backend_client.load()<EOL>self._needs_save = True<EOL>if self._config.auto_save:<EOL><INDENT>self._started = True<EOL><DEDENT>self._backend_client[key] = value<EOL>
Set a value in the session dictionary
f1372:c1:m16
@classmethod<EOL><INDENT>def pad(cls, data):<DEDENT>
if sys.version_info > (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>try:<EOL><INDENT>data = data.encode("<STR_LIT:utf-8>")<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>length = AES.block_size - (len(data) % AES.block_size)<EOL>data += bytes([length]) * length<EOL>return data<EOL><DEDENT>else:<EOL><INDENT>return data + (AES.block_size - len(data) % AES.block_size) * chr(AES.block_size - len(data) % AES.block_size)<EOL><DEDENT>
Pads data to match AES block size
f1373:c0:m1
@classmethod<EOL><INDENT>def unpad(cls, data):<DEDENT>
if sys.version_info > (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>return data[:-ord(data[len(data)-<NUM_LIT:1>:])].decode()<EOL><DEDENT>else:<EOL><INDENT>return data[:-ord(data[len(data)-<NUM_LIT:1>:])]<EOL><DEDENT>
Unpads data that has been padded
f1373:c0:m2
def encrypt(self, raw):
padded = AESCipher.pad(raw)<EOL>init_vec = Random.new().read(AES.block_size)<EOL>cipher = AES.new(self._key, AES.MODE_CBC, init_vec)<EOL>return b64encode(init_vec + cipher.encrypt(padded))<EOL>
Encrypts raw data using AES and then base64 encodes it. :param raw: :return:
f1373:c0:m3
def decrypt(self, encrypted):
decoded = b64decode(encrypted)<EOL>init_vec = decoded[:AES.block_size]<EOL>cipher = AES.new(self._key, AES.MODE_CBC, init_vec)<EOL>return AESCipher.unpad(cipher.decrypt(decoded[AES.block_size:]))<EOL>
Base64 decodes the data and then decrypts using AES. :param encrypted: :return:
f1373:c0:m4
def must_exist(self):
self._must_exist = True<EOL>
Indicates this path must exist before runtime
f1392:c0:m1
def must_be_file(self):
if self._must_be_dir:<EOL><INDENT>raise AttributeError('<STR_LIT>')<EOL><DEDENT>self._must_be_file = True<EOL>
Indicates that, if it exists, this path must be a file
f1392:c0:m2
def must_be_dir(self):
if self._must_be_file:<EOL><INDENT>raise AttributeError('<STR_LIT>')<EOL><DEDENT>self._must_be_dir = True<EOL>
Indicates that, if it exists, this path must be a directory
f1392:c0:m3
def create_dir(self):
self._create_dir = True<EOL>
Indicates that, if it doesn't exist already, this path will be created as a directory
f1392:c0:m4
@property<EOL><INDENT>def type_name(self) -> str:<DEDENT>
return Types.path<EOL>
:return: user friendly type for this config value
f1392:c0:m5
@property<EOL><INDENT>def friendly_type_name(self) -> str:<DEDENT>
_constraints_set = []<EOL>if self._must_be_dir:<EOL><INDENT>_constraints_set.append('<STR_LIT>')<EOL><DEDENT>if self._must_be_file:<EOL><INDENT>_constraints_set.append('<STR_LIT>')<EOL><DEDENT>if self._must_exist:<EOL><INDENT>_constraints_set.append('<STR_LIT>')<EOL><DEDENT>_constraints_as_str = '<STR_LIT>' + '<STR_LIT:U+002CU+0020>'.join(_constraints_set) + '<STR_LIT:)>' if _constraints_set else '<STR_LIT>'<EOL>return '<STR_LIT:path>' + _constraints_as_str<EOL>
:return: friendly type name for the end-user :rtype: str
f1392:c0:m6
@property<EOL><INDENT>def type_name(self) -> str:<DEDENT>
return Types.boolean<EOL>
:return: user friendly type for this config value
f1393:c0:m0
@property<EOL><INDENT>def user_friendly_type(self) -> str:<DEDENT>
return friendly_type_name(self.key_type)<EOL>
:return: user friendly type of the key :rtype: str
f1394:c0:m0
@property<EOL><INDENT>def mandatory(self) -> bool:<DEDENT>
return self.default is SENTINEL<EOL>
:return: True if this key has no default :rtype: bool
f1394:c0:m1
@property<EOL><INDENT>def type_name(self) -> str:<DEDENT>
return '<STR_LIT>'<EOL>
:return: user friendly type for this config value
f1394:c1:m1
@property<EOL><INDENT>def type_name(self) -> str:<DEDENT>
return Types.float<EOL>
:return: user friendly type for this config value
f1395:c0:m0
def set_limits(self, min_: typing.Optional[float] = None, max_: typing.Optional[float] = None):
self._min, self._max = min_, max_<EOL>
Sets limits for this config value If the resulting integer is outside those limits, an exception will be raised :param min_: minima :param max_: maxima
f1395:c0:m3
@property<EOL><INDENT>def path(self) -> str:<DEDENT>
path: str = ELIBConfig.config_sep_str.join(self._raw_path)<EOL>if ELIBConfig.root_path:<EOL><INDENT>prefix = ELIBConfig.config_sep_str.join(ELIBConfig.root_path)<EOL>path = ELIBConfig.config_sep_str.join((prefix, path))<EOL><DEDENT>return path<EOL>
:return: path of this config value as a string
f1396:c0:m1
@property<EOL><INDENT>def key(self) -> str:<DEDENT>
return self._raw_path[-<NUM_LIT:1>]<EOL>
:return: last component of path :rtype: str
f1396:c0:m2
@property<EOL><INDENT>def name(self) -> str:<DEDENT>
return self.path.replace('<STR_LIT>', '<STR_LIT:.>')<EOL>
:return: user friendly name of this value as a string
f1396:c0:m3
def raw_value(self) -> typing.Optional[object]:
raw_value = self._from_environ()<EOL>if raw_value is None:<EOL><INDENT>raw_value = self._from_config_file()<EOL><DEDENT>if raw_value is None:<EOL><INDENT>raw_value = self._from_default()<EOL><DEDENT>return raw_value<EOL>
:return: raw value
f1396:c0:m7
@property<EOL><INDENT>@abc.abstractmethod<EOL>def type_name(self) -> str:<DEDENT>
:return: user friendly type for this config value
f1396:c0:m11
@property<EOL><INDENT>def friendly_type_name(self) -> str:<DEDENT>
return self.type_name<EOL>
:return: friendly type name for the end-user :rtype: str
f1396:c0:m12
@property<EOL><INDENT>def type_name(self) -> str:<DEDENT>
return Types.string<EOL>
:return: user friendly type for this config value
f1397:c0:m0
@property<EOL><INDENT>def type_name(self) -> str:<DEDENT>
return Types.integer<EOL>
:return: user friendly type for this config value
f1399:c0:m1
def set_limits(self, min_=None, max_=None):
self._min, self._max = min_, max_<EOL>
Sets limits for this config value If the resulting integer is outside those limits, an exception will be raised :param min_: minima :param max_: maxima
f1399:c0:m5
@property<EOL><INDENT>def type_name(self) -> str:<DEDENT>
return Types.array<EOL>
:return: user friendly type for this config value
f1401:c0:m0
@property<EOL><INDENT>def friendly_type_name(self) -> str:<DEDENT>
return f'<STR_LIT>'<EOL>
:return: user friendly type for this config value
f1401:c0:m1
@property<EOL><INDENT>@abc.abstractmethod<EOL>def key(self) -> str:<DEDENT>
:return: last component of path :rtype: str
f1402:c0:m0
@property<EOL><INDENT>@abc.abstractmethod<EOL>def friendly_type_name(self) -> str:<DEDENT>
:return: friendly type name for the end-user :rtype: str
f1402:c0:m1
def add_to_toml_obj(self, toml_obj: tomlkit.container.Container, not_set: str):
self._toml_add_description(toml_obj)<EOL>self._toml_add_value_type(toml_obj)<EOL>self._toml_add_comments(toml_obj)<EOL>toml_obj.add(tomlkit.comment('<STR_LIT>'))<EOL>self._toml_add_value(toml_obj, not_set)<EOL>
Updates the given container in-place with this ConfigValue :param toml_obj: container to update :type toml_obj: tomlkit.container.Containers :param not_set: random UUID used to denote a value that has no default :type not_set: str
f1402:c0:m8
def _ensure_config_file_exists():
config_file = Path(ELIBConfig.config_file_path).absolute()<EOL>if not config_file.exists():<EOL><INDENT>raise ConfigFileNotFoundError(ELIBConfig.config_file_path)<EOL><DEDENT>
Makes sure the config file exists. :raises: :class:`epab.core.new_config.exc.ConfigFileNotFoundError`
f1403:m0
def read_config_file() -> typing.MutableMapping[str, typing.Any]:
return _read_file()<EOL>
Reads configuration from the disk. :return: configuration dictionary. :raises MissingConfigPackageError: raised if ``package`` is not ``None`` and it doesn't exist at the top level of the config file.
f1403:m3
def _aggregate_config_values(config_values: typing.List[ConfigValue]) -> dict:
_keys: defaultdict = _nested_default_dict()<EOL>_sorted_values = sorted(config_values, key=lambda x: x.name)<EOL>for value in _sorted_values:<EOL><INDENT>value_keys = value.path.split(ELIBConfig.config_sep_str)<EOL>this_config_key = _keys<EOL>for sub_key in value_keys[:-<NUM_LIT:1>]:<EOL><INDENT>this_config_key = this_config_key[sub_key]<EOL><DEDENT>this_config_key[value_keys[-<NUM_LIT:1>]] = value<EOL><DEDENT>return _default_dict_to_dict(_keys)<EOL>
Returns a (sorted) :param config_values: :type config_values: :return: :rtype:
f1406:m3
def write_example_config(example_file_path: str):
document = tomlkit.document()<EOL>for header_line in _get_header():<EOL><INDENT>document.add(tomlkit.comment(header_line))<EOL><DEDENT>config_keys = _aggregate_config_values(ConfigValue.config_values)<EOL>_add_config_values_to_toml_object(document, config_keys)<EOL>_doc_as_str = document.as_string().replace(f'<STR_LIT>', '<STR_LIT>')<EOL>with open(example_file_path, '<STR_LIT:w>') as stream:<EOL><INDENT>stream.write(_doc_as_str)<EOL><DEDENT>
Writes an example config file using the config values declared so far :param example_file_path: path to write to
f1406:m5
def validate_config(raise_=True):
ELIBConfig.check()<EOL>known_paths = set()<EOL>duplicate_values = set()<EOL>missing_values = set()<EOL>for config_value in ConfigValue.config_values:<EOL><INDENT>if config_value.path not in known_paths:<EOL><INDENT>known_paths.add(config_value.path)<EOL><DEDENT>else:<EOL><INDENT>duplicate_values.add(config_value.name)<EOL><DEDENT>try:<EOL><INDENT>config_value()<EOL><DEDENT>except MissingValueError:<EOL><INDENT>missing_values.add(config_value.name)<EOL><DEDENT><DEDENT>if raise_ and duplicate_values:<EOL><INDENT>raise DuplicateConfigValueError(str(duplicate_values))<EOL><DEDENT>if raise_ and missing_values:<EOL><INDENT>raise MissingValueError(str(missing_values), '<STR_LIT>')<EOL><DEDENT>return duplicate_values, missing_values<EOL>
Verifies that all configuration values have a valid setting
f1411:m0
@classmethod<EOL><INDENT>def check(cls):<DEDENT>
attribs = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>]<EOL>for attrib in attribs:<EOL><INDENT>if getattr(cls, attrib) == '<STR_LIT>':<EOL><INDENT>raise IncompleteSetupError(f'<STR_LIT>')<EOL><DEDENT><DEDENT>
Verifies that all necessary values for the package to be used have been provided :raises: `elib_config._exc.IncompleteSetupError`
f1412:c0:m0
@classmethod<EOL><INDENT>def setup(<EOL>cls,<EOL>app_version: str,<EOL>app_name: str,<EOL>config_file_path: str,<EOL>config_sep_str: str,<EOL>root_path: typing.Optional[typing.List[str]] = None,<EOL>):<DEDENT>
cls.app_version = app_version<EOL>cls.app_name = app_name<EOL>cls.config_file_path = config_file_path<EOL>cls.config_sep_str = config_sep_str<EOL>cls.root_path = root_path<EOL>
Configures elib_config in one fell swoop :param app_version: version of the application :param app_name:name of the application :param config_file_path: path to the config file to use :param config_sep_str: separator for config values paths :param root_path: list of strings that will be pre-pended to *all* config values paths (useful to setup a prefix for the whole app)
f1412:c0:m1
def friendly_type_name(raw_type: typing.Type) -> str:
try:<EOL><INDENT>return _TRANSLATE_TYPE[raw_type]<EOL><DEDENT>except KeyError:<EOL><INDENT>LOGGER.error('<STR_LIT>', raw_type)<EOL>return str(raw_type)<EOL><DEDENT>
Returns a user-friendly type name :param raw_type: raw type (str, int, ...) :return: user friendly type as string
f1414:m0
def read_local_files(*file_paths: str) -> str:
def _read_single_file(file_path):<EOL><INDENT>with open(file_path) as f:<EOL><INDENT>filename = os.path.splitext(file_path)[<NUM_LIT:0>]<EOL>title = f'<STR_LIT>'<EOL>return '<STR_LIT>'.join((title, f.read()))<EOL><DEDENT><DEDENT>return '<STR_LIT:\n>' + '<STR_LIT>'.join(map(_read_single_file, file_paths))<EOL>
Reads one or more text files and returns them joined together. A title is automatically created based on the file name. Args: *file_paths: list of files to aggregate Returns: content of files
f1415:m0
def constant_succeed_validator():
return validator(lambda _: True)<EOL>
Returns validator that always succeeds
f1417:m1
def constant_fail_validator(message):
return validator(lambda _: False, message)<EOL>
Returns validator that always fails with given message
f1417:m2
def is_odd_validator():
return validator(lambda x: x % <NUM_LIT:2> == <NUM_LIT:1>, is_odd_validator.message)<EOL>
Returns validator that checks if integer is odd
f1417:m3
def divisible_by_validator(n):
return Predicate(lambda x: x % n == <NUM_LIT:0>, '<STR_LIT>' % n)<EOL>
Returns validator that checks if integer is divisible by given `n`
f1417:m4
def merge_errors(errors1, errors2):
if errors1 is None:<EOL><INDENT>return errors2<EOL><DEDENT>elif errors2 is None:<EOL><INDENT>return errors1<EOL><DEDENT>if isinstance(errors1, list):<EOL><INDENT>if not errors1:<EOL><INDENT>return errors2<EOL><DEDENT>if isinstance(errors2, list):<EOL><INDENT>return errors1 + errors2<EOL><DEDENT>elif isinstance(errors2, dict):<EOL><INDENT>return dict(<EOL>errors2,<EOL>**{SCHEMA: merge_errors(errors1, errors2.get(SCHEMA))}<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return errors1 + [errors2]<EOL><DEDENT><DEDENT>elif isinstance(errors1, dict):<EOL><INDENT>if isinstance(errors2, list):<EOL><INDENT>return dict(<EOL>errors1,<EOL>**{SCHEMA: merge_errors(errors1.get(SCHEMA), errors2)}<EOL>)<EOL><DEDENT>elif isinstance(errors2, dict):<EOL><INDENT>errors = dict(errors1)<EOL>for k, v in iteritems(errors2):<EOL><INDENT>if k in errors:<EOL><INDENT>errors[k] = merge_errors(errors[k], v)<EOL><DEDENT>else:<EOL><INDENT>errors[k] = v<EOL><DEDENT><DEDENT>return errors<EOL><DEDENT>else:<EOL><INDENT>return dict(<EOL>errors1,<EOL>**{SCHEMA: merge_errors(errors1.get(SCHEMA), errors2)}<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(errors2, list):<EOL><INDENT>return [errors1] + errors2 if errors2 else errors1<EOL><DEDENT>elif isinstance(errors2, dict):<EOL><INDENT>return dict(<EOL>errors2,<EOL>**{SCHEMA: merge_errors(errors1, errors2.get(SCHEMA))}<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return [errors1, errors2]<EOL><DEDENT><DEDENT>
Deeply merges two error messages. Error messages can be string, list of strings or dict of error messages (recursively). Format is the same as accepted by :exc:`ValidationError`. Returns new error messages.
f1421:m0
def add_error(self, path, error):
self.errors = merge_errors(self.errors, self._make_error(path, error))<EOL>
Add error message for given field path. Example: :: builder = ValidationErrorBuilder() builder.add_error('foo.bar.baz', 'Some error') print builder.errors # => {'foo': {'bar': {'baz': 'Some error'}}} :param str path: '.'-separated list of field names :param str error: Error message
f1421:c2:m2
def add_errors(self, errors):
self.errors = merge_errors(self.errors, errors)<EOL>
Add errors in dict format. Example: :: builder = ValidationErrorBuilder() builder.add_errors({'foo': {'bar': 'Error 1'}}) builder.add_errors({'foo': {'baz': 'Error 2'}, 'bam': 'Error 3'}) print builder.errors # => {'foo': {'bar': 'Error 1', 'baz': 'Error 2'}, 'bam': 'Error 3'} :param str, list or dict errors: Errors to merge
f1421:c2:m3
def raise_errors(self):
if self.errors:<EOL><INDENT>raise ValidationError(self.errors)<EOL><DEDENT>
Raise :exc:`ValidationError` if errors are not empty; do nothing otherwise.
f1421:c2:m4
def __call__(self, value, context=None):
raise NotImplemented()<EOL>
Validate value. In case of errors, raise :exc:`~lollipop.errors.ValidationError`. Return value is always ignored.
f1422:c0:m0
def type_name_hint(data):
return data.__class__.__name__<EOL>
Returns type name of given value. To be used as a type hint in :class:`OneOf`.
f1425:m0
def dict_value_hint(key, mapper=None):
if mapper is None:<EOL><INDENT>mapper = identity<EOL><DEDENT>def hinter(data):<EOL><INDENT>return mapper(data.get(key))<EOL><DEDENT>return hinter<EOL>
Returns a function that takes a dictionary and returns value of particular key. The returned value can be optionally processed by `mapper` function. To be used as a type hint in :class:`OneOf`.
f1425:m1
def validated_type(base_type, name=None, validate=None):
if validate is None:<EOL><INDENT>validate = []<EOL><DEDENT>if not is_sequence(validate):<EOL><INDENT>validate = [validate]<EOL><DEDENT>class ValidatedSubtype(base_type):<EOL><INDENT>if name is not None:<EOL><INDENT>__name__ = name<EOL><DEDENT>def __init__(self, *args, **kwargs):<EOL><INDENT>super(ValidatedSubtype, self).__init__(*args, **kwargs)<EOL>for validator in reversed(validate):<EOL><INDENT>self.validators.insert(<NUM_LIT:0>, validator)<EOL><DEDENT><DEDENT><DEDENT>return ValidatedSubtype<EOL>
Convenient way to create a new type by adding validation to existing type. Example: :: Ipv4Address = validated_type( String, 'Ipv4Address', # regexp simplified for demo purposes Regexp('^\d+\.\d+\.\d+\.\d+$', error='Invalid IP address') ) Percentage = validated_type(Integer, validate=Range(0, 100)) # The above is the same as class Ipv4Address(String): def __init__(self, *args, **kwargs): super(Ipv4Address, self).__init__(*args, **kwargs) self.validators.insert(0, Regexp('^\d+\.\d+\.\d+\.\d+$', error='Invalid IP address')) class Percentage(Integer): def __init__(self, *args, **kwargs): super(Percentage, self).__init__(*args, **kwargs) self.validators.insert(0, Range(0, 100)) :param Type base_type: Base type for a new type. :param name str: Optional class name for new type (will be shown in places like repr). :param validate: A validator or list of validators for this data type. See `Type.validate` for details.
f1425:m3
def validate(self, data, context=None):
try:<EOL><INDENT>self.load(data, context)<EOL>return None<EOL><DEDENT>except ValidationError as ve:<EOL><INDENT>return ve.messages<EOL><DEDENT>
Takes serialized data and returns validation errors or None. :param data: Data to validate. :param context: Context data. :returns: validation errors or None
f1425:c2:m1
def load(self, data, context=None):
errors_builder = ValidationErrorBuilder()<EOL>for validator in self.validators:<EOL><INDENT>try:<EOL><INDENT>validator(data, context)<EOL><DEDENT>except ValidationError as ve:<EOL><INDENT>errors_builder.add_errors(ve.messages)<EOL><DEDENT><DEDENT>errors_builder.raise_errors()<EOL>return data<EOL>
Deserialize data from primitive types. Raises :exc:`~lollipop.errors.ValidationError` if data is invalid. :param data: Data to deserialize. :param context: Context data. :returns: Loaded data :raises: :exc:`~lollipop.errors.ValidationError`
f1425:c2:m2
def dump(self, value, context=None):
return value<EOL>
Serialize data to primitive types. Raises :exc:`~lollipop.errors.ValidationError` if data is invalid. :param value: Value to serialize. :param context: Context data. :returns: Serialized data. :raises: :exc:`~lollipop.errors.ValidationError`
f1425:c2:m3
def get_value(self, name, obj, context=None):
raise NotImplemented()<EOL>
Get value of field `name` from object `obj`. :params str name: Field name. :params obj: Object to get field value from. :returns: Field value.
f1425:c17:m1