Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def not_send_status(func): @functools.wraps(func) def wrapper(self, response, task): self._extinfo['not_send_status'] = True function = func.__get__(self, self.__class__) return self._run_func(function, response, task) return wrapper
[ "\n Do not send process status package back to scheduler.\n\n It's used by callbacks like on_message, on_result etc...\n " ]
Please provide a description of the function:def config(_config=None, **kwargs): if _config is None: _config = {} _config.update(kwargs) def wrapper(func): func._config = _config return func return wrapper
[ "\n A decorator for setting the default kwargs of `BaseHandler.crawl`.\n Any self.crawl with this callback will use this config.\n " ]
Please provide a description of the function:def every(minutes=NOTSET, seconds=NOTSET): def wrapper(func): # mark the function with variable 'is_cronjob=True', the function would be # collected into the list Handler._cron_jobs by meta class func.is_cronjob = True # collect inte...
[ "\n method will been called every minutes or seconds\n " ]
Please provide a description of the function:def catch_error(func): import amqp try: import pika.exceptions connect_exceptions = ( pika.exceptions.ConnectionClosed, pika.exceptions.AMQPConnectionError, ) except ImportError: connect_exceptions = ()...
[ "Catch errors of rabbitmq then reconnect" ]
Please provide a description of the function:def reconnect(self): import pika import pika.exceptions self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url)) self.channel = self.connection.channel() try: self.channel.queue_declare(self.na...
[ "Reconnect to rabbitmq server" ]
Please provide a description of the function:def reconnect(self): parsed = urlparse.urlparse(self.amqp_url) port = parsed.port or 5672 self.connection = amqp.Connection(host="%s:%s" % (parsed.hostname, port), userid=parsed.username or 'guest', ...
[ "Reconnect to rabbitmq server" ]
Please provide a description of the function:def put(self, taskid, priority=0, exetime=0): now = time.time() task = InQueueTask(taskid, priority, exetime) self.mutex.acquire() if taskid in self.priority_queue: self.priority_queue.put(task) elif taskid in se...
[ "\n Put a task into task queue\n \n when use heap sort, if we put tasks(with the same priority and exetime=0) into queue,\n the queue is not a strict FIFO queue, but more like a FILO stack.\n It is very possible that when there are continuous big flow, the speed of select is \n ...
Please provide a description of the function:def get(self): '''Get a task from queue when bucket available''' if self.bucket.get() < 1: return None now = time.time() self.mutex.acquire() try: task = self.priority_queue.get_nowait() self.bucket....
[]
Please provide a description of the function:def done(self, taskid): '''Mark task done''' if taskid in self.processing: self.mutex.acquire() if taskid in self.processing: del self.processing[taskid] self.mutex.release() return True ...
[]
Please provide a description of the function:def is_processing(self, taskid): ''' return True if taskid is in processing ''' return taskid in self.processing and self.processing[taskid].taskid
[]
Please provide a description of the function:def logstr(self): result = [] formater = LogFormatter(color=False) for record in self.logs: if isinstance(record, six.string_types): result.append(pretty_unicode(record)) else: if recor...
[ "handler the log records to formatted string" ]
Please provide a description of the function:def on_task(self, task, response): '''Deal one task''' start_time = time.time() response = rebuild_response(response) try: assert 'taskid' in task, 'need taskid in task' project = task['project'] updatetime...
[]
Please provide a description of the function:def run(self): '''Run loop''' logger.info("processor starting...") while not self._quit: try: task, response = self.inqueue.get(timeout=1) self.on_task(task, response) self._exceptions = 0 ...
[]
Please provide a description of the function:def connect_message_queue(name, url=None, maxsize=0, lazy_limit=True): if not url: from pyspider.libs.multiprocessing_queue import Queue return Queue(maxsize=maxsize) parsed = urlparse.urlparse(url) if parsed.scheme == 'amqp': from ...
[ "\n create connection to message queue\n\n name:\n name of message queue\n\n rabbitmq:\n amqp://username:password@host:5672/%2F\n see https://www.rabbitmq.com/uri-spec.html\n beanstalk:\n beanstalk://host:11300/\n redis:\n redis://host:6379/db\n redis://host1...
Please provide a description of the function:def hide_me(tb, g=globals()): base_tb = tb try: while tb and tb.tb_frame.f_globals is not g: tb = tb.tb_next while tb and tb.tb_frame.f_globals is g: tb = tb.tb_next except Exception as e: logging.exception(e) ...
[ "Hide stack traceback of given stack" ]
Please provide a description of the function:def run_in_subprocess(func, *args, **kwargs): from multiprocessing import Process thread = Process(target=func, args=args, kwargs=kwargs) thread.daemon = True thread.start() return thread
[ "Run function in subprocess, return a Process object" ]
Please provide a description of the function:def format_date(date, gmt_offset=0, relative=True, shorter=False, full_format=False): if not date: return '-' if isinstance(date, float) or isinstance(date, int): date = datetime.datetime.utcfromtimestamp(date) now = datetime.datetime.utcnow...
[ "Formats the given date (which should be GMT).\n\n By default, we return a relative time (e.g., \"2 minutes ago\"). You\n can return an absolute date string with ``relative=False``.\n\n You can force a full format date (\"July 10, 1980\") with\n ``full_format=True``.\n\n This method is primarily inte...
Please provide a description of the function:def utf8(string): if isinstance(string, six.text_type): return string.encode('utf8') elif isinstance(string, six.binary_type): return string else: return six.text_type(string).encode('utf8')
[ "\n Make sure string is utf8 encoded bytes.\n\n If parameter is a object, object.__str__ will been called before encode as bytes\n " ]
Please provide a description of the function:def text(string, encoding='utf8'): if isinstance(string, six.text_type): return string elif isinstance(string, six.binary_type): return string.decode(encoding) else: return six.text_type(string)
[ "\n Make sure string is unicode type, decode with given encoding if it's not.\n\n If parameter is a object, object.__str__ will been called\n " ]
Please provide a description of the function:def pretty_unicode(string): if isinstance(string, six.text_type): return string try: return string.decode("utf8") except UnicodeDecodeError: return string.decode('Latin-1').encode('unicode_escape').decode("utf8")
[ "\n Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed.\n " ]
Please provide a description of the function:def unicode_string(string): if isinstance(string, six.text_type): return string try: return string.decode("utf8") except UnicodeDecodeError: return '[BASE64-DATA]' + base64.b64encode(string) + '[/BASE64-DATA]'
[ "\n Make sure string is unicode, try to default with utf8, or base64 if failed.\n\n can been decode by `decode_unicode_string`\n " ]
Please provide a description of the function:def unicode_dict(_dict): r = {} for k, v in iteritems(_dict): r[unicode_obj(k)] = unicode_obj(v) return r
[ "\n Make sure keys and values of dict is unicode.\n " ]
Please provide a description of the function:def unicode_obj(obj): if isinstance(obj, dict): return unicode_dict(obj) elif isinstance(obj, (list, tuple)): return unicode_list(obj) elif isinstance(obj, six.string_types): return unicode_string(obj) elif isinstance(obj, (int, f...
[ "\n Make sure keys and values of dict/list/tuple is unicode. bytes will encode in base64.\n\n Can been decode by `decode_unicode_obj`\n " ]
Please provide a description of the function:def decode_unicode_string(string): if string.startswith('[BASE64-DATA]') and string.endswith('[/BASE64-DATA]'): return base64.b64decode(string[len('[BASE64-DATA]'):-len('[/BASE64-DATA]')]) return string
[ "\n Decode string encoded by `unicode_string`\n " ]
Please provide a description of the function:def decode_unicode_obj(obj): if isinstance(obj, dict): r = {} for k, v in iteritems(obj): r[decode_unicode_string(k)] = decode_unicode_obj(v) return r elif isinstance(obj, six.string_types): return decode_unicode_strin...
[ "\n Decode unicoded dict/list/tuple encoded by `unicode_obj`\n " ]
Please provide a description of the function:def load_object(name): if "." not in name: raise Exception('load object need module.object') module_name, object_name = name.rsplit('.', 1) if six.PY2: module = __import__(module_name, globals(), locals(), [utf8(object_name)], -1) else:...
[ "Load object from module" ]
Please provide a description of the function:def get_python_console(namespace=None): if namespace is None: import inspect frame = inspect.currentframe() caller = frame.f_back if not caller: logging.error("can't find caller who start this console.") calle...
[ "\n Return a interactive python console instance with caller's stack\n " ]
Please provide a description of the function:def python_console(namespace=None): if namespace is None: import inspect frame = inspect.currentframe() caller = frame.f_back if not caller: logging.error("can't find caller who start this console.") caller = ...
[ "Start a interactive python console with caller's stack" ]
Please provide a description of the function:def handler(self, environ, start_response): if environ['REQUEST_METHOD'] == 'POST': return self.handle_POST(environ, start_response) else: start_response("400 Bad request", [('Content-Type', 'text/plain')]) return...
[ "XMLRPC service for windmill browser core to communicate with" ]
Please provide a description of the function:def handle_POST(self, environ, start_response): try: # Get arguments by reading body of request. # We read this in chunks to avoid straining # socket.read(); around the 10 or 15Mb mark, some platforms # begin ...
[ "Handles the HTTP POST request.\n\n Attempts to interpret all HTTP POST requests as XML-RPC calls,\n which are forwarded to the server's _dispatch method for handling.\n\n Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher.\n " ]
Please provide a description of the function:def connect_database(url): db = _connect_database(url) db.copy = lambda: _connect_database(url) return db
[ "\n create database object by url\n\n mysql:\n mysql+type://user:passwd@host:port/database\n sqlite:\n # relative path\n sqlite+type:///path/to/database.db\n # absolute path\n sqlite+type:////path/to/database.db\n # memory database\n sqlite+type://\n mong...
Please provide a description of the function:def _update_projects(self): '''Check project update''' now = time.time() if ( not self._force_update_project and self._last_update_project + self.UPDATE_PROJECT_INTERVAL > now ): return for p...
[]
Please provide a description of the function:def _update_project(self, project): '''update one project''' if project['name'] not in self.projects: self.projects[project['name']] = Project(self, project) else: self.projects[project['name']].update(project) project...
[]
Please provide a description of the function:def _load_tasks(self, project): '''load tasks from database''' task_queue = project.task_queue for task in self.taskdb.load_tasks( self.taskdb.ACTIVE, project.name, self.scheduler_task_fields ): taskid = task['task...
[]
Please provide a description of the function:def task_verify(self, task): ''' return False if any of 'taskid', 'project', 'url' is not in task dict or project in not in task_queue ''' for each in ('taskid', 'project', 'url', ): if each not in task or n...
[]
Please provide a description of the function:def put_task(self, task): '''put task to task queue''' _schedule = task.get('schedule', self.default_schedule) self.projects[task['project']].task_queue.put( task['taskid'], priority=_schedule.get('priority', self.default_sched...
[]
Please provide a description of the function:def send_task(self, task, force=True): ''' dispatch task to fetcher out queue may have size limit to prevent block, a send_buffer is used ''' try: self.out_queue.put_nowait(task) except Queue.Full: if f...
[]
Please provide a description of the function:def _check_task_done(self): '''Check status queue''' cnt = 0 try: while True: task = self.status_queue.get_nowait() # check _on_get_info result here if task.get('taskid') == '_on_get_info' an...
[]
Please provide a description of the function:def _check_request(self): '''Check new task queue''' # check _postpone_request first todo = [] for task in self._postpone_request: if task['project'] not in self.projects: continue if self.projects[task[...
[]
Please provide a description of the function:def _check_cronjob(self): now = time.time() self._last_tick = int(self._last_tick) if now - self._last_tick < 1: return False self._last_tick += 1 for project in itervalues(self.projects): if not projec...
[ "Check projects cronjob tick, return True when a new tick is sended" ]
Please provide a description of the function:def _check_select(self): '''Select task to fetch & process''' while self._send_buffer: _task = self._send_buffer.pop() try: # use force=False here to prevent automatic send_buffer append and get exception ...
[]
Please provide a description of the function:def _dump_cnt(self): '''Dump counters to file''' self._cnt['1h'].dump(os.path.join(self.data_path, 'scheduler.1h')) self._cnt['1d'].dump(os.path.join(self.data_path, 'scheduler.1d')) self._cnt['all'].dump(os.path.join(self.data_path, 'schedule...
[]
Please provide a description of the function:def _try_dump_cnt(self): '''Dump counters every 60 seconds''' now = time.time() if now - self._last_dump_cnt > 60: self._last_dump_cnt = now self._dump_cnt() self._print_counter_log()
[]
Please provide a description of the function:def _check_delete(self): '''Check project delete''' now = time.time() for project in list(itervalues(self.projects)): if project.db_status != 'STOP': continue if now - project.updatetime < self.DELETE_TIME: ...
[]
Please provide a description of the function:def quit(self): '''Set quit signal''' self._quit = True # stop xmlrpc server if hasattr(self, 'xmlrpc_server'): self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop) self.xmlrpc_ioloop.add_callback(self.xmlrpc_ioloop...
[]
Please provide a description of the function:def run_once(self): '''comsume queues and feed tasks to fetcher, once''' self._update_projects() self._check_task_done() self._check_request() while self._check_cronjob(): pass self._check_select() self._ch...
[]
Please provide a description of the function:def run(self): '''Start scheduler loop''' logger.info("scheduler starting...") while not self._quit: try: time.sleep(self.LOOP_INTERVAL) self.run_once() self._exceptions = 0 exce...
[]
Please provide a description of the function:def xmlrpc_run(self, port=23333, bind='127.0.0.1', logRequests=False): '''Start xmlrpc interface''' from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication application = WSGIXMLRPCApplication() application.register_function(self.quit, '_...
[]
Please provide a description of the function:def on_new_request(self, task): '''Called when a new request is arrived''' task['status'] = self.taskdb.ACTIVE self.insert_task(task) self.put_task(task) project = task['project'] self._cnt['5m'].event((project, 'pending'), +1...
[]
Please provide a description of the function:def on_old_request(self, task, old_task): '''Called when a crawled task is arrived''' now = time.time() _schedule = task.get('schedule', self.default_schedule) old_schedule = old_task.get('schedule', {}) if _schedule.get('force_updat...
[]
Please provide a description of the function:def on_task_status(self, task): '''Called when a status pack is arrived''' try: procesok = task['track']['process']['ok'] if not self.projects[task['project']].task_queue.done(task['taskid']): logging.error('not process...
[]
Please provide a description of the function:def on_task_done(self, task): '''Called when a task is done and success, called by `on_task_status`''' task['status'] = self.taskdb.SUCCESS task['lastcrawltime'] = time.time() if 'schedule' in task: if task['schedule'].get('auto_r...
[]
Please provide a description of the function:def on_task_failed(self, task): '''Called when a task is failed, called by `on_task_status`''' if 'schedule' not in task: old_task = self.taskdb.get_task(task['project'], task['taskid'], fields=['schedule']) if old_task is None: ...
[]
Please provide a description of the function:def on_select_task(self, task): '''Called when a task is selected to fetch & process''' # inject informations about project logger.info('select %(project)s:%(taskid)s %(url)s', task) project_info = self.projects.get(task['project']) a...
[]
Please provide a description of the function:def _check_select(self): if not self.interactive: return super(OneScheduler, self)._check_select() # waiting for running tasks if self.running_task > 0: return is_crawled = [] def run(project=None): ...
[ "\n interactive mode of select tasks\n ", "\n Crawl given url, same parameters as BaseHandler.crawl\n\n url - url or taskid, parameters will be used if in taskdb\n project - can be ignored if only one project exists.\n " ]
Please provide a description of the function:def on_task_status(self, task): if not self.interactive: super(OneScheduler, self).on_task_status(task) try: procesok = task['track']['process']['ok'] except KeyError as e: logger.error("Bad status pack: %...
[ "Ignore not processing error in interactive mode" ]
Please provide a description of the function:def build_module(project, env=None): '''Build project script as module''' from pyspider.libs import base_handler assert 'name' in project, 'need name of project' assert 'script' in project, 'need script of project' if env is None: ...
[]
Please provide a description of the function:def _need_update(self, project_name, updatetime=None, md5sum=None): '''Check if project_name need update''' if project_name not in self.projects: return True elif md5sum and md5sum != self.projects[project_name]['info'].get('md5sum'): ...
[]
Please provide a description of the function:def _check_projects(self): '''Check projects by last update time''' for project in self.projectdb.check_update(self.last_check_projects, ['name', 'updatetime']): if project['name'] not in self.pro...
[]
Please provide a description of the function:def _update_project(self, project_name): '''Update one project from database''' project = self.projectdb.get(project_name) if not project: return None return self._load_project(project)
[]
Please provide a description of the function:def _load_project(self, project): '''Load project into self.projects from project info dict''' try: project['md5sum'] = utils.md5string(project['script']) ret = self.build_module(project, self.env) self.projects[project['na...
[]
Please provide a description of the function:def get(self, project_name, updatetime=None, md5sum=None): '''get project data object, return None if not exists''' if time.time() - self.last_check_projects > self.CHECK_PROJECTS_INTERVAL: self._check_projects() if self._need_update(proje...
[]
Please provide a description of the function:def get_all(self, name, default=None): if default is None: default = [] return self._headers.get_list(name) or default
[ "make cookie python 3 version use this instead of getheaders" ]
Please provide a description of the function:def status_count(self, project): ''' return a dict ''' pipe = self.redis.pipeline(transaction=False) for status in range(1, 5): pipe.scard(self._gen_status_key(project, status)) ret = pipe.execute() result ...
[]
Please provide a description of the function:def increment(self, n=1): with self.count.get_lock(): self.count.value += n
[ " Increment the counter by n (default = 1) " ]
Please provide a description of the function:def refresh(self): self._changed = False self.es.indices.refresh(index=self.index)
[ "\n Explicitly refresh one or more index, making all operations\n performed since the last refresh available for search.\n " ]
Please provide a description of the function:def send_result(self, type, task, result): '''Send fetch result to processor''' if self.outqueue: try: self.outqueue.put((task, result)) except Exception as e: logger.exception(e)
[]
Please provide a description of the function:def async_fetch(self, task, callback=None): '''Do one fetch''' url = task.get('url', 'data:,') if callback is None: callback = self.send_result type = 'None' start_time = time.time() try: if url.startsw...
[]
Please provide a description of the function:def sync_fetch(self, task): '''Synchronization fetch, usually used in xmlrpc thread''' if not self._running: return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True)) wait_result = threading.Condition() ...
[]
Please provide a description of the function:def data_fetch(self, url, task): '''A fake fetcher for dataurl''' self.on_fetch('data', task) result = {} result['orig_url'] = url result['content'] = dataurl.decode(url) result['headers'] = {} result['status_code'] = 2...
[]
Please provide a description of the function:def http_fetch(self, url, task): '''HTTP fetcher''' start_time = time.time() self.on_fetch('http', task) handle_error = lambda x: self.handle_error('http', url, task, start_time, x) # setup request parameters fetch = self.pack...
[]
Please provide a description of the function:def phantomjs_fetch(self, url, task): '''Fetch with phantomjs proxy''' start_time = time.time() self.on_fetch('phantomjs', task) handle_error = lambda x: self.handle_error('phantomjs', url, task, start_time, x) # check phantomjs proxy...
[]
Please provide a description of the function:def run(self): '''Run loop''' logger.info("fetcher starting...") def queue_loop(): if not self.outqueue or not self.inqueue: return while not self._quit: try: if self.outqueu...
[]
Please provide a description of the function:def quit(self): '''Quit fetcher''' self._running = False self._quit = True self.ioloop.add_callback(self.ioloop.stop) if hasattr(self, 'xmlrpc_server'): self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop) s...
[]
Please provide a description of the function:def xmlrpc_run(self, port=24444, bind='127.0.0.1', logRequests=False): '''Run xmlrpc server''' import umsgpack from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication try: from xmlrpc.client import Binary except ImportE...
[]
Please provide a description of the function:def on_result(self, type, task, result): '''Called after task fetched''' status_code = result.get('status_code', 599) if status_code != 599: status_code = (int(status_code) / 100 * 100) self._cnt['5m'].event((task.get('project'), s...
[]
Please provide a description of the function:def to_dict(self, get_value=None): result = {} for key, value in iteritems(self): if isinstance(value, BaseCounter): if get_value is not None: value = getattr(value, get_value) result[ke...
[ "Dump counters as a dict" ]
Please provide a description of the function:def value(self, key, value=1): if isinstance(key, six.string_types): key = (key, ) # assert all(isinstance(k, six.string_types) for k in key) assert isinstance(key, tuple), "event key type error" if key not in self.counter...
[ "Set value of a counter by counter key" ]
Please provide a description of the function:def trim(self): for key, value in list(iteritems(self.counters)): if value.empty(): del self.counters[key]
[ "Clear not used counters" ]
Please provide a description of the function:def to_dict(self, get_value=None): self.trim() result = {} for key, value in iteritems(self.counters): if get_value is not None: value = getattr(value, get_value) r = result for _key in key[...
[ "Dump counters as a dict" ]
Please provide a description of the function:def dump(self, filename): try: with open(filename, 'wb') as fp: cPickle.dump(self.counters, fp) except Exception as e: logging.warning("can't dump counter to file %s: %s", filename, e) return False ...
[ "Dump counters to file" ]
Please provide a description of the function:def load(self, filename): try: with open(filename, 'rb') as fp: self.counters = cPickle.load(fp) except: logging.debug("can't load counter from file: %s", filename) return False return True
[ "Load counters to file" ]
Please provide a description of the function:def cli(ctx, **kwargs): if kwargs['add_sys_path']: sys.path.append(os.getcwd()) logging.config.fileConfig(kwargs['logging_config']) # get db from env for db in ('taskdb', 'projectdb', 'resultdb'): if kwargs[db] is not None: ...
[ "\n A powerful spider system in python.\n " ]
Please provide a description of the function:def scheduler(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, inqueue_limit, delete_time, active_tasks, loop_limit, fail_pause_num, scheduler_cls, threads, get_object=False): g = ctx.obj Scheduler = load_cls(None, None, scheduler_cls) kwa...
[ "\n Run Scheduler, only one scheduler is allowed.\n " ]
Please provide a description of the function:def fetcher(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, poolsize, proxy, user_agent, timeout, phantomjs_endpoint, puppeteer_endpoint, splash_endpoint, fetcher_cls, async_mode=True, get_object=False, no_input=False): g = ctx.obj Fetcher = load_...
[ "\n Run Fetcher.\n " ]
Please provide a description of the function:def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False): g = ctx.obj Processor = load_cls(None, None, processor_cls) processor = Processor(projectdb=g.projectdb, inqueue=g.fetcher2process...
[ "\n Run Processor.\n " ]
Please provide a description of the function:def result_worker(ctx, result_cls, get_object=False): g = ctx.obj ResultWorker = load_cls(None, None, result_cls) result_worker = ResultWorker(resultdb=g.resultdb, inqueue=g.processor2result) g.instances.append(result_worker) if g.get('testing_mode...
[ "\n Run result worker.\n " ]
Please provide a description of the function:def webui(ctx, host, port, cdn, scheduler_rpc, fetcher_rpc, max_rate, max_burst, username, password, need_auth, webui_instance, process_time_limit, get_object=False): app = load_cls(None, None, webui_instance) g = ctx.obj app.config['taskdb'] = g....
[ "\n Run WebUI\n " ]
Please provide a description of the function:def phantomjs(ctx, phantomjs_path, port, auto_restart, args): args = args or ctx.default_map and ctx.default_map.get('args', []) import subprocess g = ctx.obj _quit = [] phantomjs_fetcher = os.path.join( os.path.dirname(pyspider.__file__), '...
[ "\n Run phantomjs fetcher if phantomjs is installed.\n " ]
Please provide a description of the function:def puppeteer(ctx, port, auto_restart, args): import subprocess g = ctx.obj _quit = [] puppeteer_fetcher = os.path.join( os.path.dirname(pyspider.__file__), 'fetcher/puppeteer_fetcher.js') cmd = ['node', puppeteer_fetcher, str(port)] tr...
[ "\n Run puppeteer fetcher if puppeteer is installed.\n " ]
Please provide a description of the function:def all(ctx, fetcher_num, processor_num, result_worker_num, run_in): ctx.obj['debug'] = False g = ctx.obj # FIXME: py34 cannot run components with threads if run_in == 'subprocess' and os.name != 'nt': run_in = utils.run_in_subprocess else:...
[ "\n Run all the components in subprocess or thread\n " ]
Please provide a description of the function:def bench(ctx, fetcher_num, processor_num, result_worker_num, run_in, total, show, taskdb_bench, message_queue_bench, all_bench): from pyspider.libs import bench from pyspider.webui import bench_test # flake8: noqa ctx.obj['debug'] = False g ...
[ "\n Run Benchmark test.\n In bench mode, in-memory sqlite database is used instead of on-disk sqlite database.\n " ]
Please provide a description of the function:def one(ctx, interactive, enable_phantomjs, enable_puppeteer, scripts): ctx.obj['debug'] = False g = ctx.obj g['testing_mode'] = True if scripts: from pyspider.database.local.projectdb import ProjectDB g['projectdb'] = ProjectDB(scripts...
[ "\n One mode not only means all-in-one, it runs every thing in one process over\n tornado.ioloop, for debug purpose\n " ]
Please provide a description of the function:def send_message(ctx, scheduler_rpc, project, message): if isinstance(scheduler_rpc, six.string_types): scheduler_rpc = connect_rpc(ctx, None, scheduler_rpc) if scheduler_rpc is None and os.environ.get('SCHEDULER_NAME'): scheduler_rpc = connect_r...
[ "\n Send Message to project from command line\n " ]
Please provide a description of the function:def pprint(object, stream=None, indent=1, width=80, depth=None): printer = PrettyPrinter( stream=stream, indent=indent, width=width, depth=depth) printer.pprint(object)
[ "Pretty-print a Python object to a stream [default is sys.stdout]." ]
Please provide a description of the function:def pformat(object, indent=1, width=80, depth=None): return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
[ "Format a Python object into a pretty-printed representation." ]
Please provide a description of the function:def format(self, object, context, maxlevels, level): return _safe_repr(object, context, maxlevels, level)
[ "Format object for a specific context, returning a string\n and flags indicating whether the representation is 'readable'\n and whether the object represents a recursive construct.\n " ]
Please provide a description of the function:def on_result(self, task, result): '''Called every result''' if not result: return if 'taskid' in task and 'project' in task and 'url' in task: logger.info('result %s:%s %s -> %.30r' % ( task['project'], task['t...
[]
Please provide a description of the function:def run(self): '''Run loop''' logger.info("result_worker starting...") while not self._quit: try: task, result = self.inqueue.get(timeout=1) self.on_result(task, result) except Queue.Empty as e:...
[]
Please provide a description of the function:def on_result(self, task, result): '''Called every result''' if not result: return if 'taskid' in task and 'project' in task and 'url' in task: logger.info('result %s:%s %s -> %.30r' % ( task['project'], task['t...
[]