index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
8,481
feapder.core.base_parser
__init__
null
def __init__(self, task_table, task_state, mysqldb=None): self._mysqldb = mysqldb or MysqlDB() # mysqldb self._task_state = task_state # mysql中任务表的state字段名 self._task_table = task_table # mysql中的任务表
(self, task_table, task_state, mysqldb=None)
8,495
feapder.core.spiders.task_spider
TaskSpider
null
class TaskSpider(TaskParser, Scheduler): def __init__( self, redis_key, task_table, task_table_type="mysql", task_keys=None, task_state="state", min_task_count=10000, check_task_interval=5, task_limit=10000, related_redis_key=None, related_batch_record=None, task_condition="", task_order_by="", thread_count=None, begin_callback=None, end_callback=None, delete_keys=(), keep_alive=None, batch_interval=0, use_mysql=True, **kwargs, ): """ @summary: 任务爬虫 必要条件 需要指定任务表,可以是redis表或者mysql表作为任务种子 redis任务种子表:zset类型。值为 {"xxx":xxx, "xxx2":"xxx2"};若为集成模式,需指定parser_name字段,如{"xxx":xxx, "xxx2":"xxx2", "parser_name":"TestTaskSpider"} mysql任务表: 任务表中必须有id及任务状态字段 如 state, 其他字段可根据爬虫需要的参数自行扩充。若为集成模式,需指定parser_name字段。 参考建表语句如下: CREATE TABLE `table_name` ( `id` int(11) NOT NULL AUTO_INCREMENT, `param` varchar(1000) DEFAULT NULL COMMENT '爬虫需要的抓取数据需要的参数', `state` int(11) DEFAULT NULL COMMENT '任务状态', `parser_name` varchar(255) DEFAULT NULL COMMENT '任务解析器的脚本类名', PRIMARY KEY (`id`), UNIQUE KEY `nui` (`param`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; --------- @param task_table: mysql中的任务表 或 redis中存放任务种子的key,zset类型 @param task_table_type: 任务表类型 支持 redis 、mysql @param task_keys: 需要获取的任务字段 列表 [] 如需指定解析的parser,则需将parser_name字段取出来。 @param task_state: mysql中任务表的任务状态字段 @param min_task_count: redis 中最少任务数, 少于这个数量会从种子表中取任务 @param check_task_interval: 检查是否还有任务的时间间隔; @param task_limit: 每次从数据库中取任务的数量 @param redis_key: 任务等数据存放在redis中的key前缀 @param thread_count: 线程数,默认为配置文件中的线程数 @param begin_callback: 爬虫开始回调函数 @param end_callback: 爬虫结束回调函数 @param delete_keys: 爬虫启动时删除的key,类型: 元组/bool/string。 支持正则; 常用于清空任务队列,否则重启时会断点续爬 @param keep_alive: 爬虫是否常驻,默认否 @param related_redis_key: 有关联的其他爬虫任务表(redis)注意:要避免环路 如 A -> B & B -> A 。 @param related_batch_record: 有关联的其他爬虫批次表(mysql)注意:要避免环路 如 A -> B & B -> A 。 related_redis_key 与 related_batch_record 选其一配置即可;用于相关联的爬虫没结束时,本爬虫也不结束 若相关连的爬虫为批次爬虫,推荐以related_batch_record配置, 若相关连的爬虫为普通爬虫,无批次表,可以以related_redis_key配置 @param task_condition: 任务条件 用于从一个大任务表中挑选出数据自己爬虫的任务,即where后的条件语句 @param task_order_by: 取任务时的排序条件 如 id desc @param batch_interval: 抓取时间间隔 默认为0 天为单位 多次启动时,只有当前时间与第一次抓取结束的时间间隔大于指定的时间间隔时,爬虫才启动 @param use_mysql: 是否使用mysql数据库 --------- @result: """ Scheduler.__init__( self, redis_key=redis_key, thread_count=thread_count, begin_callback=begin_callback, end_callback=end_callback, delete_keys=delete_keys, keep_alive=keep_alive, auto_start_requests=False, batch_interval=batch_interval, task_table=task_table, **kwargs, ) self._redisdb = RedisDB() self._mysqldb = MysqlDB() if use_mysql else None self._task_table = task_table # mysql中的任务表 self._task_keys = task_keys # 需要获取的任务字段 self._task_table_type = task_table_type if self._task_table_type == "mysql" and not self._task_keys: raise Exception("需指定任务字段 使用task_keys") self._task_state = task_state # mysql中任务表的state字段名 self._min_task_count = min_task_count # redis 中最少任务数 self._check_task_interval = check_task_interval self._task_limit = task_limit # mysql中一次取的任务数量 self._related_task_tables = [ setting.TAB_REQUESTS.format(redis_key=redis_key) ] # 自己的task表也需要检查是否有任务 if related_redis_key: self._related_task_tables.append( setting.TAB_REQUESTS.format(redis_key=related_redis_key) ) self._related_batch_record = related_batch_record self._task_condition = task_condition self._task_condition_prefix_and = task_condition and " and {}".format( task_condition ) self._task_condition_prefix_where = task_condition and " where {}".format( task_condition ) self._task_order_by = task_order_by and " order by {}".format(task_order_by) self._is_more_parsers = True # 多模版类爬虫 self.reset_task() def add_parser(self, parser, **kwargs): parser = parser( self._task_table, self._task_state, self._mysqldb, **kwargs, ) # parser 实例化 self._parsers.append(parser) def start_monitor_task(self): """ @summary: 监控任务状态 --------- --------- @result: """ if not self._parsers: # 不是多模版模式, 将自己注入到parsers,自己为模版 self._is_more_parsers = False self._parsers.append(self) elif len(self._parsers) <= 1: self._is_more_parsers = False # 添加任务 for parser in self._parsers: parser.add_task() while True: try: # 检查redis中是否有任务 任务小于_min_task_count 则从mysql中取 tab_requests = setting.TAB_REQUESTS.format(redis_key=self._redis_key) todo_task_count = self._redisdb.zget_count(tab_requests) tasks = [] if todo_task_count < self._min_task_count: tasks = self.get_task(todo_task_count) if not tasks: if not todo_task_count: if self._keep_alive: log.info("任务均已做完,爬虫常驻, 等待新任务") time.sleep(self._check_task_interval) continue elif self.have_alive_spider(): log.info("任务均已做完,但还有爬虫在运行,等待爬虫结束") time.sleep(self._check_task_interval) continue elif not self.related_spider_is_done(): continue else: log.info("任务均已做完,爬虫结束") break else: log.info("redis 中尚有%s条积压任务,暂时不派发新任务" % todo_task_count) if not tasks: if todo_task_count >= self._min_task_count: # log.info('任务正在进行 redis中剩余任务 %s' % todo_task_count) pass else: log.info("无待做种子 redis中剩余任务 %s" % todo_task_count) else: # make start requests self.distribute_task(tasks) log.info(f"添加任务到redis成功 共{len(tasks)}条") except Exception as e: log.exception(e) time.sleep(self._check_task_interval) def get_task(self, todo_task_count) -> List[Union[Tuple, Dict]]: """ 获取任务 Args: todo_task_count: redis里剩余的任务数 Returns: """ tasks = [] if self._task_table_type == "mysql": # 从mysql中取任务 log.info("redis 中剩余任务%s 数量过小 从mysql中取任务追加" % todo_task_count) tasks = self.get_todo_task_from_mysql() if not tasks: # 状态为0的任务已经做完,需要检查状态为2的任务是否丢失 # redis 中无待做任务,此时mysql中状态为2的任务为丢失任务。需重新做 if todo_task_count == 0: log.info("无待做任务,尝试取丢失的任务") tasks = self.get_doing_task_from_mysql() elif self._task_table_type == "redis": log.info("redis 中剩余任务%s 数量过小 从redis种子任务表中取任务追加" % todo_task_count) tasks = self.get_task_from_redis() else: raise Exception( f"task_table_type expect mysql or redis,bug got {self._task_table_type}" ) return tasks def distribute_task(self, tasks): """ @summary: 分发任务 --------- @param tasks: --------- @result: """ if self._is_more_parsers: # 为多模版类爬虫,需要下发指定的parser for task in tasks: for parser in self._parsers: # 寻找task对应的parser if parser.name in task: if isinstance(task, dict): task = PerfectDict(_dict=task) else: task = PerfectDict( _dict=dict(zip(self._task_keys, task)), _values=list(task), ) requests = parser.start_requests(task) if requests and not isinstance(requests, Iterable): raise Exception( "%s.%s返回值必须可迭代" % (parser.name, "start_requests") ) result_type = 1 for request in requests or []: if isinstance(request, Request): request.parser_name = request.parser_name or parser.name self._request_buffer.put_request(request) result_type = 1 elif isinstance(request, Item): self._item_buffer.put_item(request) result_type = 2 if ( self._item_buffer.get_items_count() >= setting.ITEM_MAX_CACHED_COUNT ): self._item_buffer.flush() elif callable(request): # callbale的request可能是更新数据库操作的函数 if result_type == 1: self._request_buffer.put_request(request) else: self._item_buffer.put_item(request) if ( self._item_buffer.get_items_count() >= setting.ITEM_MAX_CACHED_COUNT ): self._item_buffer.flush() else: raise TypeError( "start_requests yield result type error, expect Request、Item、callback func, bug get type: {}".format( type(requests) ) ) break else: # task没对应的parser 则将task下发到所有的parser for task in tasks: for parser in self._parsers: if isinstance(task, dict): task = PerfectDict(_dict=task) else: task = PerfectDict( _dict=dict(zip(self._task_keys, task)), _values=list(task) ) requests = parser.start_requests(task) if requests and not isinstance(requests, Iterable): raise Exception( "%s.%s返回值必须可迭代" % (parser.name, "start_requests") ) result_type = 1 for request in requests or []: if isinstance(request, Request): request.parser_name = request.parser_name or parser.name self._request_buffer.put_request(request) result_type = 1 elif isinstance(request, Item): self._item_buffer.put_item(request) result_type = 2 if ( self._item_buffer.get_items_count() >= setting.ITEM_MAX_CACHED_COUNT ): self._item_buffer.flush() elif callable(request): # callbale的request可能是更新数据库操作的函数 if result_type == 1: self._request_buffer.put_request(request) else: self._item_buffer.put_item(request) if ( self._item_buffer.get_items_count() >= setting.ITEM_MAX_CACHED_COUNT ): self._item_buffer.flush() self._request_buffer.flush() self._item_buffer.flush() def get_task_from_redis(self): tasks = self._redisdb.zget(self._task_table, count=self._task_limit) tasks = [eval(task) for task in tasks] return tasks def get_todo_task_from_mysql(self): """ @summary: 取待做的任务 --------- --------- @result: """ # TODO 分批取数据 每批最大取 1000000个,防止内存占用过大 # 查询任务 task_keys = ", ".join([f"`{key}`" for key in self._task_keys]) sql = "select %s from %s where %s = 0%s%s limit %s" % ( task_keys, self._task_table, self._task_state, self._task_condition_prefix_and, self._task_order_by, self._task_limit, ) tasks = self._mysqldb.find(sql) if tasks: # 更新任务状态 for i in range(0, len(tasks), 10000): # 10000 一批量更新 task_ids = str( tuple([task[0] for task in tasks[i : i + 10000]]) ).replace(",)", ")") sql = "update %s set %s = 2 where id in %s" % ( self._task_table, self._task_state, task_ids, ) self._mysqldb.update(sql) return tasks def get_doing_task_from_mysql(self): """ @summary: 取正在做的任务 --------- --------- @result: """ # 查询任务 task_keys = ", ".join([f"`{key}`" for key in self._task_keys]) sql = "select %s from %s where %s = 2%s%s limit %s" % ( task_keys, self._task_table, self._task_state, self._task_condition_prefix_and, self._task_order_by, self._task_limit, ) tasks = self._mysqldb.find(sql) return tasks def get_lose_task_count(self): sql = "select count(1) from %s where %s = 2%s" % ( self._task_table, self._task_state, self._task_condition_prefix_and, ) doing_count = self._mysqldb.find(sql)[0][0] return doing_count def reset_lose_task_from_mysql(self): """ @summary: 重置丢失任务为待做 --------- --------- @result: """ sql = "update {table} set {state} = 0 where {state} = 2{task_condition}".format( table=self._task_table, state=self._task_state, task_condition=self._task_condition_prefix_and, ) return self._mysqldb.update(sql) def related_spider_is_done(self): """ 相关连的爬虫是否跑完 @return: True / False / None 表示无相关的爬虫 可由自身的total_count 和 done_count 来判断 """ for related_redis_task_table in self._related_task_tables: if self._redisdb.exists_key(related_redis_task_table): log.info(f"依赖的爬虫还未结束,任务表为:{related_redis_task_table}") return False if self._related_batch_record: sql = "select is_done from {} order by id desc limit 1".format( self._related_batch_record ) is_done = self._mysqldb.find(sql) is_done = is_done[0][0] if is_done else None if is_done is None: log.warning("相关联的批次表不存在或无批次信息") return True if not is_done: log.info(f"依赖的爬虫还未结束,批次表为:{self._related_batch_record}") return False return True # -------- 批次结束逻辑 ------------ def task_is_done(self): """ @summary: 检查种子表是否做完 --------- --------- @result: True / False (做完 / 未做完) """ is_done = False if self._task_table_type == "mysql": sql = "select 1 from %s where (%s = 0 or %s=2)%s limit 1" % ( self._task_table, self._task_state, self._task_state, self._task_condition_prefix_and, ) count = self._mysqldb.find(sql) # [(1,)] / [] elif self._task_table_type == "redis": count = self._redisdb.zget_count(self._task_table) else: raise Exception( f"task_table_type expect mysql or redis,bug got {self._task_table_type}" ) if not count: log.info("种子表中任务均已完成") is_done = True return is_done def run(self): """ @summary: 重写run方法 检查mysql中的任务是否做完, 做完停止 --------- --------- @result: """ try: if not self.is_reach_next_spider_time(): return if not self._parsers: # 不是add_parser 模式 self._parsers.append(self) self._start() while True: try: if self._stop_spider or ( self.all_thread_is_done() and self.task_is_done() and self.related_spider_is_done() ): # redis全部的任务已经做完 并且mysql中的任务已经做完(检查各个线程all_thread_is_done,防止任务没做完,就更新任务状态,导致程序结束的情况) if not self._is_notify_end: self.spider_end() self._is_notify_end = True if not self._keep_alive: self._stop_all_thread() break else: log.info("常驻爬虫,等待新任务") else: self._is_notify_end = False self.check_task_status() except Exception as e: log.exception(e) tools.delay_time(10) # 10秒钟检查一次爬虫状态 except Exception as e: msg = "《%s》主线程异常 爬虫结束 exception: %s" % (self.name, e) log.error(msg) self.send_msg( msg, level="error", message_prefix="《%s》爬虫异常结束".format(self.name) ) os._exit(137) # 使退出码为35072 方便爬虫管理器重启 @classmethod def to_DebugTaskSpider(cls, *args, **kwargs): # DebugBatchSpider 继承 cls DebugTaskSpider.__bases__ = (cls,) DebugTaskSpider.__name__ = cls.__name__ return DebugTaskSpider(*args, **kwargs)
(redis_key, task_table, task_table_type='mysql', task_keys=None, task_state='state', min_task_count=10000, check_task_interval=5, task_limit=10000, related_redis_key=None, related_batch_record=None, task_condition='', task_order_by='', thread_count=None, begin_callback=None, end_callback=None, delete_keys=(), keep_alive=None, batch_interval=0, use_mysql=True, **kwargs)
8,497
feapder.core.spiders.task_spider
__init__
@summary: 任务爬虫 必要条件 需要指定任务表,可以是redis表或者mysql表作为任务种子 redis任务种子表:zset类型。值为 {"xxx":xxx, "xxx2":"xxx2"};若为集成模式,需指定parser_name字段,如{"xxx":xxx, "xxx2":"xxx2", "parser_name":"TestTaskSpider"} mysql任务表: 任务表中必须有id及任务状态字段 如 state, 其他字段可根据爬虫需要的参数自行扩充。若为集成模式,需指定parser_name字段。 参考建表语句如下: CREATE TABLE `table_name` ( `id` int(11) NOT NULL AUTO_INCREMENT, `param` varchar(1000) DEFAULT NULL COMMENT '爬虫需要的抓取数据需要的参数', `state` int(11) DEFAULT NULL COMMENT '任务状态', `parser_name` varchar(255) DEFAULT NULL COMMENT '任务解析器的脚本类名', PRIMARY KEY (`id`), UNIQUE KEY `nui` (`param`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; --------- @param task_table: mysql中的任务表 或 redis中存放任务种子的key,zset类型 @param task_table_type: 任务表类型 支持 redis 、mysql @param task_keys: 需要获取的任务字段 列表 [] 如需指定解析的parser,则需将parser_name字段取出来。 @param task_state: mysql中任务表的任务状态字段 @param min_task_count: redis 中最少任务数, 少于这个数量会从种子表中取任务 @param check_task_interval: 检查是否还有任务的时间间隔; @param task_limit: 每次从数据库中取任务的数量 @param redis_key: 任务等数据存放在redis中的key前缀 @param thread_count: 线程数,默认为配置文件中的线程数 @param begin_callback: 爬虫开始回调函数 @param end_callback: 爬虫结束回调函数 @param delete_keys: 爬虫启动时删除的key,类型: 元组/bool/string。 支持正则; 常用于清空任务队列,否则重启时会断点续爬 @param keep_alive: 爬虫是否常驻,默认否 @param related_redis_key: 有关联的其他爬虫任务表(redis)注意:要避免环路 如 A -> B & B -> A 。 @param related_batch_record: 有关联的其他爬虫批次表(mysql)注意:要避免环路 如 A -> B & B -> A 。 related_redis_key 与 related_batch_record 选其一配置即可;用于相关联的爬虫没结束时,本爬虫也不结束 若相关连的爬虫为批次爬虫,推荐以related_batch_record配置, 若相关连的爬虫为普通爬虫,无批次表,可以以related_redis_key配置 @param task_condition: 任务条件 用于从一个大任务表中挑选出数据自己爬虫的任务,即where后的条件语句 @param task_order_by: 取任务时的排序条件 如 id desc @param batch_interval: 抓取时间间隔 默认为0 天为单位 多次启动时,只有当前时间与第一次抓取结束的时间间隔大于指定的时间间隔时,爬虫才启动 @param use_mysql: 是否使用mysql数据库 --------- @result:
def __init__( self, redis_key, task_table, task_table_type="mysql", task_keys=None, task_state="state", min_task_count=10000, check_task_interval=5, task_limit=10000, related_redis_key=None, related_batch_record=None, task_condition="", task_order_by="", thread_count=None, begin_callback=None, end_callback=None, delete_keys=(), keep_alive=None, batch_interval=0, use_mysql=True, **kwargs, ): """ @summary: 任务爬虫 必要条件 需要指定任务表,可以是redis表或者mysql表作为任务种子 redis任务种子表:zset类型。值为 {"xxx":xxx, "xxx2":"xxx2"};若为集成模式,需指定parser_name字段,如{"xxx":xxx, "xxx2":"xxx2", "parser_name":"TestTaskSpider"} mysql任务表: 任务表中必须有id及任务状态字段 如 state, 其他字段可根据爬虫需要的参数自行扩充。若为集成模式,需指定parser_name字段。 参考建表语句如下: CREATE TABLE `table_name` ( `id` int(11) NOT NULL AUTO_INCREMENT, `param` varchar(1000) DEFAULT NULL COMMENT '爬虫需要的抓取数据需要的参数', `state` int(11) DEFAULT NULL COMMENT '任务状态', `parser_name` varchar(255) DEFAULT NULL COMMENT '任务解析器的脚本类名', PRIMARY KEY (`id`), UNIQUE KEY `nui` (`param`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; --------- @param task_table: mysql中的任务表 或 redis中存放任务种子的key,zset类型 @param task_table_type: 任务表类型 支持 redis 、mysql @param task_keys: 需要获取的任务字段 列表 [] 如需指定解析的parser,则需将parser_name字段取出来。 @param task_state: mysql中任务表的任务状态字段 @param min_task_count: redis 中最少任务数, 少于这个数量会从种子表中取任务 @param check_task_interval: 检查是否还有任务的时间间隔; @param task_limit: 每次从数据库中取任务的数量 @param redis_key: 任务等数据存放在redis中的key前缀 @param thread_count: 线程数,默认为配置文件中的线程数 @param begin_callback: 爬虫开始回调函数 @param end_callback: 爬虫结束回调函数 @param delete_keys: 爬虫启动时删除的key,类型: 元组/bool/string。 支持正则; 常用于清空任务队列,否则重启时会断点续爬 @param keep_alive: 爬虫是否常驻,默认否 @param related_redis_key: 有关联的其他爬虫任务表(redis)注意:要避免环路 如 A -> B & B -> A 。 @param related_batch_record: 有关联的其他爬虫批次表(mysql)注意:要避免环路 如 A -> B & B -> A 。 related_redis_key 与 related_batch_record 选其一配置即可;用于相关联的爬虫没结束时,本爬虫也不结束 若相关连的爬虫为批次爬虫,推荐以related_batch_record配置, 若相关连的爬虫为普通爬虫,无批次表,可以以related_redis_key配置 @param task_condition: 任务条件 用于从一个大任务表中挑选出数据自己爬虫的任务,即where后的条件语句 @param task_order_by: 取任务时的排序条件 如 id desc @param batch_interval: 抓取时间间隔 默认为0 天为单位 多次启动时,只有当前时间与第一次抓取结束的时间间隔大于指定的时间间隔时,爬虫才启动 @param use_mysql: 是否使用mysql数据库 --------- @result: """ Scheduler.__init__( self, redis_key=redis_key, thread_count=thread_count, begin_callback=begin_callback, end_callback=end_callback, delete_keys=delete_keys, keep_alive=keep_alive, auto_start_requests=False, batch_interval=batch_interval, task_table=task_table, **kwargs, ) self._redisdb = RedisDB() self._mysqldb = MysqlDB() if use_mysql else None self._task_table = task_table # mysql中的任务表 self._task_keys = task_keys # 需要获取的任务字段 self._task_table_type = task_table_type if self._task_table_type == "mysql" and not self._task_keys: raise Exception("需指定任务字段 使用task_keys") self._task_state = task_state # mysql中任务表的state字段名 self._min_task_count = min_task_count # redis 中最少任务数 self._check_task_interval = check_task_interval self._task_limit = task_limit # mysql中一次取的任务数量 self._related_task_tables = [ setting.TAB_REQUESTS.format(redis_key=redis_key) ] # 自己的task表也需要检查是否有任务 if related_redis_key: self._related_task_tables.append( setting.TAB_REQUESTS.format(redis_key=related_redis_key) ) self._related_batch_record = related_batch_record self._task_condition = task_condition self._task_condition_prefix_and = task_condition and " and {}".format( task_condition ) self._task_condition_prefix_where = task_condition and " where {}".format( task_condition ) self._task_order_by = task_order_by and " order by {}".format(task_order_by) self._is_more_parsers = True # 多模版类爬虫 self.reset_task()
(self, redis_key, task_table, task_table_type='mysql', task_keys=None, task_state='state', min_task_count=10000, check_task_interval=5, task_limit=10000, related_redis_key=None, related_batch_record=None, task_condition='', task_order_by='', thread_count=None, begin_callback=None, end_callback=None, delete_keys=(), keep_alive=None, batch_interval=0, use_mysql=True, **kwargs)
8,510
feapder.core.spiders.task_spider
add_parser
null
def add_parser(self, parser, **kwargs): parser = parser( self._task_table, self._task_state, self._mysqldb, **kwargs, ) # parser 实例化 self._parsers.append(parser)
(self, parser, **kwargs)
8,516
feapder.core.spiders.task_spider
distribute_task
@summary: 分发任务 --------- @param tasks: --------- @result:
def distribute_task(self, tasks): """ @summary: 分发任务 --------- @param tasks: --------- @result: """ if self._is_more_parsers: # 为多模版类爬虫,需要下发指定的parser for task in tasks: for parser in self._parsers: # 寻找task对应的parser if parser.name in task: if isinstance(task, dict): task = PerfectDict(_dict=task) else: task = PerfectDict( _dict=dict(zip(self._task_keys, task)), _values=list(task), ) requests = parser.start_requests(task) if requests and not isinstance(requests, Iterable): raise Exception( "%s.%s返回值必须可迭代" % (parser.name, "start_requests") ) result_type = 1 for request in requests or []: if isinstance(request, Request): request.parser_name = request.parser_name or parser.name self._request_buffer.put_request(request) result_type = 1 elif isinstance(request, Item): self._item_buffer.put_item(request) result_type = 2 if ( self._item_buffer.get_items_count() >= setting.ITEM_MAX_CACHED_COUNT ): self._item_buffer.flush() elif callable(request): # callbale的request可能是更新数据库操作的函数 if result_type == 1: self._request_buffer.put_request(request) else: self._item_buffer.put_item(request) if ( self._item_buffer.get_items_count() >= setting.ITEM_MAX_CACHED_COUNT ): self._item_buffer.flush() else: raise TypeError( "start_requests yield result type error, expect Request、Item、callback func, bug get type: {}".format( type(requests) ) ) break else: # task没对应的parser 则将task下发到所有的parser for task in tasks: for parser in self._parsers: if isinstance(task, dict): task = PerfectDict(_dict=task) else: task = PerfectDict( _dict=dict(zip(self._task_keys, task)), _values=list(task) ) requests = parser.start_requests(task) if requests and not isinstance(requests, Iterable): raise Exception( "%s.%s返回值必须可迭代" % (parser.name, "start_requests") ) result_type = 1 for request in requests or []: if isinstance(request, Request): request.parser_name = request.parser_name or parser.name self._request_buffer.put_request(request) result_type = 1 elif isinstance(request, Item): self._item_buffer.put_item(request) result_type = 2 if ( self._item_buffer.get_items_count() >= setting.ITEM_MAX_CACHED_COUNT ): self._item_buffer.flush() elif callable(request): # callbale的request可能是更新数据库操作的函数 if result_type == 1: self._request_buffer.put_request(request) else: self._item_buffer.put_item(request) if ( self._item_buffer.get_items_count() >= setting.ITEM_MAX_CACHED_COUNT ): self._item_buffer.flush() self._request_buffer.flush() self._item_buffer.flush()
(self, tasks)
8,523
feapder.core.spiders.task_spider
get_lose_task_count
null
def get_lose_task_count(self): sql = "select count(1) from %s where %s = 2%s" % ( self._task_table, self._task_state, self._task_condition_prefix_and, ) doing_count = self._mysqldb.find(sql)[0][0] return doing_count
(self)
8,524
feapder.core.spiders.task_spider
get_task
获取任务 Args: todo_task_count: redis里剩余的任务数 Returns:
def get_task(self, todo_task_count) -> List[Union[Tuple, Dict]]: """ 获取任务 Args: todo_task_count: redis里剩余的任务数 Returns: """ tasks = [] if self._task_table_type == "mysql": # 从mysql中取任务 log.info("redis 中剩余任务%s 数量过小 从mysql中取任务追加" % todo_task_count) tasks = self.get_todo_task_from_mysql() if not tasks: # 状态为0的任务已经做完,需要检查状态为2的任务是否丢失 # redis 中无待做任务,此时mysql中状态为2的任务为丢失任务。需重新做 if todo_task_count == 0: log.info("无待做任务,尝试取丢失的任务") tasks = self.get_doing_task_from_mysql() elif self._task_table_type == "redis": log.info("redis 中剩余任务%s 数量过小 从redis种子任务表中取任务追加" % todo_task_count) tasks = self.get_task_from_redis() else: raise Exception( f"task_table_type expect mysql or redis,bug got {self._task_table_type}" ) return tasks
(self, todo_task_count) -> List[Union[Tuple, Dict]]
8,525
feapder.core.spiders.task_spider
get_task_from_redis
null
def get_task_from_redis(self): tasks = self._redisdb.zget(self._task_table, count=self._task_limit) tasks = [eval(task) for task in tasks] return tasks
(self)
8,538
feapder.core.spiders.task_spider
related_spider_is_done
相关连的爬虫是否跑完 @return: True / False / None 表示无相关的爬虫 可由自身的total_count 和 done_count 来判断
def related_spider_is_done(self): """ 相关连的爬虫是否跑完 @return: True / False / None 表示无相关的爬虫 可由自身的total_count 和 done_count 来判断 """ for related_redis_task_table in self._related_task_tables: if self._redisdb.exists_key(related_redis_task_table): log.info(f"依赖的爬虫还未结束,任务表为:{related_redis_task_table}") return False if self._related_batch_record: sql = "select is_done from {} order by id desc limit 1".format( self._related_batch_record ) is_done = self._mysqldb.find(sql) is_done = is_done[0][0] if is_done else None if is_done is None: log.warning("相关联的批次表不存在或无批次信息") return True if not is_done: log.info(f"依赖的爬虫还未结束,批次表为:{self._related_batch_record}") return False return True
(self)
8,541
feapder.core.spiders.task_spider
run
@summary: 重写run方法 检查mysql中的任务是否做完, 做完停止 --------- --------- @result:
def run(self): """ @summary: 重写run方法 检查mysql中的任务是否做完, 做完停止 --------- --------- @result: """ try: if not self.is_reach_next_spider_time(): return if not self._parsers: # 不是add_parser 模式 self._parsers.append(self) self._start() while True: try: if self._stop_spider or ( self.all_thread_is_done() and self.task_is_done() and self.related_spider_is_done() ): # redis全部的任务已经做完 并且mysql中的任务已经做完(检查各个线程all_thread_is_done,防止任务没做完,就更新任务状态,导致程序结束的情况) if not self._is_notify_end: self.spider_end() self._is_notify_end = True if not self._keep_alive: self._stop_all_thread() break else: log.info("常驻爬虫,等待新任务") else: self._is_notify_end = False self.check_task_status() except Exception as e: log.exception(e) tools.delay_time(10) # 10秒钟检查一次爬虫状态 except Exception as e: msg = "《%s》主线程异常 爬虫结束 exception: %s" % (self.name, e) log.error(msg) self.send_msg( msg, level="error", message_prefix="《%s》爬虫异常结束".format(self.name) ) os._exit(137) # 使退出码为35072 方便爬虫管理器重启
(self)
8,549
feapder.core.spiders.task_spider
start_monitor_task
@summary: 监控任务状态 --------- --------- @result:
def start_monitor_task(self): """ @summary: 监控任务状态 --------- --------- @result: """ if not self._parsers: # 不是多模版模式, 将自己注入到parsers,自己为模版 self._is_more_parsers = False self._parsers.append(self) elif len(self._parsers) <= 1: self._is_more_parsers = False # 添加任务 for parser in self._parsers: parser.add_task() while True: try: # 检查redis中是否有任务 任务小于_min_task_count 则从mysql中取 tab_requests = setting.TAB_REQUESTS.format(redis_key=self._redis_key) todo_task_count = self._redisdb.zget_count(tab_requests) tasks = [] if todo_task_count < self._min_task_count: tasks = self.get_task(todo_task_count) if not tasks: if not todo_task_count: if self._keep_alive: log.info("任务均已做完,爬虫常驻, 等待新任务") time.sleep(self._check_task_interval) continue elif self.have_alive_spider(): log.info("任务均已做完,但还有爬虫在运行,等待爬虫结束") time.sleep(self._check_task_interval) continue elif not self.related_spider_is_done(): continue else: log.info("任务均已做完,爬虫结束") break else: log.info("redis 中尚有%s条积压任务,暂时不派发新任务" % todo_task_count) if not tasks: if todo_task_count >= self._min_task_count: # log.info('任务正在进行 redis中剩余任务 %s' % todo_task_count) pass else: log.info("无待做种子 redis中剩余任务 %s" % todo_task_count) else: # make start requests self.distribute_task(tasks) log.info(f"添加任务到redis成功 共{len(tasks)}条") except Exception as e: log.exception(e) time.sleep(self._check_task_interval)
(self)
8,552
feapder.core.spiders.task_spider
task_is_done
@summary: 检查种子表是否做完 --------- --------- @result: True / False (做完 / 未做完)
def task_is_done(self): """ @summary: 检查种子表是否做完 --------- --------- @result: True / False (做完 / 未做完) """ is_done = False if self._task_table_type == "mysql": sql = "select 1 from %s where (%s = 0 or %s=2)%s limit 1" % ( self._task_table, self._task_state, self._task_state, self._task_condition_prefix_and, ) count = self._mysqldb.find(sql) # [(1,)] / [] elif self._task_table_type == "redis": count = self._redisdb.zget_count(self._task_table) else: raise Exception( f"task_table_type expect mysql or redis,bug got {self._task_table_type}" ) if not count: log.info("种子表中任务均已完成") is_done = True return is_done
(self)
8,557
feapder.network.item
UpdateItem
null
class UpdateItem(Item): __update_key__ = [] def __init__(self, **kwargs): super(UpdateItem, self).__init__(**kwargs) @property def update_key(self): return self.__update_key__ or self.__class__.__update_key__ @update_key.setter def update_key(self, keys): if isinstance(keys, (tuple, list)): self.__update_key__ = keys else: self.__update_key__ = (keys,)
(**kwargs)
8,559
feapder.network.item
__init__
null
def __init__(self, **kwargs): super(UpdateItem, self).__init__(**kwargs)
(self, **kwargs)
8,578
cnab.types
Action
Action(modifies: Optional[bool] = None, stateless: Optional[bool] = None, description: Optional[str] = None)
class Action: modifies: Optional[bool] = None stateless: Optional[bool] = None description: Optional[str] = None @staticmethod def from_dict(obj: Any) -> "Action": assert isinstance(obj, dict) modifies = from_union([from_bool, from_none], obj.get("modifies")) stateless = from_union([from_bool, from_none], obj.get("stateless")) description = from_union([from_str, from_none], obj.get("description")) return Action(modifies, stateless, description) def to_dict(self) -> dict: result: dict = {} result["modifies"] = from_union([from_bool, from_none], self.modifies) result["stateless"] = from_union([from_bool, from_none], self.stateless) result["description"] = from_union([from_str, from_none], self.description) return clean(result)
(modifies: Optional[bool] = None, stateless: Optional[bool] = None, description: Optional[str] = None) -> None
8,579
cnab.types
__eq__
null
import canonicaljson # type: ignore from dataclasses import dataclass, field from typing import Optional, Any, List, Union, Dict, TypeVar, Callable, Type, cast T = TypeVar("T") def from_bool(x: Any) -> bool: if not isinstance(x, bool): raise Exception(f"{x} not a boolean") return x
(self, other)
8,581
cnab.types
__repr__
null
@staticmethod def from_dict(obj: Any) -> "Maintainer": assert isinstance(obj, dict) name = from_union([from_str, from_none], obj.get("name")) email = from_union([from_str, from_none], obj.get("email")) url = from_union([from_str, from_none], obj.get("url")) return Maintainer(name, email, url)
(self)
8,582
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "Action": assert isinstance(obj, dict) modifies = from_union([from_bool, from_none], obj.get("modifies")) stateless = from_union([from_bool, from_none], obj.get("stateless")) description = from_union([from_str, from_none], obj.get("description")) return Action(modifies, stateless, description)
(obj: Any) -> cnab.types.Action
8,583
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["modifies"] = from_union([from_bool, from_none], self.modifies) result["stateless"] = from_union([from_bool, from_none], self.stateless) result["description"] = from_union([from_str, from_none], self.description) return clean(result)
(self) -> dict
8,584
cnab.types
Bundle
Bundle(name: str, version: str, invocation_images: List[cnab.types.InvocationImage], schema_version: Optional[str] = 'v1', actions: Dict[str, cnab.types.Action] = <factory>, credentials: Dict[str, cnab.types.Credential] = <factory>, description: Optional[str] = None, license: Optional[str] = None, images: Dict[str, cnab.types.Image] = <factory>, keywords: List[str] = <factory>, maintainers: List[cnab.types.Maintainer] = <factory>, parameters: Dict[str, cnab.types.Parameter] = <factory>)
class Bundle: name: str version: str invocation_images: List[InvocationImage] schema_version: Optional[str] = "v1" actions: Dict[str, Action] = field(default_factory=dict) credentials: Dict[str, Credential] = field(default_factory=dict) description: Optional[str] = None license: Optional[str] = None images: Dict[str, Image] = field(default_factory=dict) keywords: List[str] = field(default_factory=list) maintainers: List[Maintainer] = field(default_factory=list) parameters: Dict[str, Parameter] = field(default_factory=dict) @staticmethod def from_dict(obj: Any) -> "Bundle": assert isinstance(obj, dict) actions = from_union( [lambda x: from_dict(Action.from_dict, x), from_none], obj.get("actions") ) credentials = from_union( [lambda x: from_dict(Credential.from_dict, x), from_none], obj.get("credentials"), ) description = from_union([from_str, from_none], obj.get("description")) license = from_union([from_str, from_none], obj.get("license")) images = from_union( [lambda x: from_dict(Image.from_dict, x), from_none], obj.get("images") ) invocation_images = from_list( InvocationImage.from_dict, obj.get("invocationImages") ) keywords = from_union( [lambda x: from_list(from_str, x), from_none], obj.get("keywords") ) maintainers = from_union( [lambda x: from_list(Maintainer.from_dict, x), from_none], obj.get("maintainers"), ) name = from_str(obj.get("name")) parameters = from_union( [lambda x: from_dict(Parameter.from_dict, x), from_none], obj.get("parameters"), ) schema_version = from_union([from_str, from_none], obj.get("schemaVersion")) version = from_str(obj.get("version")) return Bundle( name, version, invocation_images, schema_version, actions, credentials, description, license, images, keywords, maintainers, parameters, ) def to_dict(self) -> dict: result: dict = {} result["actions"] = from_dict(lambda x: to_class(Action, x), self.actions) result["credentials"] = from_dict( lambda x: to_class(Credential, x), self.credentials ) result["description"] = from_union([from_str, from_none], self.description) result["license"] = from_union([from_str, from_none], self.license) result["images"] = from_dict(lambda x: to_class(Image, x), self.images) result["invocationImages"] = from_list( lambda x: to_class(InvocationImage, x), self.invocation_images ) result["keywords"] = from_list(from_str, self.keywords) result["maintainers"] = from_list( lambda x: to_class(Maintainer, x), self.maintainers ) result["name"] = from_str(self.name) result["parameters"] = from_dict( lambda x: to_class(Parameter, x), self.parameters ) result["schemaVersion"] = from_str(self.schema_version) result["version"] = from_str(self.version) return clean(result) def to_json(self, pretty: bool = False) -> str: if pretty: func = canonicaljson.encode_pretty_printed_json else: func = canonicaljson.encode_canonical_json return func(self.to_dict()).decode()
(name: str, version: str, invocation_images: List[cnab.types.InvocationImage], schema_version: Optional[str] = 'v1', actions: Dict[str, cnab.types.Action] = <factory>, credentials: Dict[str, cnab.types.Credential] = <factory>, description: Optional[str] = None, license: Optional[str] = None, images: Dict[str, cnab.types.Image] = <factory>, keywords: List[str] = <factory>, maintainers: List[cnab.types.Maintainer] = <factory>, parameters: Dict[str, cnab.types.Parameter] = <factory>) -> None
8,588
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "Bundle": assert isinstance(obj, dict) actions = from_union( [lambda x: from_dict(Action.from_dict, x), from_none], obj.get("actions") ) credentials = from_union( [lambda x: from_dict(Credential.from_dict, x), from_none], obj.get("credentials"), ) description = from_union([from_str, from_none], obj.get("description")) license = from_union([from_str, from_none], obj.get("license")) images = from_union( [lambda x: from_dict(Image.from_dict, x), from_none], obj.get("images") ) invocation_images = from_list( InvocationImage.from_dict, obj.get("invocationImages") ) keywords = from_union( [lambda x: from_list(from_str, x), from_none], obj.get("keywords") ) maintainers = from_union( [lambda x: from_list(Maintainer.from_dict, x), from_none], obj.get("maintainers"), ) name = from_str(obj.get("name")) parameters = from_union( [lambda x: from_dict(Parameter.from_dict, x), from_none], obj.get("parameters"), ) schema_version = from_union([from_str, from_none], obj.get("schemaVersion")) version = from_str(obj.get("version")) return Bundle( name, version, invocation_images, schema_version, actions, credentials, description, license, images, keywords, maintainers, parameters, )
(obj: Any) -> cnab.types.Bundle
8,589
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["actions"] = from_dict(lambda x: to_class(Action, x), self.actions) result["credentials"] = from_dict( lambda x: to_class(Credential, x), self.credentials ) result["description"] = from_union([from_str, from_none], self.description) result["license"] = from_union([from_str, from_none], self.license) result["images"] = from_dict(lambda x: to_class(Image, x), self.images) result["invocationImages"] = from_list( lambda x: to_class(InvocationImage, x), self.invocation_images ) result["keywords"] = from_list(from_str, self.keywords) result["maintainers"] = from_list( lambda x: to_class(Maintainer, x), self.maintainers ) result["name"] = from_str(self.name) result["parameters"] = from_dict( lambda x: to_class(Parameter, x), self.parameters ) result["schemaVersion"] = from_str(self.schema_version) result["version"] = from_str(self.version) return clean(result)
(self) -> dict
8,590
cnab.types
to_json
null
def to_json(self, pretty: bool = False) -> str: if pretty: func = canonicaljson.encode_pretty_printed_json else: func = canonicaljson.encode_canonical_json return func(self.to_dict()).decode()
(self, pretty: bool = False) -> str
8,591
cnab.cnab
CNAB
null
class CNAB: bundle: Bundle name: str def __init__(self, bundle: Union[Bundle, dict, str], name: str = None): if isinstance(bundle, Bundle): self.bundle = bundle elif isinstance(bundle, dict): self.bundle = Bundle.from_dict(bundle) elif isinstance(bundle, str): with open(bundle) as f: data = json.load(f) self.bundle = Bundle.from_dict(data) else: raise TypeError self.name = name or self.bundle.name def run(self, action: str, credentials: dict = {}, parameters: dict = {}): import docker # type: ignore # check if action is supported assert action in self.actions client = docker.from_env() docker_images = extract_docker_images(self.bundle.invocation_images) assert len(docker_images) == 1 # check if parameters passed in are in bundle parameters errors = [] for key in parameters: if key not in self.bundle.parameters: errors.append(f"Invalid parameter provided: {key}") assert len(errors) == 0 # check if required parameters have been passed in required = [] for param in self.bundle.parameters: parameter = self.bundle.parameters[param] if parameter.required: required.append(param) for param in required: assert param in parameters # validate passed in params for param in parameters: parameter = self.bundle.parameters[param] if parameter.allowed_values: assert param in parameter.allowed_values if isinstance(param, int): if parameter.max_value: assert param <= parameter.max_value if parameter.min_value: assert param >= parameter.min_value elif isinstance(param, str): if parameter.max_length: assert len(param) <= parameter.max_length if parameter.min_length: assert len(param) >= parameter.min_length env = { "CNAB_INSTALLATION_NAME": self.name, "CNAB_BUNDLE_NAME": self.bundle.name, "CNAB_ACTION": action, } # build environment hash for param in self.bundle.parameters: parameter = self.bundle.parameters[param] if parameter.destination: if parameter.destination.env: key = parameter.destination.env value = ( parameters[param] if param in parameters else parameter.default_value ) env[key] = value if parameter.destination.path: # not yet supported pass mounts = [] if self.bundle.credentials: for name in self.bundle.credentials: # check credential has been provided assert name in credentials credential = self.bundle.credentials[name] if credential.env: # discussing behavour in https://github.com/deislabs/cnab-spec/issues/69 assert credential.env[:5] != "CNAB_" env[credential.env] = credentials[name] if credential.path: tmp = tempfile.NamedTemporaryFile(mode="w+", delete=True) tmp.write(credentials[name]) tmp.flush() mounts.append( docker.types.Mount( target=credential.path, source=tmp.name, read_only=True, type="bind", ) ) # Mount image maps for runtime usage tmp = tempfile.NamedTemporaryFile(mode="w+", delete=True) tmp.write(json.dumps(self.bundle.images)) tmp.flush() mounts.append( docker.types.Mount( target="/cnab/app/image-map.json", source=tmp.name, read_only=True, type="bind", ) ) return client.containers.run( docker_images[0].image, "/cnab/app/run", auto_remove=False, remove=True, environment=env, mounts=mounts, ) @property def actions(self) -> dict: actions = { "install": Action(modifies=True), "uninstall": Action(modifies=True), "upgrade": Action(modifies=True), } if self.bundle.actions: actions.update(self.bundle.actions) return actions @property def parameters(self) -> dict: return self.bundle.parameters @property def credentials(self) -> dict: return self.bundle.credentials
(bundle: cnab.types.Bundle, name: str = None)
8,592
cnab.cnab
__init__
null
def __init__(self, bundle: Union[Bundle, dict, str], name: str = None): if isinstance(bundle, Bundle): self.bundle = bundle elif isinstance(bundle, dict): self.bundle = Bundle.from_dict(bundle) elif isinstance(bundle, str): with open(bundle) as f: data = json.load(f) self.bundle = Bundle.from_dict(data) else: raise TypeError self.name = name or self.bundle.name
(self, bundle: Union[cnab.types.Bundle, dict, str], name: Optional[str] = None)
8,593
cnab.cnab
run
null
def run(self, action: str, credentials: dict = {}, parameters: dict = {}): import docker # type: ignore # check if action is supported assert action in self.actions client = docker.from_env() docker_images = extract_docker_images(self.bundle.invocation_images) assert len(docker_images) == 1 # check if parameters passed in are in bundle parameters errors = [] for key in parameters: if key not in self.bundle.parameters: errors.append(f"Invalid parameter provided: {key}") assert len(errors) == 0 # check if required parameters have been passed in required = [] for param in self.bundle.parameters: parameter = self.bundle.parameters[param] if parameter.required: required.append(param) for param in required: assert param in parameters # validate passed in params for param in parameters: parameter = self.bundle.parameters[param] if parameter.allowed_values: assert param in parameter.allowed_values if isinstance(param, int): if parameter.max_value: assert param <= parameter.max_value if parameter.min_value: assert param >= parameter.min_value elif isinstance(param, str): if parameter.max_length: assert len(param) <= parameter.max_length if parameter.min_length: assert len(param) >= parameter.min_length env = { "CNAB_INSTALLATION_NAME": self.name, "CNAB_BUNDLE_NAME": self.bundle.name, "CNAB_ACTION": action, } # build environment hash for param in self.bundle.parameters: parameter = self.bundle.parameters[param] if parameter.destination: if parameter.destination.env: key = parameter.destination.env value = ( parameters[param] if param in parameters else parameter.default_value ) env[key] = value if parameter.destination.path: # not yet supported pass mounts = [] if self.bundle.credentials: for name in self.bundle.credentials: # check credential has been provided assert name in credentials credential = self.bundle.credentials[name] if credential.env: # discussing behavour in https://github.com/deislabs/cnab-spec/issues/69 assert credential.env[:5] != "CNAB_" env[credential.env] = credentials[name] if credential.path: tmp = tempfile.NamedTemporaryFile(mode="w+", delete=True) tmp.write(credentials[name]) tmp.flush() mounts.append( docker.types.Mount( target=credential.path, source=tmp.name, read_only=True, type="bind", ) ) # Mount image maps for runtime usage tmp = tempfile.NamedTemporaryFile(mode="w+", delete=True) tmp.write(json.dumps(self.bundle.images)) tmp.flush() mounts.append( docker.types.Mount( target="/cnab/app/image-map.json", source=tmp.name, read_only=True, type="bind", ) ) return client.containers.run( docker_images[0].image, "/cnab/app/run", auto_remove=False, remove=True, environment=env, mounts=mounts, )
(self, action: str, credentials: dict = {}, parameters: dict = {})
8,594
cnab.invocation_image
CNABDirectory
null
class CNABDirectory(object): path: str def __init__(self, path: str): self.path = path def has_cnab_directory(self) -> bool: cnab = os.path.join(self.path, "cnab") return os.path.isdir(cnab) def has_app_directory(self) -> bool: app = os.path.join(self.path, "cnab", "app") return os.path.isdir(app) def has_no_misc_files_in_cnab_dir(self) -> bool: cnab = os.path.join(self.path, "cnab") disallowed_dirs: List[str] = [] disallowed_files: List[str] = [] for root, dirs, files in os.walk(cnab): disallowed_dirs = [x for x in dirs if x not in ["app", "build"]] disallowed_files = [ x for x in files if x not in ["LICENSE", "README.md", "README.txt"] ] break if disallowed_dirs or disallowed_files: return False else: return True def has_run(self) -> bool: run = os.path.join(self.path, "cnab", "app", "run") return os.path.isfile(run) def has_executable_run(self) -> bool: run = os.path.join(self.path, "cnab", "app", "run") return os.access(run, os.X_OK) def readme(self) -> Union[bool, str]: readme = os.path.join(self.path, "cnab", "README") txt = readme + ".txt" md = readme + ".md" if os.path.isfile(txt): with open(txt, "r") as content: return content.read() elif os.path.isfile(md): with open(md, "r") as content: return content.read() else: return False def license(self) -> Union[bool, str]: license = os.path.join(self.path, "cnab", "LICENSE") if os.path.isfile(license): with open(license, "r") as content: return content.read() else: return False def valid(self) -> bool: errors = [] if not self.has_executable_run(): errors.append("Run entrypoint is not executable") if not self.has_run(): errors.append("Missing a run entrypoint") if not self.has_app_directory(): errors.append("Missing the app directory") if not self.has_cnab_directory(): errors.append("Missing the cnab directory") if not self.has_no_misc_files_in_cnab_dir(): errors.append("Has additional files in the cnab directory") if len(errors) == 0: return True else: raise InvalidCNABDirectoryError(errors)
(path: str)
8,595
cnab.invocation_image
__init__
null
def __init__(self, path: str): self.path = path
(self, path: str)
8,596
cnab.invocation_image
has_app_directory
null
def has_app_directory(self) -> bool: app = os.path.join(self.path, "cnab", "app") return os.path.isdir(app)
(self) -> bool
8,597
cnab.invocation_image
has_cnab_directory
null
def has_cnab_directory(self) -> bool: cnab = os.path.join(self.path, "cnab") return os.path.isdir(cnab)
(self) -> bool
8,598
cnab.invocation_image
has_executable_run
null
def has_executable_run(self) -> bool: run = os.path.join(self.path, "cnab", "app", "run") return os.access(run, os.X_OK)
(self) -> bool
8,599
cnab.invocation_image
has_no_misc_files_in_cnab_dir
null
def has_no_misc_files_in_cnab_dir(self) -> bool: cnab = os.path.join(self.path, "cnab") disallowed_dirs: List[str] = [] disallowed_files: List[str] = [] for root, dirs, files in os.walk(cnab): disallowed_dirs = [x for x in dirs if x not in ["app", "build"]] disallowed_files = [ x for x in files if x not in ["LICENSE", "README.md", "README.txt"] ] break if disallowed_dirs or disallowed_files: return False else: return True
(self) -> bool
8,600
cnab.invocation_image
has_run
null
def has_run(self) -> bool: run = os.path.join(self.path, "cnab", "app", "run") return os.path.isfile(run)
(self) -> bool
8,601
cnab.invocation_image
license
null
def license(self) -> Union[bool, str]: license = os.path.join(self.path, "cnab", "LICENSE") if os.path.isfile(license): with open(license, "r") as content: return content.read() else: return False
(self) -> Union[bool, str]
8,602
cnab.invocation_image
readme
null
def readme(self) -> Union[bool, str]: readme = os.path.join(self.path, "cnab", "README") txt = readme + ".txt" md = readme + ".md" if os.path.isfile(txt): with open(txt, "r") as content: return content.read() elif os.path.isfile(md): with open(md, "r") as content: return content.read() else: return False
(self) -> Union[bool, str]
8,603
cnab.invocation_image
valid
null
def valid(self) -> bool: errors = [] if not self.has_executable_run(): errors.append("Run entrypoint is not executable") if not self.has_run(): errors.append("Missing a run entrypoint") if not self.has_app_directory(): errors.append("Missing the app directory") if not self.has_cnab_directory(): errors.append("Missing the cnab directory") if not self.has_no_misc_files_in_cnab_dir(): errors.append("Has additional files in the cnab directory") if len(errors) == 0: return True else: raise InvalidCNABDirectoryError(errors)
(self) -> bool
8,604
cnab.types
Credential
Credential(description: Optional[str] = None, env: Optional[str] = None, path: Optional[str] = None)
class Credential: description: Optional[str] = None env: Optional[str] = None path: Optional[str] = None @staticmethod def from_dict(obj: Any) -> "Credential": assert isinstance(obj, dict) description = from_union([from_str, from_none], obj.get("description")) env = from_union([from_str, from_none], obj.get("env")) path = from_union([from_str, from_none], obj.get("path")) return Credential(description, env, path) def to_dict(self) -> dict: result: dict = {} result["description"] = from_union([from_str, from_none], self.description) result["env"] = from_union([from_str, from_none], self.env) result["path"] = from_union([from_str, from_none], self.path) return clean(result)
(description: Optional[str] = None, env: Optional[str] = None, path: Optional[str] = None) -> None
8,608
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "Credential": assert isinstance(obj, dict) description = from_union([from_str, from_none], obj.get("description")) env = from_union([from_str, from_none], obj.get("env")) path = from_union([from_str, from_none], obj.get("path")) return Credential(description, env, path)
(obj: Any) -> cnab.types.Credential
8,609
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["description"] = from_union([from_str, from_none], self.description) result["env"] = from_union([from_str, from_none], self.env) result["path"] = from_union([from_str, from_none], self.path) return clean(result)
(self) -> dict
8,610
cnab.types
Destination
Destination(description: Optional[str] = None, env: Optional[str] = None, path: Optional[str] = None)
class Destination: description: Optional[str] = None env: Optional[str] = None path: Optional[str] = None @staticmethod def from_dict(obj: Any) -> "Destination": assert isinstance(obj, dict) description = from_union([from_str, from_none], obj.get("description")) env = from_union([from_str, from_none], obj.get("env")) path = from_union([from_str, from_none], obj.get("path")) return Destination(description, env, path) def to_dict(self) -> dict: result: dict = {} result["description"] = from_union([from_str, from_none], self.description) result["env"] = from_union([from_str, from_none], self.env) result["path"] = from_union([from_str, from_none], self.path) return clean(result)
(description: Optional[str] = None, env: Optional[str] = None, path: Optional[str] = None) -> None
8,614
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "Destination": assert isinstance(obj, dict) description = from_union([from_str, from_none], obj.get("description")) env = from_union([from_str, from_none], obj.get("env")) path = from_union([from_str, from_none], obj.get("path")) return Destination(description, env, path)
(obj: Any) -> cnab.types.Destination
8,616
cnab.types
Image
Image(image: str, description: Optional[str] = None, digest: Optional[str] = None, image_type: Optional[str] = None, media_type: Optional[str] = None, platform: Optional[cnab.types.ImagePlatform] = None, refs: List[cnab.types.Ref] = <factory>, size: Optional[int] = None)
class Image: image: str description: Optional[str] = None digest: Optional[str] = None image_type: Optional[str] = None media_type: Optional[str] = None platform: Optional[ImagePlatform] = None refs: List[Ref] = field(default_factory=list) size: Optional[int] = None @staticmethod def from_dict(obj: Any) -> "Image": assert isinstance(obj, dict) description = from_union([from_str, from_none], obj.get("description")) digest = from_union([from_str, from_none], obj.get("digest")) image = from_str(obj.get("image")) image_type = from_union([from_str, from_none], obj.get("imageType")) media_type = from_union([from_str, from_none], obj.get("mediaType")) platform = from_union([ImagePlatform.from_dict, from_none], obj.get("platform")) refs = from_union( [lambda x: from_list(Ref.from_dict, x), from_none], obj.get("refs") ) size = from_union([from_int, from_none], obj.get("size")) return Image( description, digest, image, image_type, media_type, platform, refs, size ) def to_dict(self) -> dict: result: dict = {} result["description"] = from_union([from_str, from_none], self.description) result["digest"] = from_union([from_str, from_none], self.digest) result["image"] = from_str(self.image) result["imageType"] = from_union([from_str, from_none], self.image_type) result["mediaType"] = from_union([from_str, from_none], self.media_type) result["platform"] = from_union( [lambda x: to_class(ImagePlatform, x), from_none], self.platform ) result["refs"] = from_list(lambda x: to_class(Ref, x), self.refs) result["size"] = from_union([from_int, from_none], self.size) return clean(result)
(image: str, description: Optional[str] = None, digest: Optional[str] = None, image_type: Optional[str] = None, media_type: Optional[str] = None, platform: Optional[cnab.types.ImagePlatform] = None, refs: List[cnab.types.Ref] = <factory>, size: Optional[int] = None) -> None
8,620
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "Image": assert isinstance(obj, dict) description = from_union([from_str, from_none], obj.get("description")) digest = from_union([from_str, from_none], obj.get("digest")) image = from_str(obj.get("image")) image_type = from_union([from_str, from_none], obj.get("imageType")) media_type = from_union([from_str, from_none], obj.get("mediaType")) platform = from_union([ImagePlatform.from_dict, from_none], obj.get("platform")) refs = from_union( [lambda x: from_list(Ref.from_dict, x), from_none], obj.get("refs") ) size = from_union([from_int, from_none], obj.get("size")) return Image( description, digest, image, image_type, media_type, platform, refs, size )
(obj: Any) -> cnab.types.Image
8,621
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["description"] = from_union([from_str, from_none], self.description) result["digest"] = from_union([from_str, from_none], self.digest) result["image"] = from_str(self.image) result["imageType"] = from_union([from_str, from_none], self.image_type) result["mediaType"] = from_union([from_str, from_none], self.media_type) result["platform"] = from_union( [lambda x: to_class(ImagePlatform, x), from_none], self.platform ) result["refs"] = from_list(lambda x: to_class(Ref, x), self.refs) result["size"] = from_union([from_int, from_none], self.size) return clean(result)
(self) -> dict
8,622
cnab.types
ImagePlatform
ImagePlatform(architecture: Optional[str] = None, os: Optional[str] = None)
class ImagePlatform: architecture: Optional[str] = None os: Optional[str] = None @staticmethod def from_dict(obj: Any) -> "ImagePlatform": assert isinstance(obj, dict) architecture = from_union([from_str, from_none], obj.get("architecture")) os = from_union([from_str, from_none], obj.get("os")) return ImagePlatform(architecture, os) def to_dict(self) -> dict: result: dict = {} result["architecture"] = from_union([from_str, from_none], self.architecture) result["os"] = from_union([from_str, from_none], self.os) return clean(result)
(architecture: Optional[str] = None, os: Optional[str] = None) -> None
8,626
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "ImagePlatform": assert isinstance(obj, dict) architecture = from_union([from_str, from_none], obj.get("architecture")) os = from_union([from_str, from_none], obj.get("os")) return ImagePlatform(architecture, os)
(obj: Any) -> cnab.types.ImagePlatform
8,627
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["architecture"] = from_union([from_str, from_none], self.architecture) result["os"] = from_union([from_str, from_none], self.os) return clean(result)
(self) -> dict
8,628
cnab.types
InvocationImage
InvocationImage(image: str, digest: Optional[str] = None, image_type: Optional[str] = 'oci', media_type: Optional[str] = None, platform: Optional[cnab.types.ImagePlatform] = None, size: Optional[str] = None)
class InvocationImage: image: str digest: Optional[str] = None image_type: Optional[str] = "oci" media_type: Optional[str] = None platform: Optional[ImagePlatform] = None size: Optional[str] = None @staticmethod def from_dict(obj: Any) -> "InvocationImage": assert isinstance(obj, dict) digest = from_union([from_str, from_none], obj.get("digest")) image = from_str(obj.get("image")) image_type = from_union([from_str, from_none], obj.get("imageType")) media_type = from_union([from_str, from_none], obj.get("mediaType")) platform = from_union([ImagePlatform.from_dict, from_none], obj.get("platform")) size = from_union([from_str, from_none], obj.get("size")) return InvocationImage(image, digest, image_type, media_type, platform, size) def to_dict(self) -> dict: result: dict = {} result["digest"] = from_union([from_str, from_none], self.digest) result["image"] = from_str(self.image) result["imageType"] = from_union([from_str, from_none], self.image_type) result["mediaType"] = from_union([from_str, from_none], self.media_type) result["platform"] = from_union( [lambda x: to_class(ImagePlatform, x), from_none], self.platform ) result["size"] = from_union([from_str, from_none], self.size) return clean(result)
(image: str, digest: Optional[str] = None, image_type: Optional[str] = 'oci', media_type: Optional[str] = None, platform: Optional[cnab.types.ImagePlatform] = None, size: Optional[str] = None) -> None
8,632
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "InvocationImage": assert isinstance(obj, dict) digest = from_union([from_str, from_none], obj.get("digest")) image = from_str(obj.get("image")) image_type = from_union([from_str, from_none], obj.get("imageType")) media_type = from_union([from_str, from_none], obj.get("mediaType")) platform = from_union([ImagePlatform.from_dict, from_none], obj.get("platform")) size = from_union([from_str, from_none], obj.get("size")) return InvocationImage(image, digest, image_type, media_type, platform, size)
(obj: Any) -> cnab.types.InvocationImage
8,633
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["digest"] = from_union([from_str, from_none], self.digest) result["image"] = from_str(self.image) result["imageType"] = from_union([from_str, from_none], self.image_type) result["mediaType"] = from_union([from_str, from_none], self.media_type) result["platform"] = from_union( [lambda x: to_class(ImagePlatform, x), from_none], self.platform ) result["size"] = from_union([from_str, from_none], self.size) return clean(result)
(self) -> dict
8,634
cnab.types
Maintainer
Maintainer(name: str, email: Optional[str] = None, url: Optional[str] = None)
class Maintainer: name: str email: Optional[str] = None url: Optional[str] = None @staticmethod def from_dict(obj: Any) -> "Maintainer": assert isinstance(obj, dict) name = from_union([from_str, from_none], obj.get("name")) email = from_union([from_str, from_none], obj.get("email")) url = from_union([from_str, from_none], obj.get("url")) return Maintainer(name, email, url) def to_dict(self) -> dict: result: dict = {} result["name"] = from_union([from_str, from_none], self.name) result["email"] = from_union([from_str, from_none], self.email) result["url"] = from_union([from_str, from_none], self.url) return clean(result)
(name: str, email: Optional[str] = None, url: Optional[str] = None) -> None
8,639
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["name"] = from_union([from_str, from_none], self.name) result["email"] = from_union([from_str, from_none], self.email) result["url"] = from_union([from_str, from_none], self.url) return clean(result)
(self) -> dict
8,640
cnab.types
Metadata
Metadata(description: Optional[str] = None)
class Metadata: description: Optional[str] = None @staticmethod def from_dict(obj: Any) -> "Metadata": assert isinstance(obj, dict) description = from_union([from_str, from_none], obj.get("description")) return Metadata(description) def to_dict(self) -> dict: result: dict = {} result["description"] = from_union([from_str, from_none], self.description) return clean(result)
(description: Optional[str] = None) -> None
8,644
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "Metadata": assert isinstance(obj, dict) description = from_union([from_str, from_none], obj.get("description")) return Metadata(description)
(obj: Any) -> cnab.types.Metadata
8,645
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["description"] = from_union([from_str, from_none], self.description) return clean(result)
(self) -> dict
8,646
cnab.types
Parameter
Parameter(type: str, destination: cnab.types.Destination, default_value: Union[bool, int, NoneType, str] = None, allowed_values: Optional[List[Any]] = <factory>, max_length: Optional[int] = None, max_value: Optional[int] = None, metadata: Optional[cnab.types.Metadata] = None, min_length: Optional[int] = None, min_value: Optional[int] = None, required: Optional[bool] = None)
class Parameter: type: str destination: Destination default_value: Union[bool, int, None, str] = None allowed_values: Optional[List[Any]] = field(default_factory=list) max_length: Optional[int] = None max_value: Optional[int] = None metadata: Optional[Metadata] = None min_length: Optional[int] = None min_value: Optional[int] = None required: Optional[bool] = None @staticmethod def from_dict(obj: Any) -> "Parameter": assert isinstance(obj, dict) allowed_values = from_union( [lambda x: from_list(lambda x: x, x), from_none], obj.get("allowedValues") ) default_value = from_union( [from_int, from_bool, from_none, from_str], obj.get("defaultValue") ) destination = from_union([Destination.from_dict], obj.get("destination")) max_length = from_union([from_int, from_none], obj.get("maxLength")) max_value = from_union([from_int, from_none], obj.get("maxValue")) metadata = from_union([Metadata.from_dict, from_none], obj.get("metadata")) min_length = from_union([from_int, from_none], obj.get("minLength")) min_value = from_union([from_int, from_none], obj.get("minValue")) required = from_union([from_bool, from_none], obj.get("required")) type = from_str(obj.get("type")) return Parameter( type, destination, default_value, allowed_values, max_length, max_value, metadata, min_length, min_value, required, ) def to_dict(self) -> dict: result: dict = {} result["allowedValues"] = from_list(lambda x: x, self.allowed_values) result["destination"] = from_union( [lambda x: to_class(Destination, x)], self.destination ) result["maxLength"] = from_union([from_int, from_none], self.max_length) result["maxValue"] = from_union([from_int, from_none], self.max_value) result["metadata"] = from_union( [lambda x: to_class(Metadata, x), from_none], self.metadata ) result["minLength"] = from_union([from_int, from_none], self.min_length) result["minValue"] = from_union([from_int, from_none], self.min_value) result["required"] = from_union([from_bool, from_none], self.required) result["type"] = from_str(self.type) return clean(result)
(type: str, destination: cnab.types.Destination, default_value: Union[bool, int, NoneType, str] = None, allowed_values: Optional[List[Any]] = <factory>, max_length: Optional[int] = None, max_value: Optional[int] = None, metadata: Optional[cnab.types.Metadata] = None, min_length: Optional[int] = None, min_value: Optional[int] = None, required: Optional[bool] = None) -> None
8,650
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "Parameter": assert isinstance(obj, dict) allowed_values = from_union( [lambda x: from_list(lambda x: x, x), from_none], obj.get("allowedValues") ) default_value = from_union( [from_int, from_bool, from_none, from_str], obj.get("defaultValue") ) destination = from_union([Destination.from_dict], obj.get("destination")) max_length = from_union([from_int, from_none], obj.get("maxLength")) max_value = from_union([from_int, from_none], obj.get("maxValue")) metadata = from_union([Metadata.from_dict, from_none], obj.get("metadata")) min_length = from_union([from_int, from_none], obj.get("minLength")) min_value = from_union([from_int, from_none], obj.get("minValue")) required = from_union([from_bool, from_none], obj.get("required")) type = from_str(obj.get("type")) return Parameter( type, destination, default_value, allowed_values, max_length, max_value, metadata, min_length, min_value, required, )
(obj: Any) -> cnab.types.Parameter
8,651
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["allowedValues"] = from_list(lambda x: x, self.allowed_values) result["destination"] = from_union( [lambda x: to_class(Destination, x)], self.destination ) result["maxLength"] = from_union([from_int, from_none], self.max_length) result["maxValue"] = from_union([from_int, from_none], self.max_value) result["metadata"] = from_union( [lambda x: to_class(Metadata, x), from_none], self.metadata ) result["minLength"] = from_union([from_int, from_none], self.min_length) result["minValue"] = from_union([from_int, from_none], self.min_value) result["required"] = from_union([from_bool, from_none], self.required) result["type"] = from_str(self.type) return clean(result)
(self) -> dict
8,652
cnab.types
Ref
Ref(field: Optional[str] = None, media_type: Optional[str] = None, path: Optional[str] = None)
class Ref: field: Optional[str] = None media_type: Optional[str] = None path: Optional[str] = None @staticmethod def from_dict(obj: Any) -> "Ref": assert isinstance(obj, dict) field = from_union([from_str, from_none], obj.get("field")) media_type = from_union([from_str, from_none], obj.get("mediaType")) path = from_union([from_str, from_none], obj.get("path")) return Ref(field, media_type, path) def to_dict(self) -> dict: result: dict = {} result["field"] = from_union([from_str, from_none], self.field) result["mediaType"] = from_union([from_str, from_none], self.media_type) result["path"] = from_union([from_str, from_none], self.path) return clean(result)
(field: Optional[str] = None, media_type: Optional[str] = None, path: Optional[str] = None) -> None
8,656
cnab.types
from_dict
null
@staticmethod def from_dict(obj: Any) -> "Ref": assert isinstance(obj, dict) field = from_union([from_str, from_none], obj.get("field")) media_type = from_union([from_str, from_none], obj.get("mediaType")) path = from_union([from_str, from_none], obj.get("path")) return Ref(field, media_type, path)
(obj: Any) -> cnab.types.Ref
8,657
cnab.types
to_dict
null
def to_dict(self) -> dict: result: dict = {} result["field"] = from_union([from_str, from_none], self.field) result["mediaType"] = from_union([from_str, from_none], self.media_type) result["path"] = from_union([from_str, from_none], self.path) return clean(result)
(self) -> dict
8,662
ipaddr
AddressValueError
A Value Error related to the address.
class AddressValueError(ValueError): """A Value Error related to the address."""
null
8,664
ipaddr
collapse_address_list
Collapse a list of IP objects. Example: collapse_address_list([IPv4('1.1.0.0/24'), IPv4('1.1.1.0/24')]) -> [IPv4('1.1.0.0/23')] Args: addresses: A list of IPv4Network or IPv6Network objects. Returns: A list of IPv4Network or IPv6Network objects depending on what we were passed. Raises: TypeError: If passed a list of mixed version objects.
def collapse_address_list(addresses): """Collapse a list of IP objects. Example: collapse_address_list([IPv4('1.1.0.0/24'), IPv4('1.1.1.0/24')]) -> [IPv4('1.1.0.0/23')] Args: addresses: A list of IPv4Network or IPv6Network objects. Returns: A list of IPv4Network or IPv6Network objects depending on what we were passed. Raises: TypeError: If passed a list of mixed version objects. """ i = 0 addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseIP): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( str(ip), str(ips[-1]))) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( str(ip), str(ips[-1]))) ips.append(ip.ip) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( str(ip), str(nets[-1]))) nets.append(ip) # sort and dedup ips = sorted(set(ips)) nets = sorted(set(nets)) while i < len(ips): (first, last, last_index) = _find_address_range(ips[i:]) i += last_index + 1 addrs.extend(summarize_address_range(first, last)) return _collapse_address_list_recursive(sorted( addrs + nets, key=_BaseNet._get_networks_key))
(addresses)
8,665
ipaddr
IPAddress
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. version: An Integer, 4 or 6. If set, don't try to automatically determine what the IP address type is. important for things like IPAddress(1), which could be IPv4, '0.0.0.1', or IPv6, '::1'. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address.
def IPAddress(address, version=None): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. version: An Integer, 4 or 6. If set, don't try to automatically determine what the IP address type is. important for things like IPAddress(1), which could be IPv4, '0.0.0.1', or IPv6, '::1'. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. """ if version: if version == 4: return IPv4Address(address) elif version == 6: return IPv6Address(address) try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address)
(address, version=None)
8,666
ipaddr
IPNetwork
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. version: An Integer, if set, don't try to automatically determine what the IP address type is. important for things like IPNetwork(1), which could be IPv4, '0.0.0.1/32', or IPv6, '::1/128'. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if a strict network was requested and a strict network wasn't given.
def IPNetwork(address, version=None, strict=False): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. version: An Integer, if set, don't try to automatically determine what the IP address type is. important for things like IPNetwork(1), which could be IPv4, '0.0.0.1/32', or IPv6, '::1/128'. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if a strict network was requested and a strict network wasn't given. """ if version: if version == 4: return IPv4Network(address, strict) elif version == 6: return IPv6Network(address, strict) try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address)
(address, version=None, strict=False)
8,667
ipaddr
IPv4Address
Represent and manipulate single IPv4 Addresses.
class IPv4Address(_BaseV4, _BaseIP): """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address): """ Args: address: A string or integer representing the IP '192.168.1.1' Additionally, an integer can be passed, so IPv4Address('192.168.1.1') == IPv4Address(3232235777). or, more generally IPv4Address(int(IPv4Address('192.168.1.1'))) == IPv4Address('192.168.1.1') Raises: AddressValueError: If ipaddr isn't a valid IPv4 address. """ _BaseV4.__init__(self, address) # Efficient copy constructor. if isinstance(address, IPv4Address): self._ip = address._ip return # Efficient constructor from integer. if isinstance(address, (int, long)): self._ip = address if address < 0 or address > self._ALL_ONES: raise AddressValueError(address) return # Constructing from a packed address if isinstance(address, Bytes): try: self._ip, = struct.unpack('!I', address) except struct.error: raise AddressValueError(address) # Wrong length. return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str)
(address)
8,668
ipaddr
__add__
null
def __add__(self, other): if not isinstance(other, int): return NotImplemented return IPAddress(int(self) + other, version=self._version)
(self, other)
8,669
ipaddr
__eq__
null
def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except AttributeError: return NotImplemented
(self, other)
8,670
ipaddr
__ge__
null
def __ge__(self, other): lt = self.__lt__(other) if lt is NotImplemented: return NotImplemented return not lt
(self, other)
8,671
ipaddr
__gt__
null
def __gt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( str(self), str(other))) if not isinstance(other, _BaseIP): raise TypeError('%s and %s are not of the same type' % ( str(self), str(other))) if self._ip != other._ip: return self._ip > other._ip return False
(self, other)
8,672
ipaddr
__hash__
null
def __hash__(self): return hash(hex(long(self._ip)))
(self)
8,673
ipaddr
__hex__
null
def __hex__(self): return hex(self._ip)
(self)
8,674
ipaddr
__index__
null
def __index__(self): return self._ip
(self)
8,675
ipaddr
__init__
Args: address: A string or integer representing the IP '192.168.1.1' Additionally, an integer can be passed, so IPv4Address('192.168.1.1') == IPv4Address(3232235777). or, more generally IPv4Address(int(IPv4Address('192.168.1.1'))) == IPv4Address('192.168.1.1') Raises: AddressValueError: If ipaddr isn't a valid IPv4 address.
def __init__(self, address): """ Args: address: A string or integer representing the IP '192.168.1.1' Additionally, an integer can be passed, so IPv4Address('192.168.1.1') == IPv4Address(3232235777). or, more generally IPv4Address(int(IPv4Address('192.168.1.1'))) == IPv4Address('192.168.1.1') Raises: AddressValueError: If ipaddr isn't a valid IPv4 address. """ _BaseV4.__init__(self, address) # Efficient copy constructor. if isinstance(address, IPv4Address): self._ip = address._ip return # Efficient constructor from integer. if isinstance(address, (int, long)): self._ip = address if address < 0 or address > self._ALL_ONES: raise AddressValueError(address) return # Constructing from a packed address if isinstance(address, Bytes): try: self._ip, = struct.unpack('!I', address) except struct.error: raise AddressValueError(address) # Wrong length. return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str)
(self, address)
8,676
ipaddr
__int__
null
def __int__(self): return self._ip
(self)
8,677
ipaddr
__le__
null
def __le__(self, other): gt = self.__gt__(other) if gt is NotImplemented: return NotImplemented return not gt
(self, other)
8,678
ipaddr
__lt__
null
def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( str(self), str(other))) if not isinstance(other, _BaseIP): raise TypeError('%s and %s are not of the same type' % ( str(self), str(other))) if self._ip != other._ip: return self._ip < other._ip return False
(self, other)
8,679
ipaddr
__ne__
null
def __ne__(self, other): eq = self.__eq__(other) if eq is NotImplemented: return NotImplemented return not eq
(self, other)
8,681
ipaddr
__str__
null
def __str__(self): return '%s' % self._string_from_ip_int(self._ip)
(self)
8,682
ipaddr
__sub__
null
def __sub__(self, other): if not isinstance(other, int): return NotImplemented return IPAddress(int(self) - other, version=self._version)
(self, other)
8,683
ipaddr
_explode_shorthand_ip_string
null
def _explode_shorthand_ip_string(self): return str(self)
(self)
8,684
ipaddr
_get_address_key
null
def _get_address_key(self): return (self._version, self)
(self)
8,685
ipaddr
_ip_int_from_string
Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address.
def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError(ip_str) packed_ip = 0 for oc in octets: try: packed_ip = (packed_ip << 8) | self._parse_octet(oc) except ValueError: raise AddressValueError(ip_str) return packed_ip
(self, ip_str)
8,686
ipaddr
_parse_octet
Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255].
def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): raise ValueError octet_int = int(octet_str, 10) # Disallow leading zeroes, because no clear standard exists on # whether these should be interpreted as decimal or octal. if octet_int > 255 or (octet_str[0] == '0' and len(octet_str) > 1): raise ValueError return octet_int
(self, octet_str)
8,687
ipaddr
_string_from_ip_int
Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation.
def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ octets = [] for _ in xrange(4): octets.insert(0, str(ip_int & 0xFF)) ip_int >>= 8 return '.'.join(octets)
(self, ip_int)
8,688
ipaddr
IPv4Network
This class represents and manipulates 32-bit IPv4 networks. Attributes: [examples for IPv4Network('1.2.3.4/27')] ._ip: 16909060 .ip: IPv4Address('1.2.3.4') .network: IPv4Address('1.2.3.0') .hostmask: IPv4Address('0.0.0.31') .broadcast: IPv4Address('1.2.3.31') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27
class IPv4Network(_BaseV4, _BaseNet): """This class represents and manipulates 32-bit IPv4 networks. Attributes: [examples for IPv4Network('1.2.3.4/27')] ._ip: 16909060 .ip: IPv4Address('1.2.3.4') .network: IPv4Address('1.2.3.0') .hostmask: IPv4Address('0.0.0.31') .broadcast: IPv4Address('1.2.3.31') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27 """ def __init__(self, address, strict=False): """Instantiate a new IPv4 network object. Args: address: The IPv4 network as a string, 2-tuple, or any format supported by the IPv4Address constructor. Strings typically use CIDR format, such as '192.0.2.0/24'. If a dotted-quad is provided after the '/', it is treated as a netmask if it starts with a nonzero bit (e.g. 255.0.0.0 == /8) or a hostmask if it starts with a zero bit (e.g. /0.0.0.255 == /8), with the single exception of an all-zero mask which is treated as /0. The 2-tuple format consists of an (ip, prefixlen), where ip is any format recognized by the IPv4Address constructor, and prefixlen is an integer from 0 through 32. A plain IPv4 address (in any format) will be forwarded to the IPv4Address constructor, with an implied prefixlen of 32. For example, the following inputs are equivalent: IPv4Network('192.0.2.1/32') IPv4Network('192.0.2.1/255.255.255.255') IPv4Network('192.0.2.1') IPv4Network(0xc0000201) IPv4Network(IPv4Address('192.0.2.1')) IPv4Network(('192.0.2.1', 32)) IPv4Network((0xc0000201, 32)) IPv4Network((IPv4Address('192.0.2.1'), 32)) strict: A boolean. If true, ensure that we have been passed A true network address, eg, 192.168.1.0/24 and not an IP address on a network, eg, 192.168.1.1/24. Raises: AddressValueError: If ipaddr isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict was True and a network address was not supplied. """ _BaseNet.__init__(self, address) _BaseV4.__init__(self, address) # Constructing from a single IP address. if isinstance(address, (int, long, Bytes, IPv4Address)): self.ip = IPv4Address(address) self._ip = self.ip._ip self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) return # Constructing from an (ip, prefixlen) tuple. if isinstance(address, tuple): try: ip, prefixlen = address except ValueError: raise AddressValueError(address) self.ip = IPv4Address(ip) self._ip = self.ip._ip self._prefixlen = self._prefix_from_prefix_int(prefixlen) else: # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = str(address).split('/') if len(addr) > 2: raise AddressValueError(address) self._ip = self._ip_int_from_string(addr[0]) self.ip = IPv4Address(self._ip) if len(addr) == 2: try: # Check for a netmask in prefix length form. self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if self.ip != self.network: raise ValueError('%s has host bits set' % self.ip) if self._prefixlen == (self._max_prefixlen - 1): self.iterhosts = self.__iter__ # backwards compatibility IsRFC1918 = lambda self: self.is_private IsMulticast = lambda self: self.is_multicast IsLoopback = lambda self: self.is_loopback IsLinkLocal = lambda self: self.is_link_local
(address, strict=False)
8,689
ipaddr
address_exclude
Remove an address from a larger block. For example: addr1 = IPNetwork('10.1.1.0/24') addr2 = IPNetwork('10.1.1.0/26') addr1.address_exclude(addr2) = [IPNetwork('10.1.1.64/26'), IPNetwork('10.1.1.128/25')] or IPv6: addr1 = IPNetwork('::1/32') addr2 = IPNetwork('::1/128') addr1.address_exclude(addr2) = [IPNetwork('::0/128'), IPNetwork('::2/127'), IPNetwork('::4/126'), IPNetwork('::8/125'), ... IPNetwork('0:0:8000::/33')] Args: other: An IPvXNetwork object of the same type. Returns: A sorted list of IPvXNetwork objects addresses which is self minus other. Raises: TypeError: If self and other are of difffering address versions, or if other is not a network object. ValueError: If other is not completely contained by self.
def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = IPNetwork('10.1.1.0/24') addr2 = IPNetwork('10.1.1.0/26') addr1.address_exclude(addr2) = [IPNetwork('10.1.1.64/26'), IPNetwork('10.1.1.128/25')] or IPv6: addr1 = IPNetwork('::1/32') addr2 = IPNetwork('::1/128') addr1.address_exclude(addr2) = [IPNetwork('::0/128'), IPNetwork('::2/127'), IPNetwork('::4/126'), IPNetwork('::8/125'), ... IPNetwork('0:0:8000::/33')] Args: other: An IPvXNetwork object of the same type. Returns: A sorted list of IPvXNetwork objects addresses which is self minus other. Raises: TypeError: If self and other are of difffering address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( str(self), str(other))) if not isinstance(other, _BaseNet): raise TypeError("%s is not a network object" % str(other)) if other not in self: raise ValueError('%s not contained in %s' % (str(other), str(self))) if other == self: return [] ret_addrs = [] # Make sure we're comparing the network of other. other = IPNetwork('%s/%s' % (str(other.network), str(other.prefixlen)), version=other._version) s1, s2 = self.subnet() while s1 != other and s2 != other: if other in s1: ret_addrs.append(s2) s1, s2 = s1.subnet() elif other in s2: ret_addrs.append(s1) s1, s2 = s2.subnet() else: # If we got here, there's a bug somewhere. assert True == False, ('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (str(s1), str(s2), str(other))) if s1 == other: ret_addrs.append(s2) elif s2 == other: ret_addrs.append(s1) else: # If we got here, there's a bug somewhere. assert True == False, ('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (str(s1), str(s2), str(other))) return sorted(ret_addrs, key=_BaseNet._get_networks_key)
(self, other)
8,690
ipaddr
compare_networks
Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4('1.1.1.0/24') < IPv4('1.1.2.0/24') IPv6('1080::200C:417A') < IPv6('1080::200B:417B') 0 if self == other eg: IPv4('1.1.1.1/24') == IPv4('1.1.1.2/24') IPv6('1080::200C:417A/96') == IPv6('1080::200C:417B/96') 1 if self > other eg: IPv4('1.1.1.0/24') > IPv4('1.1.0.0/24') IPv6('1080::1:200C:417A/112') > IPv6('1080::0:200C:417A/112') If the IP versions of self and other are different, returns: -1 if self._version < other._version eg: IPv4('10.0.0.1/24') < IPv6('::1/128') 1 if self._version > other._version eg: IPv6('::1/128') > IPv4('255.255.255.0/24')
def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4('1.1.1.0/24') < IPv4('1.1.2.0/24') IPv6('1080::200C:417A') < IPv6('1080::200B:417B') 0 if self == other eg: IPv4('1.1.1.1/24') == IPv4('1.1.1.2/24') IPv6('1080::200C:417A/96') == IPv6('1080::200C:417B/96') 1 if self > other eg: IPv4('1.1.1.0/24') > IPv4('1.1.0.0/24') IPv6('1080::1:200C:417A/112') > IPv6('1080::0:200C:417A/112') If the IP versions of self and other are different, returns: -1 if self._version < other._version eg: IPv4('10.0.0.1/24') < IPv6('::1/128') 1 if self._version > other._version eg: IPv6('::1/128') > IPv4('255.255.255.0/24') """ if self._version < other._version: return -1 if self._version > other._version: return 1 # self._version == other._version below here: if self.network < other.network: return -1 if self.network > other.network: return 1 # self.network == other.network below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 # self.network == other.network and self.netmask == other.netmask return 0
(self, other)
8,691
ipaddr
__contains__
null
def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNet): return (self.network <= other.network and self.broadcast >= other.broadcast) # dealing with another address else: return (int(self.network) <= int(other._ip) <= int(self.broadcast))
(self, other)
8,692
ipaddr
<lambda>
null
IsLinkLocal = lambda self: self.is_link_local
(self)
8,693
ipaddr
<lambda>
null
IsLoopback = lambda self: self.is_loopback
(self)
8,694
ipaddr
<lambda>
null
IsMulticast = lambda self: self.is_multicast
(self)
8,695
ipaddr
<lambda>
null
IsRFC1918 = lambda self: self.is_private
(self)
8,696
ipaddr
subnet
Return a list of subnets, rather than an iterator.
def subnet(self, prefixlen_diff=1, new_prefix=None): """Return a list of subnets, rather than an iterator.""" return list(self.iter_subnets(prefixlen_diff, new_prefix))
(self, prefixlen_diff=1, new_prefix=None)
8,697
ipaddr
supernet
The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network)
def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) return IPNetwork('%s/%s' % (str(self.network), str(self.prefixlen - prefixlen_diff)), version=self._version)
(self, prefixlen_diff=1, new_prefix=None)
8,699
ipaddr
__eq__
null
def __eq__(self, other): try: return (self._version == other._version and self.network == other.network and int(self.netmask) == int(other.netmask)) except AttributeError: if isinstance(other, _BaseIP): return (self._version == other._version and self._ip == other._ip)
(self, other)
8,701
ipaddr
__getitem__
null
def __getitem__(self, n): network = int(self.network) broadcast = int(self.broadcast) if n >= 0: if network + n > broadcast: raise IndexError return IPAddress(network + n, version=self._version) else: n += 1 if broadcast + n < network: raise IndexError return IPAddress(broadcast + n, version=self._version)
(self, n)
8,702
ipaddr
__gt__
null
def __gt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( str(self), str(other))) if not isinstance(other, _BaseNet): raise TypeError('%s and %s are not of the same type' % ( str(self), str(other))) if self.network != other.network: return self.network > other.network if self.netmask != other.netmask: return self.netmask > other.netmask return False
(self, other)
8,703
ipaddr
__hash__
null
def __hash__(self): return hash(int(self.network) ^ int(self.netmask))
(self)
8,706
ipaddr
__init__
Instantiate a new IPv4 network object. Args: address: The IPv4 network as a string, 2-tuple, or any format supported by the IPv4Address constructor. Strings typically use CIDR format, such as '192.0.2.0/24'. If a dotted-quad is provided after the '/', it is treated as a netmask if it starts with a nonzero bit (e.g. 255.0.0.0 == /8) or a hostmask if it starts with a zero bit (e.g. /0.0.0.255 == /8), with the single exception of an all-zero mask which is treated as /0. The 2-tuple format consists of an (ip, prefixlen), where ip is any format recognized by the IPv4Address constructor, and prefixlen is an integer from 0 through 32. A plain IPv4 address (in any format) will be forwarded to the IPv4Address constructor, with an implied prefixlen of 32. For example, the following inputs are equivalent: IPv4Network('192.0.2.1/32') IPv4Network('192.0.2.1/255.255.255.255') IPv4Network('192.0.2.1') IPv4Network(0xc0000201) IPv4Network(IPv4Address('192.0.2.1')) IPv4Network(('192.0.2.1', 32)) IPv4Network((0xc0000201, 32)) IPv4Network((IPv4Address('192.0.2.1'), 32)) strict: A boolean. If true, ensure that we have been passed A true network address, eg, 192.168.1.0/24 and not an IP address on a network, eg, 192.168.1.1/24. Raises: AddressValueError: If ipaddr isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict was True and a network address was not supplied.
def __init__(self, address, strict=False): """Instantiate a new IPv4 network object. Args: address: The IPv4 network as a string, 2-tuple, or any format supported by the IPv4Address constructor. Strings typically use CIDR format, such as '192.0.2.0/24'. If a dotted-quad is provided after the '/', it is treated as a netmask if it starts with a nonzero bit (e.g. 255.0.0.0 == /8) or a hostmask if it starts with a zero bit (e.g. /0.0.0.255 == /8), with the single exception of an all-zero mask which is treated as /0. The 2-tuple format consists of an (ip, prefixlen), where ip is any format recognized by the IPv4Address constructor, and prefixlen is an integer from 0 through 32. A plain IPv4 address (in any format) will be forwarded to the IPv4Address constructor, with an implied prefixlen of 32. For example, the following inputs are equivalent: IPv4Network('192.0.2.1/32') IPv4Network('192.0.2.1/255.255.255.255') IPv4Network('192.0.2.1') IPv4Network(0xc0000201) IPv4Network(IPv4Address('192.0.2.1')) IPv4Network(('192.0.2.1', 32)) IPv4Network((0xc0000201, 32)) IPv4Network((IPv4Address('192.0.2.1'), 32)) strict: A boolean. If true, ensure that we have been passed A true network address, eg, 192.168.1.0/24 and not an IP address on a network, eg, 192.168.1.1/24. Raises: AddressValueError: If ipaddr isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict was True and a network address was not supplied. """ _BaseNet.__init__(self, address) _BaseV4.__init__(self, address) # Constructing from a single IP address. if isinstance(address, (int, long, Bytes, IPv4Address)): self.ip = IPv4Address(address) self._ip = self.ip._ip self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) return # Constructing from an (ip, prefixlen) tuple. if isinstance(address, tuple): try: ip, prefixlen = address except ValueError: raise AddressValueError(address) self.ip = IPv4Address(ip) self._ip = self.ip._ip self._prefixlen = self._prefix_from_prefix_int(prefixlen) else: # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = str(address).split('/') if len(addr) > 2: raise AddressValueError(address) self._ip = self._ip_int_from_string(addr[0]) self.ip = IPv4Address(self._ip) if len(addr) == 2: try: # Check for a netmask in prefix length form. self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if self.ip != self.network: raise ValueError('%s has host bits set' % self.ip) if self._prefixlen == (self._max_prefixlen - 1): self.iterhosts = self.__iter__
(self, address, strict=False)