INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
send_registration_mail ( email * request ** kwargs ) Sends the registration mail
def send_registration_mail(email, *, request, **kwargs): """send_registration_mail(email, *, request, **kwargs) Sends the registration mail * ``email``: The email address where the registration link should be sent to. * ``request``: A HTTP request instance, used to construct the complete UR...
decode ( code * max_age ) Decodes the code from the registration link and returns a tuple consisting of the verified email address and the payload which was passed through to get_confirmation_code.
def decode(code, *, max_age): """decode(code, *, max_age) Decodes the code from the registration link and returns a tuple consisting of the verified email address and the payload which was passed through to ``get_confirmation_code``. The maximum age in seconds of the link has to be specified as ``m...
do_some_work
def do_some_work( self, work_dict): """do_some_work :param work_dict: dictionary for key/values """ label = "do_some_work" log.info(("task - {} - start " "work_dict={}") .format(label, work_dict)) ret_data = { "job_resul...
Builds route53 record entries enabling DNS names for services Note: gcdt. route53 create_record ( awsclient... ) is used in dataplatform cloudformation. py templates!
def create_record(awsclient, name_prefix, instance_reference, type="A", host_zone_name=None): """ Builds route53 record entries enabling DNS names for services Note: gcdt.route53 create_record(awsclient, ...) is used in dataplatform cloudformation.py templates! :param name_prefix: The sub domain pr...
Use service discovery to get the host zone name from the default stack
def _retrieve_stack_host_zone_name(awsclient, default_stack_name=None): """ Use service discovery to get the host zone name from the default stack :return: Host zone name as string """ global _host_zone_name if _host_zone_name is not None: return _host_zone_name env = get_env() ...
Load and register installed gcdt plugins.
def load_plugins(group='gcdt10'): """Load and register installed gcdt plugins. """ # on using entrypoints: # http://stackoverflow.com/questions/774824/explain-python-entry-points # TODO: make sure we do not have conflicting generators installed! for ep in pkg_resources.iter_entry_points(group, n...
Load and register installed gcdt plugins.
def get_plugin_versions(group='gcdt10'): """Load and register installed gcdt plugins. """ versions = {} for ep in pkg_resources.iter_entry_points(group, name=None): versions[ep.dist.project_name] = ep.dist.version return versions
Delete the specified log group
def delete_log_group(awsclient, log_group_name): """Delete the specified log group :param log_group_name: log group name :return: """ client_logs = awsclient.get_client('logs') response = client_logs.delete_log_group( logGroupName=log_group_name )
Sets the retention of the specified log group if the log group does not yet exist than it will be created first.
def put_retention_policy(awsclient, log_group_name, retention_in_days): """Sets the retention of the specified log group if the log group does not yet exist than it will be created first. :param log_group_name: log group name :param retention_in_days: log group name :return: """ try: ...
Note: this is used to retrieve logs in ramuda.
def filter_log_events(awsclient, log_group_name, start_ts, end_ts=None): """ Note: this is used to retrieve logs in ramuda. :param log_group_name: log group name :param start_ts: timestamp :param end_ts: timestamp :return: list of log entries """ client_logs = awsclient.get_client('logs...
Get info on the specified log group
def describe_log_group(awsclient, log_group_name): """Get info on the specified log group :param log_group_name: log group name :return: """ client_logs = awsclient.get_client('logs') request = { 'logGroupNamePrefix': log_group_name, 'limit': 1 } response = client_logs....
Get info on the specified log stream
def describe_log_stream(awsclient, log_group_name, log_stream_name): """Get info on the specified log stream :param log_group_name: log group name :param log_stream_name: log stream :return: """ client_logs = awsclient.get_client('logs') response = client_logs.describe_log_streams( ...
Creates a log group with the specified name.
def create_log_group(awsclient, log_group_name): """Creates a log group with the specified name. :param log_group_name: log group name :return: """ client_logs = awsclient.get_client('logs') response = client_logs.create_log_group( logGroupName=log_group_name, )
Creates a log stream for the specified log group.
def create_log_stream(awsclient, log_group_name, log_stream_name): """Creates a log stream for the specified log group. :param log_group_name: log group name :param log_stream_name: log stream name :return: """ client_logs = awsclient.get_client('logs') response = client_logs.create_log_st...
Put log events for the specified log group and stream.
def put_log_events(awsclient, log_group_name, log_stream_name, log_events, sequence_token=None): """Put log events for the specified log group and stream. :param log_group_name: log group name :param log_stream_name: log stream name :param log_events: [{'timestamp': 123, 'message': '...
Get log events for the specified log group and stream. this is used in tenkai output instance diagnostics
def get_log_events(awsclient, log_group_name, log_stream_name, start_ts=None): """Get log events for the specified log group and stream. this is used in tenkai output instance diagnostics :param log_group_name: log group name :param log_stream_name: log stream name :param start_ts: timestamp :r...
Check
def check_log_stream_exists(awsclient, log_group_name, log_stream_name): """Check :param log_group_name: log group name :param log_stream_name: log stream name :return: True / False """ lg = describe_log_group(awsclient, log_group_name) if lg and lg['logGroupName'] == log_group_name: ...
Convert unix timestamp ( millis ) into date & time we use in logs output.
def decode_format_timestamp(timestamp): """Convert unix timestamp (millis) into date & time we use in logs output. :param timestamp: unix timestamp in millis :return: date, time in UTC """ dt = maya.MayaDT(timestamp / 1000).datetime(naive=True) return dt.strftime('%Y-%m-%d'), dt.strftime('%H:%M...
Reload the configuration from disk returning True if the configuration has changed from the previous values.
def reload(self): """Reload the configuration from disk returning True if the configuration has changed from the previous values. """ config = self._default_configuration() if self._file_path: config.update(self._load_config_file()) if config != self._values:...
Load the configuration file into memory returning the content.
def _load_config_file(self): """Load the configuration file into memory, returning the content. """ LOGGER.info('Loading configuration from %s', self._file_path) if self._file_path.endswith('json'): config = self._load_json_config() else: config = self._l...
Load the configuration file in JSON format
def _load_json_config(self): """Load the configuration file in JSON format :rtype: dict """ try: return json.loads(self._read_config()) except ValueError as error: raise ValueError( 'Could not read configuration file: {}'.format(error))
Loads the configuration file from a. yaml or. yml file
def _load_yaml_config(self): """Loads the configuration file from a .yaml or .yml file :type: dict """ try: config = self._read_config() except OSError as error: raise ValueError('Could not read configuration file: %s' % error) try: r...
Normalize the file path value.
def _normalize_file_path(file_path): """Normalize the file path value. :param str file_path: The file path as passed in :rtype: str """ if not file_path: return None elif file_path.startswith('s3://') or \ file_path.startswith('http://') or \...
Read the configuration from the various places it may be read from.
def _read_config(self): """Read the configuration from the various places it may be read from. :rtype: str :raises: ValueError """ if not self._file_path: return None elif self._file_path.startswith('s3://'): return self._read_s3_config() ...
Read a remote config via URL.
def _read_remote_config(self): """Read a remote config via URL. :rtype: str :raises: ValueError """ try: import requests except ImportError: requests = None if not requests: raise ValueError( 'Remote config URL...
Read in the value of the configuration file in Amazon S3.
def _read_s3_config(self): """Read in the value of the configuration file in Amazon S3. :rtype: str :raises: ValueError """ try: import boto3 import botocore.exceptions except ImportError: boto3, botocore = None, None if not ...
Update the internal configuration values removing debug_only handlers if debug is False. Returns True if the configuration has changed from previous configuration values.
def update(self, configuration, debug=None): """Update the internal configuration values, removing debug_only handlers if debug is False. Returns True if the configuration has changed from previous configuration values. :param dict configuration: The logging configuration :param...
Configure the Python stdlib logger
def configure(self): """Configure the Python stdlib logger""" if self.debug is not None and not self.debug: self._remove_debug_handlers() self._remove_debug_only() logging.config.dictConfig(self.config) try: logging.captureWarnings(True) except Att...
Remove any handlers with an attribute of debug_only that is True and remove the references to said handlers from any loggers that are referencing them.
def _remove_debug_handlers(self): """Remove any handlers with an attribute of debug_only that is True and remove the references to said handlers from any loggers that are referencing them. """ remove = list() for handler in self.config[self.HANDLERS]: if self...
Iterate through each handler removing the invalid dictConfig key of debug_only.
def _remove_debug_only(self): """Iterate through each handler removing the invalid dictConfig key of debug_only. """ LOGGER.debug('Removing debug only from handlers') for handler in self.config[self.HANDLERS]: if self.DEBUG_ONLY in self.config[self.HANDLERS][handler]...
Convert this object to a dictionary with formatting appropriate for a PIF.
def as_dictionary(self): """ Convert this object to a dictionary with formatting appropriate for a PIF. :returns: Dictionary with the content of this object formatted for a PIF. """ return {to_camel_case(i): Serializable._convert_to_dictionary(self.__dict__[i]) f...
Convert obj to a dictionary with formatting appropriate for a PIF. This function attempts to treat obj as a Pio object and otherwise returns obj.
def _convert_to_dictionary(obj): """ Convert obj to a dictionary with formatting appropriate for a PIF. This function attempts to treat obj as a Pio object and otherwise returns obj. :param obj: Object to convert to a dictionary. :returns: Input object as a dictionary or the ori...
Helper function that returns an object or if it is a dictionary initializes it from class_.
def _get_object(class_, obj): """ Helper function that returns an object, or if it is a dictionary, initializes it from class_. :param class_: Class to use to instantiate object. :param obj: Object to process. :return: One or more objects. """ if isinstance(obj, ...
Calculates the damping factor for sound in dB/ m depending on temperature humidity and sound frequency. Source: http:// www. sengpielaudio. com/ LuftdaempfungFormel. htm
def damping(temp, relhum, freq, pres=101325): """ Calculates the damping factor for sound in dB/m depending on temperature, humidity and sound frequency. Source: http://www.sengpielaudio.com/LuftdaempfungFormel.htm temp: Temperature in degrees celsius relhum: Relative humidity as percentage, e....
Calculates the total sound pressure level based on multiple source levels
def total_level(source_levels): """ Calculates the total sound pressure level based on multiple source levels """ sums = 0.0 for l in source_levels: if l is None: continue if l == 0: continue sums += pow(10.0, float(l) / 10.0) level = 10.0 * math.l...
Calculates the A - rated total sound pressure level based on octave band frequencies
def total_rated_level(octave_frequencies): """ Calculates the A-rated total sound pressure level based on octave band frequencies """ sums = 0.0 for band in OCTAVE_BANDS.keys(): if band not in octave_frequencies: continue if octave_frequencies[band] is None: ...
Calculates the energy - equivalent ( Leq3 ) value given a regular measurement interval.
def leq3(levels): """ Calculates the energy-equivalent (Leq3) value given a regular measurement interval. """ n = float(len(levels)) sums = 0.0 if sum(levels) == 0.0: return 0.0 for l in levels: if l == 0: continue sums += pow(10.0, float(l) / 10.0) ...
Calculates the sound pressure level in dependence of a distance where a perfect ball - shaped source and spread is assumed.
def distant_level(reference_level, distance, reference_distance=1.0): """ Calculates the sound pressure level in dependence of a distance where a perfect ball-shaped source and spread is assumed. reference_level: Sound pressure level in reference distance in dB distance: Distance to calculate s...
Calculates the damped A - rated total sound pressure level in a given distance temperature and relative humidity from octave frequency sound pressure levels in a reference distance
def distant_total_damped_rated_level( octave_frequencies, distance, temp, relhum, reference_distance=1.0): """ Calculates the damped, A-rated total sound pressure level in a given distance, temperature and relative humidity from octave frequenc...
ASRS [ Ra ] Ra Rc ASRS [ Ra ] Rb #imm5_counting
def ASRS(self, params): """ ASRS [Ra,] Ra, Rc ASRS [Ra,] Rb, #imm5_counting Arithmetic shift right Rb by Rc or imm5_counting and store the result in Ra imm5 counting is [1, 32] In the register shift, the first two operands must be the same register Ra, Rb, and Rc...
LSLS [ Ra ] Ra Rc LSLS [ Ra ] Rb #imm5
def LSLS(self, params): """ LSLS [Ra,] Ra, Rc LSLS [Ra,] Rb, #imm5 Logical shift left Rb by Rc or imm5 and store the result in Ra imm5 is [0, 31] In the register shift, the first two operands must be the same register Ra, Rb, and Rc must be low registers ...
LSRS [ Ra ] Ra Rc LSRS [ Ra ] Rb #imm5_counting
def LSRS(self, params): """ LSRS [Ra,] Ra, Rc LSRS [Ra,] Rb, #imm5_counting Logical shift right Rb by Rc or imm5 and store the result in Ra imm5 counting is [1, 32] In the register shift, the first two operands must be the same register Ra, Rb, and Rc must be low...
RORS [ Ra ] Ra Rc
def RORS(self, params): """ RORS [Ra,] Ra, Rc Rotate shift right Rb by Rc or imm5 and store the result in Ra The first two operands must be the same register Ra and Rc must be low registers The first register is optional """ # This instruction allows for ...
解析话题列表: internal: param xml: 页面XML: param tds: 每列的含义,可以是title created comment group updated author time rec: param selector: 表在页面中的位置: return:
def _parse_topic_table(self, xml, tds='title,created,comment,group', selector='//table[@class="olt"]//tr'): """ 解析话题列表 :internal :param xml: 页面XML :param tds: 每列的含义,可以是title, created, comment, group, updated, author, time, rec :param selector: 表在页面中的位置 :...
搜索小组: param keyword: 搜索的关键字: param start: 翻页: return: 含总数的列表
def search_groups(self, keyword, start=0): """ 搜索小组 :param keyword: 搜索的关键字 :param start: 翻页 :return: 含总数的列表 """ xml = self.api.xml(API_GROUP_SEARCH_GROUPS % (start, keyword)) xml_results = xml.xpath('//div[@class="groups"]/div[@class="result"]') ...
已加入的小组列表: param user_alias: 用户名,默认为当前用户名: return: 单页列表
def list_joined_groups(self, user_alias=None): """ 已加入的小组列表 :param user_alias: 用户名,默认为当前用户名 :return: 单页列表 """ xml = self.api.xml(API_GROUP_LIST_JOINED_GROUPS % (user_alias or self.api.user_alias)) xml_results = xml.xpath('//div[@class="group-list group-ca...
加入小组: param group_alias: 小组ID: param message: 如果要验证,留言信息: return: 枚举 - joined: 加入成功 - waiting: 等待审核 - initial: 加入失败
def join_group(self, group_alias, message=None): """ 加入小组 :param group_alias: 小组ID :param message: 如果要验证,留言信息 :return: 枚举 - joined: 加入成功 - waiting: 等待审核 - initial: 加入失败 """ xml = self.api.xml(API_GROUP_GROUP...
退出小组: param group_alias: 小组ID: return:
def leave_group(self, group_alias): """ 退出小组 :param group_alias: 小组ID :return: """ return self.api.req(API_GROUP_GROUP_HOME % group_alias, params={ 'action': 'quit', 'ck': self.api.ck(), })
搜索话题: param keyword: 关键字: param sort: 排序方式 relevance/ newest: param start: 翻页: return: 带总数的列表
def search_topics(self, keyword, sort='relevance', start=0): """ 搜索话题 :param keyword: 关键字 :param sort: 排序方式 relevance/newest :param start: 翻页 :return: 带总数的列表 """ xml = self.api.xml(API_GROUP_SEARCH_TOPICS % (start, sort, keyword)) return b...
小组内话题列表: param group_alias: 小组ID: param _type: 类型 默认最新,hot: 最热: param start: 翻页: return: 带下一页的列表
def list_topics(self, group_alias, _type='', start=0): """ 小组内话题列表 :param group_alias: 小组ID :param _type: 类型 默认最新,hot:最热 :param start: 翻页 :return: 带下一页的列表 """ xml = self.api.xml(API_GROUP_LIST_GROUP_TOPICS % group_alias, params={ 'star...
已加入的所有小组的话题列表: param start: 翻页: return: 带下一页的列表
def list_joined_topics(self, start=0): """ 已加入的所有小组的话题列表 :param start: 翻页 :return: 带下一页的列表 """ xml = self.api.xml(API_GROUP_HOME, params={'start': start}) return build_list_result(self._parse_topic_table(xml, 'title,comment,created,group'), xml)
发表的话题: param start: 翻页: return: 带下一页的列表
def list_user_topics(self, start=0): """ 发表的话题 :param start: 翻页 :return: 带下一页的列表 """ xml = self.api.xml(API_GROUP_LIST_USER_PUBLISHED_TOPICS % self.api.user_alias, params={'start': start}) return build_list_result(self._parse_topic_table(xml, 'title,comme...
回复过的话题列表: param start: 翻页: return: 带下一页的列表
def list_commented_topics(self, start=0): """ 回复过的话题列表 :param start: 翻页 :return: 带下一页的列表 """ xml = self.api.xml(API_GROUP_LIST_USER_COMMENTED_TOPICS % self.api.user_alias, params={'start': start}) return build_list_result(self._parse_topic_table(xml, 'tit...
喜欢过的话题: param user_alias: 指定用户,默认当前: param start: 翻页: return: 带下一页的列表
def list_liked_topics(self, user_alias=None, start=0): """ 喜欢过的话题 :param user_alias: 指定用户,默认当前 :param start: 翻页 :return: 带下一页的列表 """ user_alias = user_alias or self.api.user_alias xml = self.api.xml(API_GROUP_LIST_USER_LIKED_TOPICS % user_alias, p...
推荐的话题列表: param user_alias: 指定用户,默认当前: param start: 翻页: return: 带下一页的列表
def list_reced_topics(self, user_alias=None, start=0): """ 推荐的话题列表 :param user_alias: 指定用户,默认当前 :param start: 翻页 :return: 带下一页的列表 """ user_alias = user_alias or self.api.user_alias xml = self.api.xml(API_GROUP_LIST_USER_RECED_TOPICS % user_alias, ...
创建话题(小心验证码~): param group_alias: 小组ID: param title: 标题: param content: 内容: return: bool
def add_topic(self, group_alias, title, content): """ 创建话题(小心验证码~) :param group_alias: 小组ID :param title: 标题 :param content: 内容 :return: bool """ xml = self.api.req(API_GROUP_ADD_TOPIC % group_alias, 'post', data={ 'ck': self.api.ck(),...
删除话题(需要先删除所有评论,使用默认参数): param topic_id: 话题ID: return: None
def remove_topic(self, topic_id): """ 删除话题(需要先删除所有评论,使用默认参数) :param topic_id: 话题ID :return: None """ comment_start = 0 while comment_start is not None: comments = self.list_comments(topic_id, comment_start) for comment in comments[...
更新话题: param topic_id: 话题ID: param title: 标题: param content: 内容: return: bool
def update_topic(self, topic_id, title, content): """ 更新话题 :param topic_id: 话题ID :param title: 标题 :param content: 内容 :return: bool """ xml = self.api.req(API_GROUP_UPDATE_TOPIC % topic_id, 'post', data={ 'ck': self.api.ck(), ...
回复列表: param topic_id: 话题ID: param start: 翻页: return: 带下一页的列表
def list_comments(self, topic_id, start=0): """ 回复列表 :param topic_id: 话题ID :param start: 翻页 :return: 带下一页的列表 """ xml = self.api.xml(API_GROUP_GET_TOPIC % topic_id, params={'start': start}) xml_results = xml.xpath('//ul[@id="comments"]/li') ...
添加评论: param topic_id: 话题ID: param content: 内容: param reply_id: 回复ID: return: None
def add_comment(self, topic_id, content, reply_id=None): """ 添加评论 :param topic_id: 话题ID :param content: 内容 :param reply_id: 回复ID :return: None """ return self.api.req(API_GROUP_ADD_COMMENT % topic_id, 'post', data={ 'ck': self.api.ck()...
删除评论(自己发的话题所有的都可以删除,否则只能删自己发的): param topic_id: 话题ID: param comment_id: 评论ID: param reason: 原因 0/ 1/ 2 (内容不符/ 反动/ 其它): param other: 其它原因的具体 ( 2 ): return: None
def remove_comment(self, topic_id, comment_id, reason='0', other=None): """ 删除评论(自己发的话题所有的都可以删除,否则只能删自己发的) :param topic_id: 话题ID :param comment_id: 评论ID :param reason: 原因 0/1/2 (内容不符/反动/其它) :param other: 其它原因的具体(2) :return: None """ params...
列出用户在话题下的所有回复: param topic_id: 话题ID: param user_alias: 用户ID,默认当前: return: 纯列表
def list_user_comments(self, topic_id, user_alias=None): """ 列出用户在话题下的所有回复 :param topic_id: 话题ID :param user_alias: 用户ID,默认当前 :return: 纯列表 """ user_alias = user_alias or self.api.user_alias comment_start = 0 results = [] while comm...
删除回复的话题(删除所有自己发布的评论): param topic_id: 话题ID: return: None
def remove_commented_topic(self, topic_id): """ 删除回复的话题(删除所有自己发布的评论) :param topic_id: 话题ID :return: None """ return [self.remove_comment(topic_id, item['id']) for item in self.list_user_comments(topic_id)]
Creates a new: class: Shell with a function as callback. This works otherwise the same as: func: command just that the cls parameter is set to: class: Shell.
def shell(name=None, **attrs): """Creates a new :class:`Shell` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Shell`. """ attrs.setdefault('cls', Shell) return click.command(name, **attrs)
This is used by gcdt plugins to get a logger with the right level.
def getLogger(name): """This is used by gcdt plugins to get a logger with the right level.""" logger = logging.getLogger(name) # note: the level might be adjusted via '-v' option logger.setLevel(logging_config['loggers']['gcdt']['level']) return logger
Discovers methods in the XML - RPC API and creates attributes for them on this object. Enables stuff like magento. cart. create (... ) to work without having to define Python methods for each XML - RPC equivalent.
def _discover(self): """Discovers methods in the XML-RPC API and creates attributes for them on this object. Enables stuff like "magento.cart.create(...)" to work without having to define Python methods for each XML-RPC equivalent. """ self._resources = {} resources = se...
If the session expired logs back in.
def keep_session_alive(self): """If the session expired, logs back in.""" try: self.resources() except xmlrpclib.Fault as fault: if fault.faultCode == 5: self.login() else: raise
Prints discovered resources and their associated methods. Nice when noodling in the terminal to wrap your head around Magento s insanity.
def help(self): """Prints discovered resources and their associated methods. Nice when noodling in the terminal to wrap your head around Magento's insanity. """ print('Resources:') print('') for name in sorted(self._resources.keys()): methods = sorted(self._r...
Import the controller and run it.
def run(self): """Import the controller and run it. This mimics the processing done by :func:`helper.start` when a controller is run in the foreground. A new instance of ``self.controller`` is created and run until a keyboard interrupt occurs or the controller stops on its own ...
Scans the input path and automatically determines the optimal piece size based on ~1500 pieces ( up to MAX_PIECE_SIZE ) along with other basic info including total size ( in bytes ) the total number of files piece size ( in bytes ) and resulting number of pieces. If piece_size has already been set the custom value will...
def get_info(self): """ Scans the input path and automatically determines the optimal piece size based on ~1500 pieces (up to MAX_PIECE_SIZE) along with other basic info, including total size (in bytes), the total number of files, piece size (in bytes), and resulting numb...
Computes and stores piece data. Returns True on success False otherwise.
def generate(self, callback=None): """ Computes and stores piece data. Returns ``True`` on success, ``False`` otherwise. :param callback: progress/cancellation callable with method signature ``(filename, pieces_completed, pieces_total)``. Useful for reporting pro...
Returns the base32 info hash of the torrent. Useful for generating magnet links.
def info_hash_base32(self): """ Returns the base32 info hash of the torrent. Useful for generating magnet links. .. note:: ``generate()`` must be called first. """ if getattr(self, '_data', None): return b32encode(sha1(bencode(self._data['info'])).digest()) ...
: return: The SHA - 1 info hash of the torrent. Useful for generating magnet links.
def info_hash(self): """ :return: The SHA-1 info hash of the torrent. Useful for generating magnet links. .. note:: ``generate()`` must be called first. """ if getattr(self, '_data', None): return sha1(bencode(self._data['info'])).hexdigest() else...
请求API
def req(self, url, method='get', params=None, data=None, auth=False): """ 请求API :type url: str :param url: API :type method: str :param method: HTTP METHOD :type params: dict :param params: query :type data: dict ...
请求并返回json: type url: str: param url: API: type method: str: param method: HTTP METHOD: type params: dict: param params: query: type data: dict: param data: body: rtype: dict: return:
def json(self, url, method='get', params=None, data=None): """ 请求并返回json :type url: str :param url: API :type method: str :param method: HTTP METHOD :type params: dict :param params: query :type data: di...
请求并返回xml: type url: str: param url: API: type method: str: param method: HTTP METHOD: type params: dict: param params: query: type data: dict: param data: body: rtype: html. HtmlElement: return:
def xml(self, url, method='get', params=None, data=None): """ 请求并返回xml :type url: str :param url: API :type method: str :param method: HTTP METHOD :type params: dict :param params: query :type data: dict ...
持久化会话信息
def persist(self): """ 持久化会话信息 """ with open(self.persist_file, 'w+') as f: json.dump({ 'cookies': self.cookies, 'user_alias': self.user_alias, }, f, indent=2) self.logger.debug('persist session to <%s>' % self.persist_f...
加载会话信息
def load(self): """ 加载会话信息 """ if not os.path.isfile(self.persist_file): return with open(self.persist_file, 'r') as f: cfg = json.load(f) or {} self.cookies = cfg.get('cookies', {}) self.user_alias = cfg.get('user_alias') or None ...
更新会话信息,主要是ck user_alias
def flush(self): """ 更新会话信息,主要是ck, user_alias """ if 'dbcl2' not in self.cookies: return r = self.req(API_ACCOUNT_HOME) if RE_SESSION_EXPIRE.search(r.url): return self.expire() self.cookies.update(dict(r.cookies)) self.user_alias = ...
登录: type username: str: param username: 用户名(手机号或者邮箱): type password: str: param password: 密码
def login(self, username, password): """ 登录 :type username: str :param username: 用户名(手机号或者邮箱) :type password: str :param password: 密码 """ r0 = self.req(API_HOME) time.sleep(1) cookies = dict(r0.cookies) data = { ...
如果遭遇验证码,用这个接口: type cookies: str|dict: param cookies: cookie字符串或者字典: return: self
def use(self, cookies): """ 如果遭遇验证码,用这个接口 :type cookies: str|dict :param cookies: cookie字符串或者字典 :return: self """ self.cookies = dict([item.split('=', 1) for item in re.split(r'; *', cookies)]) \ if isinstance(cookies, str) else cookies ...
登出会话: return: self
def logout(self): """ 登出会话 :return: self """ self.req(API_ACCOUNT_LOGOUT % self.ck()) self.cookies = {} self.user_alias = None self.persist()
Upload bundle and deploy to deployment group. This includes the bundle - action.
def deploy(awsclient, applicationName, deploymentGroupName, deploymentConfigName, bucket, bundlefile): """Upload bundle and deploy to deployment group. This includes the bundle-action. :param applicationName: :param deploymentGroupName: :param deploymentConfigName: :param bucket: ...
Wait until an deployment is in an steady state and output information.
def output_deployment_status(awsclient, deployment_id, iterations=100): """Wait until an deployment is in an steady state and output information. :param deployment_id: :param iterations: :return: exit_code """ counter = 0 steady_states = ['Succeeded', 'Failed', 'Stopped'] client_codedep...
stop tenkai deployment.
def stop_deployment(awsclient, deployment_id): """stop tenkai deployment. :param awsclient: :param deployment_id: """ log.info('Deployment: %s - stopping active deployment.', deployment_id) client_codedeploy = awsclient.get_client('codedeploy') response = client_codedeploy.stop_deployment(...
list deployment instances.
def _list_deployment_instances(awsclient, deployment_id): """list deployment instances. :param awsclient: :param deployment_id: """ client_codedeploy = awsclient.get_client('codedeploy') instances = [] next_token = None # TODO refactor generic exhaust_function from this while True...
instance summary.
def _get_deployment_instance_summary(awsclient, deployment_id, instance_id): """instance summary. :param awsclient: :param deployment_id: :param instance_id: return: status, last_event """ client_codedeploy = awsclient.get_client('codedeploy') request = { 'deploymentId': deploym...
Gets you the diagnostics details for the first Failed event.
def _get_deployment_instance_diagnostics(awsclient, deployment_id, instance_id): """Gets you the diagnostics details for the first 'Failed' event. :param awsclient: :param deployment_id: :param instance_id: return: None or (error_code, script_name, message, log_tail) """ client_codedeploy =...
summary
def output_deployment_summary(awsclient, deployment_id): """summary :param awsclient: :param deployment_id: """ log.info('\ndeployment summary:') log.info('%-22s %-12s %s', 'Instance ID', 'Status', 'Most recent event') for instance_id in _list_deployment_instances(awsclient, deployment_id):...
diagnostics
def output_deployment_diagnostics(awsclient, deployment_id, log_group, start_time=None): """diagnostics :param awsclient: :param deployment_id: """ headline = False for instance_id in _list_deployment_instances(awsclient, deployment_id): diagnostics = _get_deployment_instance_diagnostic...
: return:: rtype: bool
def is_type(self): """ :return: :rtype: bool """ if self.__is_type_result is not None: return self.__is_type_result self.__is_type_result = self.__is_type() return self.__is_type_result
: raises TypeError: If the value is not matched the type that the class represented.
def validate(self, error_message=None): """ :raises TypeError: If the value is not matched the type that the class represented. """ if self.is_type(): return if not error_message: error_message = "invalid value type" raise TypeError(...
: return: Converted value.: raises typepy. TypeConversionError: If the value cannot convert.
def convert(self): """ :return: Converted value. :raises typepy.TypeConversionError: If the value cannot convert. """ if self.is_type(): return self.force_convert() raise TypeConversionError( "failed to convert from {} to {}".format(t...
always_fails
def always_fails( self, work_dict): """always_fails :param work_dict: dictionary for key/values """ label = "always_fails" log.info(("task - {} - start " "work_dict={}") .format(label, work_dict)) raise Exception( wo...
Build name from prefix and name + type: param name: Name of the role/ policy: param is_policy: True if policy should be added as suffix: param prefix: True if prefix should be added: return: Joined name
def name_build(self, name, is_policy=False, prefix=True): """ Build name from prefix and name + type :param name: Name of the role/policy :param is_policy: True if policy should be added as suffix :param prefix: True if prefix should be added :return: Joined name ...
Transforms name to AWS valid characters and adds prefix and type: param name: Name of the role/ policy: param is_policy: True if policy should be added as suffix: param prefix: True if prefix should be added: return: Transformed and joined name
def name_strip(self, name, is_policy=False, prefix=True): """ Transforms name to AWS valid characters and adds prefix and type :param name: Name of the role/policy :param is_policy: True if policy should be added as suffix :param prefix: True if prefix should be added :re...
Generate policy for IAM cloudformation template: param name: Name of the policy: param statements: The rules the policy should have: param roles: The roles associated with this policy: param is_managed_policy: True if managed policy: return: Ref to new policy
def build_policy(self, name, statements, roles, is_managed_policy=False): """ Generate policy for IAM cloudformation template :param name: Name of the policy :param statements: The "rules" the policy should have :param roles: The roles associated with this policy :param i...
Generate bucket policy for S3 bucket: param bucket: The bucket to attach policy to: param name: The name of the bucket ( to generate policy name from it ): param statements: The rules the policy should have: return: Ref to new policy
def build_policy_bucket(self, bucket, name, statements): """ Generate bucket policy for S3 bucket :param bucket: The bucket to attach policy to :param name: The name of the bucket (to generate policy name from it) :param statements: The "rules" the policy should have :ret...
Generate role for IAM cloudformation template: param name: Name of role: param policies: List of policies to attach to this role ( False = none ): return: Ref to new role
def build_role(self, name, policies=False): """ Generate role for IAM cloudformation template :param name: Name of role :param policies: List of policies to attach to this role (False = none) :return: Ref to new role """ # Build role template if policies: ...
Generate S3 bucket statement: param name: Name of the bucket: param lifecycle_configuration: Additional lifecycle configuration ( default = False ): param use_plain_name: Just use the given name and do not add prefix: return: Ref to new bucket
def build_bucket(self, name, lifecycle_configuration=False, use_plain_name=False): """ Generate S3 bucket statement :param name: Name of the bucket :param lifecycle_configuration: Additional lifecycle configuration (default=False) :param use_plain_name: Just ...