code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Put a connection back in the pool. Coroutine. ''' assert not self._closed key = connection.key host_pool = self._host_pools[key] _logger.debug('Check in %s', key) yield from host_pool.release(connection) force = self.count() > self._max_cou...
def release(self, connection: Connection)
Put a connection back in the pool. Coroutine.
8.76388
6.744192
1.299471
'''Synchronous version of :meth:`release`.''' _logger.debug('No wait check in.') release_task = asyncio.get_event_loop().create_task( self.release(connection) ) self._release_tasks.add(release_task)
def no_wait_release(self, connection: Connection)
Synchronous version of :meth:`release`.
6.090673
4.766615
1.277777
'''Return a context manager that returns a connection. Usage:: session = yield from connection_pool.session('example.com', 80) with session as connection: connection.write(b'blah') connection.close() Coroutine. ''' connec...
def session(self, host: str, port: int, use_ssl: bool=False)
Return a context manager that returns a connection. Usage:: session = yield from connection_pool.session('example.com', 80) with session as connection: connection.write(b'blah') connection.close() Coroutine.
4.55918
2.313808
1.970423
'''Clean all closed connections. Args: force: Clean connected and idle connections too. Coroutine. ''' assert not self._closed with (yield from self._host_pools_lock): for key, pool in tuple(self._host_pools.items()): yield from ...
def clean(self, force: bool=False)
Clean all closed connections. Args: force: Clean connected and idle connections too. Coroutine.
4.953238
3.025405
1.637214
'''Close all the connections and clean up. This instance will not be usable after calling this method. ''' for key, pool in tuple(self._host_pools.items()): pool.close() del self._host_pools[key] del self._host_pool_waiters[key] self._closed...
def close(self)
Close all the connections and clean up. This instance will not be usable after calling this method.
5.03229
3.527801
1.426467
'''Return number of connections.''' counter = 0 for pool in self._host_pools.values(): counter += pool.count() return counter
def count(self) -> int
Return number of connections.
8.123512
6.67083
1.217766
'''Set the preferred address.''' if addr_1 > addr_2: addr_1, addr_2 = addr_2, addr_1 self._cache[(addr_1, addr_2)] = preferred_addr
def set_preferred(self, preferred_addr, addr_1, addr_2)
Set the preferred address.
3.114436
3.579438
0.870091
'''Return the preferred address.''' if addr_1 > addr_2: addr_1, addr_2 = addr_2, addr_1 return self._cache.get((addr_1, addr_2))
def get_preferred(self, addr_1, addr_2)
Return the preferred address.
3.076846
3.065624
1.003661
'''Connect using happy eyeballs.''' self._primary_connection = self._connection_factory(primary_address) self._secondary_connection = self._connection_factory(secondary_address) @asyncio.coroutine def connect_primary(): yield from self._primary_connection.connect() ...
def _connect_dual_stack(self, primary_address, secondary_address)
Connect using happy eyeballs.
3.182369
2.958933
1.075513
'''Get preferred host from DNS results.''' host_1 = result.first_ipv4.ip_address if result.first_ipv4 else None host_2 = result.first_ipv6.ip_address if result.first_ipv6 else None if not host_2: return host_1, None elif not host_1: return host_2, None ...
def _get_preferred_host(self, result: ResolveResult) -> Tuple[str, str]
Get preferred host from DNS results.
2.990054
2.791624
1.071081
'''Check if any journal files exist and raise an error.''' files = list(glob.glob(self._prefix_filename + '*-wpullinc')) if files: raise OSError('WARC file {} is incomplete.'.format(files[0]))
def _check_journals_and_maybe_raise(self)
Check if any journal files exist and raise an error.
17.441744
12.01732
1.451384
'''Create and set as current WARC file.''' if self._params.max_size and not meta and self._params.appending: while True: self._warc_filename = self._generate_warc_filename() if os.path.exists(self._warc_filename): _logger.debug('Skip {0}',...
def _start_new_warc_file(self, meta=False)
Create and set as current WARC file.
3.598566
3.390756
1.061287
'''Return a suitable WARC filename.''' if self._params.max_size is None: sequence_name = '' elif meta: sequence_name = '-meta' else: sequence_name = '-{0:05d}'.format(self._sequence_num) if self._params.compress: extension = 'warc....
def _generate_warc_filename(self, meta=False)
Return a suitable WARC filename.
3.346865
3.181932
1.051834
'''Create and set current CDX file.''' self._cdx_filename = '{0}.cdx'.format(self._prefix_filename) if not self._params.appending: wpull.util.truncate_file(self._cdx_filename) self._write_cdx_header() elif not os.path.exists(self._cdx_filename): self....
def _start_new_cdx_file(self)
Create and set current CDX file.
4.5255
4.138933
1.093398
'''Add the metadata to the Warcinfo record.''' self._warcinfo_record.set_common_fields( WARCRecord.WARCINFO, WARCRecord.WARC_FIELDS) info_fields = NameValueRecord(wrap_width=1024) info_fields['Software'] = self._params.software_string \ or self.DEFAULT_SOFTWARE_S...
def _populate_warcinfo(self, extra_fields=None)
Add the metadata to the Warcinfo record.
3.734099
3.510607
1.063662
'''Set up the logging file.''' logger = logging.getLogger() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') self._log_temp_file = NamedTemporaryFile( prefix='tmp-wpull-warc-', dir=self._params.temp_dir, ...
def _setup_log(self)
Set up the logging file.
3.306236
3.207464
1.030794
'''Move the file to the ``move_to`` directory.''' assert self._params.move_to if os.path.isdir(self._params.move_to): _logger.debug('Moved {} to {}.', self._warc_filename, self._params.move_to) shutil.move(filename, self._params.move_to) ...
def _move_file_to_dest_dir(self, filename)
Move the file to the ``move_to`` directory.
3.678003
3.343346
1.100096
'''Set the content length and possibly the checksums.''' if self._params.digests: record.compute_checksum(payload_offset) else: record.set_content_length()
def set_length_and_maybe_checksums(self, record, payload_offset=None)
Set the content length and possibly the checksums.
7.588214
6.412765
1.183298
'''Append the record to the WARC file.''' # FIXME: probably not a good idea to modifiy arguments passed to us # TODO: add extra gzip headers that wget uses record.fields['WARC-Warcinfo-ID'] = self._warcinfo_record.fields[ WARCRecord.WARC_RECORD_ID] _logger.debug('Wri...
def write_record(self, record)
Append the record to the WARC file.
4.058313
3.965797
1.023329
'''Close the WARC file and clean up any logging handlers.''' if self._log_temp_file: self._log_handler.flush() logger = logging.getLogger() logger.removeHandler(self._log_handler) self._log_handler.stream.close() log_record = WARCRecord() ...
def close(self)
Close the WARC file and clean up any logging handlers.
3.639748
3.327615
1.093801
'''Write the CDX header. It writes the fields: 1. a: original URL 2. b: UNIX timestamp 3. m: MIME Type from the HTTP Content-type 4. s: response code 5. k: new style checksum 6. S: raw file record size 7. V: offset in raw file 8. g: filen...
def _write_cdx_header(self)
Write the CDX header. It writes the fields: 1. a: original URL 2. b: UNIX timestamp 3. m: MIME Type from the HTTP Content-type 4. s: response code 5. k: new style checksum 6. S: raw file record size 7. V: offset in raw file 8. g: filename of raw ...
5.037392
1.856202
2.713816
'''Write the CDX field if needed.''' if record.fields[WARCRecord.WARC_TYPE] != WARCRecord.RESPONSE \ or not re.match(r'application/http; *msgtype *= *response', record.fields[WARCRecord.CONTENT_TYPE]): return url = record.fields['WARC-Target-URI...
def _write_cdx_field(self, record, raw_file_record_size, raw_file_offset)
Write the CDX field if needed.
2.730956
2.697295
1.01248
'''Return the MIME type from a Content-Type string. Returns: str, None: A string in the form ``type/subtype`` or None. ''' match = re.match(r'([a-zA-Z0-9-]+/[a-zA-Z0-9-]+)', value) if match: return match.group(1)
def parse_mimetype(cls, value)
Return the MIME type from a Content-Type string. Returns: str, None: A string in the form ``type/subtype`` or None.
3.442158
1.954694
1.76097
'''Return new temp file.''' return wpull.body.new_temp_file( directory=self._temp_dir, hint=hint )
def _new_temp_file(self, hint='warcrecsess')
Return new temp file.
14.798188
11.782578
1.255938
'''Record the revisit if possible.''' fields = self._response_record.fields ref_record_id = self._url_table.get_revisit_id( fields['WARC-Target-URI'], fields.get('WARC-Payload-Digest', '').upper().replace('SHA1:', '') ) if ref_record_id: try:...
def _record_revisit(self, payload_offset: int)
Record the revisit if possible.
3.78829
3.676503
1.030406
'''Increment the number of files downloaded. Args: size: The size of the file ''' assert size >= 0, size self.files += 1 self.size += size self.bandwidth_meter.feed(size)
def increment(self, size: int)
Increment the number of files downloaded. Args: size: The size of the file
7.328775
5.72035
1.281176
'''Return whether the quota is exceeded.''' if self.quota and self._url_table is not None: return self.size >= self.quota and \ self._url_table.get_root_url_todo_count() == 0
def is_quota_exceeded(self) -> bool
Return whether the quota is exceeded.
9.929627
8.654328
1.14736
'''Increment the error counter preferring base exceptions.''' _logger.debug('Increment error %s', error) for error_class in ERROR_PRIORITIES: if isinstance(error, error_class): self.errors[error_class] += 1 return self.errors[type(error)] += ...
def increment_error(self, error: Exception)
Increment the error counter preferring base exceptions.
5.17376
3.588367
1.441815
'''Add a node to the head. ''' assert not node.tail old_head = self.head if old_head: assert old_head.tail == self old_head.tail = node node.head = old_head node.tail = self self.head = node
def link_head(self, node)
Add a node to the head.
3.669375
3.463351
1.059487
'''Add a node to the tail.''' assert not node.head old_tail = self.tail if old_tail: assert old_tail.head == self old_tail.head = node node.tail = old_tail node.head = self self.tail = node
def link_tail(self, node)
Add a node to the tail.
3.280923
3.233406
1.014696
'''Remove this node and link any head or tail.''' old_head = self.head old_tail = self.tail self.head = None self.tail = None if old_head: old_head.tail = old_tail if old_tail: old_tail.head = old_head
def unlink(self)
Remove this node and link any head or tail.
3.205808
2.126987
1.507206
'''Parse the status line bytes. Returns: tuple: An tuple representing the method, URI, and version. ''' match = re.match( br'([a-zA-Z]+)[ \t]+([^ \t]+)[ \t]+(HTTP/\d+\.\d+)', data ) if match: groups = match.grou...
def parse_status_line(self, data)
Parse the status line bytes. Returns: tuple: An tuple representing the method, URI, and version.
5.237605
3.571794
1.466379
'''Modify the request to be suitable for HTTP server. Args: full_url (bool): Use full URL as the URI. By default, only the path of the URL is given to the server. ''' assert self.url assert self.method assert self.version url_info = s...
def prepare_for_send(self, full_url=False)
Modify the request to be suitable for HTTP server. Args: full_url (bool): Use full URL as the URI. By default, only the path of the URL is given to the server.
3.586316
2.333339
1.536989
'''Parse the status line bytes. Returns: tuple: An tuple representing the version, code, and reason. ''' match = re.match( br'(HTTP/\d+\.\d+)[ \t]+([0-9]{1,3})[ \t]*([^\r\n]*)', data ) if match: groups = match.groups() ...
def parse_status_line(cls, data)
Parse the status line bytes. Returns: tuple: An tuple representing the version, code, and reason.
5.05749
3.830996
1.32015
'''Return whether the document is likely to be CSS.''' if 'css' in response.fields.get('content-type', '').lower(): return True if response.body: # Stylesheet mistakenly served as HTML if 'html' in response.fields.get('content-type', '').lower(): ...
def is_response(cls, response)
Return whether the document is likely to be CSS.
6.765862
4.759166
1.421649
'''Return whether the file is likely CSS.''' peeked_data = wpull.string.printable_bytes( wpull.util.peek_file(file)).lower() if b'<html' in peeked_data: return VeryFalse if re.search(br'@import |color:|background[a-z-]*:|font[a-z-]*:', peeke...
def is_file(cls, file)
Return whether the file is likely CSS.
13.69078
10.549122
1.297812
'''Begin fetching the next request.''' self._current_session = session = self._http_client.session() request = self.next_request() assert request if request.url_info.password or \ request.url_info.hostname_with_port in self._hostnames_with_auth: self...
def start(self)
Begin fetching the next request.
6.631562
5.736483
1.156033
'''Download content. Args: file: An optional file object for the document contents. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: Response: An instance of :class:`.http.request.Response`. S...
def download(self, file: Optional[IO[bytes]]=None, duration_timeout: Optional[float]=None)
Download content. Args: file: An optional file object for the document contents. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: Response: An instance of :class:`.http.request.Response`. See :meth:`W...
9.542941
2.108135
4.526722
'''Handle the response and update the internal state.''' _logger.debug('Handling response') self._redirect_tracker.load(response) if self._redirect_tracker.is_redirect(): self._process_redirect() self._loop_type = LoopType.redirect elif response.status_c...
def _process_response(self, response: Response)
Handle the response and update the internal state.
4.585319
4.024821
1.13926
'''Update the Redirect Tracker.''' _logger.debug('Handling redirect.') if self._redirect_tracker.exceeded(): raise ProtocolError('Too many redirects.') try: url = self._redirect_tracker.next_location() if not url: raise ProtocolError...
def _process_redirect(self)
Update the Redirect Tracker.
4.59589
4.21595
1.09012
'''Return the referrer hostname.''' referer = self._original_request.fields.get('Referer') if referer: return URLInfo.parse(referer).hostname else: return None
def _get_cookie_referrer_host(self)
Return the referrer hostname.
6.833744
5.929336
1.152531
'''Add the cookie headers to the Request.''' self._cookie_jar.add_cookie_header( request, self._get_cookie_referrer_host() )
def _add_cookies(self, request: Request)
Add the cookie headers to the Request.
11.400079
7.026497
1.622441
'''Load the cookie headers from the Response.''' self._cookie_jar.extract_cookies( response, response.request, self._get_cookie_referrer_host() )
def _extract_cookies(self, response: Response)
Load the cookie headers from the Response.
12.719192
7.113799
1.78796
'''Return a fetch session. Args: request: The request to be fetched. Example usage:: client = WebClient() session = client.session(Request('http://www.example.com')) with session: while not session.done(): re...
def session(self, request: Request) -> WebSession
Return a fetch session. Args: request: The request to be fetched. Example usage:: client = WebClient() session = client.session(Request('http://www.example.com')) with session: while not session.done(): request = ses...
3.944551
1.77149
2.226686
'''Return URL string with the path replaced with directory only.''' dir_name = posixpath.dirname(url_info.path) if not dir_name.endswith('/'): url_template = 'ftp://{}{}/' else: url_template = 'ftp://{}{}' return url_template.format(url_info.hostname_with_port, dir_name)
def to_dir_path_url(url_info: URLInfo) -> str
Return URL string with the path replaced with directory only.
4.757778
3.319978
1.433075
'''Process. Coroutine. ''' self._item_session.request = request = Request(self._item_session.url_record.url) verdict = self._fetch_rule.check_ftp_request(self._item_session)[0] if not verdict: self._item_session.skip() return self._add_r...
def process(self)
Process. Coroutine.
6.781769
6.47108
1.048012
'''Check if file, modify request, and return whether is a file. Coroutine. ''' if self._item_session.url_record.link_type: is_file = self._item_session.url_record.link_type == LinkType.file elif request.url_info.path.endswith('/'): is_file = False ...
def _prepare_request_file_vs_dir(self, request: Request) -> bool
Check if file, modify request, and return whether is a file. Coroutine.
4.852974
3.977931
1.219975
'''Fetch parent directory and return list FileEntry. Coroutine. ''' directory_url = to_dir_path_url(request.url_info) if use_cache: if directory_url in self._processor.listing_cache: return self._processor.listing_cache[directory_url] direct...
def _fetch_parent_path(self, request: Request, use_cache: bool=True)
Fetch parent directory and return list FileEntry. Coroutine.
5.248778
4.527809
1.159231
'''Fetch the request Coroutine. ''' _logger.info(_('Fetching ‘{url}’.'), url=request.url) self._item_session.request = request response = None try: with self._processor.ftp_client.session() as session: if is_file: ...
def _fetch(self, request: Request, is_file: bool)
Fetch the request Coroutine.
4.272513
4.059051
1.052589
'''Add links from file listing response.''' base_url = response.request.url_info.url if self._glob_pattern: level = self._item_session.url_record.level else: level = None for file_entry in response.files: if self._glob_pattern and \ ...
def _add_listing_links(self, response: ListingResponse)
Add links from file listing response.
3.572457
3.355216
1.064747
'''Log response.''' _logger.info( _('Fetched ‘{url}’: {reply_code} {reply_text}. ' 'Length: {content_length}.'), url=request.url, reply_code=response.reply.code, reply_text=response.reply.text, content_length=response.body.size(...
def _log_response(self, request: Request, response: Response)
Log response.
5.129367
4.603688
1.114187
'''Process a response.''' self._item_session.update_record_value(status_code=response.reply.code) is_listing = isinstance(response, ListingResponse) if is_listing and not self._processor.fetch_params.remove_listing or \ not is_listing: filename = self._file_w...
def _handle_response(self, request: Request, response: Response)
Process a response.
6.506195
6.201765
1.049088
'''Make a symlink on the system.''' path = self._file_writer_session.extra_resource_path('dummy') if path: dir_path = os.path.dirname(path) symlink_path = os.path.join(dir_path, link_name) _logger.debug('symlink {} -> {}', symlink_path, link_target) ...
def _make_symlink(self, link_name: str, link_target: str)
Make a symlink on the system.
4.072078
3.754415
1.084611
'''Fetch and apply Unix permissions. Coroutine. ''' files = yield from self._fetch_parent_path(request) if not files: return filename = posixpath.basename(request.file_path) for file_entry in files: if file_entry.name == filename and fi...
def _apply_unix_permissions(self, request: Request, response: Response)
Fetch and apply Unix permissions. Coroutine.
5.992356
4.742076
1.263657
'''Build URL rewriter if needed.''' if session.args.escaped_fragment or session.args.strip_session_id: return session.factory.new( 'URLRewriter', hash_fragment=session.args.escaped_fragment, session_id=session.args.strip_session_id ...
def _build_url_rewriter(cls, session: AppSession)
Build URL rewriter if needed.
8.339835
6.602797
1.263076
'''Create the URL filter instances. Returns: A list of URL filter instances ''' args = session.args filters = [ HTTPSOnlyFilter() if args.https_only else SchemeFilter(), RecursiveFilter( enabled=args.recursive, page_requisites...
def _build_url_filters(cls, session: AppSession)
Create the URL filter instances. Returns: A list of URL filter instances
3.10613
2.88805
1.075511
'''Build the Document Converter.''' if not session.args.convert_links: return converter = session.factory.new( 'BatchDocumentConverter', session.factory['HTMLParser'], session.factory['ElementWalker'], session.factory['URLTable'], ...
def _build_document_converter(cls, session: AppSession)
Build the Document Converter.
14.508173
12.952223
1.12013
'''Set up the root logger if needed. The root logger is set the appropriate level so the file and WARC logs work correctly. ''' assert ( logging.CRITICAL > logging.ERROR > logging.WARNING > logging.INFO > logging.DEBUG ...
def _setup_logging(cls, args)
Set up the root logger if needed. The root logger is set the appropriate level so the file and WARC logs work correctly.
3.768914
2.865078
1.315466
'''Set up the console logger. A handler and with a formatter is added to the root logger. ''' stream = new_encoded_stream(args, stderr) logger = logging.getLogger() session.console_log_handler = handler = logging.StreamHandler(stream) formatter = logging.Format...
def _setup_console_logger(cls, session: AppSession, args, stderr)
Set up the console logger. A handler and with a formatter is added to the root logger.
4.468826
3.326422
1.343433
'''Set up the file message logger. A file log handler and with a formatter is added to the root logger. ''' if not (args.output_file or args.append_output): return logger = logging.getLogger() formatter = logging.Formatter( '%(asctime)s - %(name...
def _setup_file_logger(cls, session: AppSession, args)
Set up the file message logger. A file log handler and with a formatter is added to the root logger.
2.614063
1.982304
1.318699
'''Process PhantomJS. Coroutine. ''' if response.status_code != 200: return if not HTMLReader.is_supported(request=request, response=response): return _logger.debug('Starting PhantomJS processing.') self._file_writer_session = file_writ...
def process(self, item_session: ItemSession, request, response, file_writer_session)
Process PhantomJS. Coroutine.
5.718666
5.065488
1.128947
'''Start PhantomJS processing.''' _logger.debug('Started PhantomJS processing.') session = PhantomJSCoprocessorSession( self._phantomjs_driver_factory, self._root_path, self._processing_rule, self._file_writer_session, request, response, item_sess...
def _run_driver(self, item_session: ItemSession, request, response)
Start PhantomJS processing.
7.709269
6.487476
1.188331
'''Add the action log to the WARC file.''' _logger.debug('Adding action log record.') actions = [] with open(path, 'r', encoding='utf-8', errors='replace') as file: for line in file: actions.append(json.loads(line)) log_data = json.dumps( ...
def _add_warc_action_log(self, path, url)
Add the action log to the WARC file.
4.890107
4.809161
1.016832
'''Add the snaphot to the WARC file.''' _logger.debug('Adding snapshot record.') extension = os.path.splitext(filename)[1] content_type = { '.pdf': 'application/pdf', '.html': 'text/html', '.png': 'image/png', '.gif': 'image/gif' ...
def _add_warc_snapshot(self, filename, url)
Add the snaphot to the WARC file.
4.324939
4.128391
1.047609
'''Extract links from the DOM.''' mock_response = self._new_mock_response( self._response, self._get_temp_path('phantom', '.html') ) self._item_session.request = self._request self._item_session.response = mock_response self._processing_rule.scrape_document(...
def _scrape_document(self)
Extract links from the DOM.
9.5626
8.380347
1.141074
'''Return a new mock Response with the content.''' mock_response = copy.copy(response) mock_response.body = Body(open(file_path, 'rb')) mock_response.fields = NameValueRecord() for name, value in response.fields.get_all(): mock_response.fields.add(name, value) ...
def _new_mock_response(self, response, file_path)
Return a new mock Response with the content.
4.392982
3.768934
1.165577
'''Clean up.''' for path in self._temp_filenames: if os.path.exists(path): os.remove(path)
def close(self)
Clean up.
5.875703
5.152932
1.140264
'''Create the SSL options. The options must be accepted by the `ssl` module. ''' args = session.args # Logic is based on tornado.netutil.ssl_options_to_context ssl_context = ssl.SSLContext(args.secure_protocol) if args.check_certificate: ssl_context...
def _build_ssl_context(cls, session: AppSession) -> ssl.SSLContext
Create the SSL options. The options must be accepted by the `ssl` module.
3.560763
3.206261
1.110566
'''Load the Certificate Authority certificates. ''' args = session.args if session.ca_certs_filename: return session.ca_certs_filename certs = set() if args.use_internal_ca_certs: pem_filename = os.path.join( os.path.dirname(__fi...
def _load_ca_certs(cls, session: AppSession, clean: bool=True)
Load the Certificate Authority certificates.
2.480714
2.412163
1.028419
'''Read the PEM file. Returns: iterable: An iterable of certificates. The certificate data is :class:`byte`. ''' _logger.debug('Reading PEM {0}.'.format(filename)) if from_package: return wpull.util.filter_pem(wpull.util.get_package_data(file...
def _read_pem_file(cls, filename, from_package=False)
Read the PEM file. Returns: iterable: An iterable of certificates. The certificate data is :class:`byte`.
4.804315
3.033884
1.583553
'''Begin a HTTP request Args: request: Request information. Returns: A response populated with the HTTP headers. Once the headers are received, call :meth:`download`. Coroutine. ''' if self._session_state != SessionState.ready: ...
def start(self, request: Request) -> Response
Begin a HTTP request Args: request: Request information. Returns: A response populated with the HTTP headers. Once the headers are received, call :meth:`download`. Coroutine.
3.746407
3.020566
1.2403
'''Read the response content into file. Args: file: A file object or asyncio stream. raw: Whether chunked transfer encoding should be included. rewind: Seek the given file back to its original offset after reading is finished. duration_tim...
def download( self, file: Union[IO[bytes], asyncio.StreamWriter, None]=None, raw: bool=False, rewind: bool=True, duration_timeout: Optional[float]=None)
Read the response content into file. Args: file: A file object or asyncio stream. raw: Whether chunked transfer encoding should be included. rewind: Seek the given file back to its original offset after reading is finished. duration_timeout: Maxim...
4.407763
2.644009
1.667076
'''Convert an instance recursively to bytes.''' if isinstance(instance, bytes): return instance elif hasattr(instance, 'encode'): return instance.encode(encoding, error) elif isinstance(instance, list): return list([to_bytes(item, encoding, error) for item in instance]) elif ...
def to_bytes(instance, encoding='utf-8', error='strict')
Convert an instance recursively to bytes.
1.715087
1.677815
1.022214
'''Convert an instance recursively to string.''' if isinstance(instance, str): return instance elif hasattr(instance, 'decode'): return instance.decode(encoding) elif isinstance(instance, list): return list([to_str(item, encoding) for item in instance]) elif isinstance(instan...
def to_str(instance, encoding='utf-8')
Convert an instance recursively to string.
1.846904
1.792077
1.030594
'''Return the Python name of the encoder/decoder Returns: str, None ''' name = UnicodeDammit.CHARSET_ALIASES.get(name.lower(), name) try: return codecs.lookup(name).name except (LookupError, TypeError, ValueError): # TypeError occurs when name contains \x00 (ValueError ...
def normalize_codec_name(name)
Return the Python name of the encoder/decoder Returns: str, None
7.784446
5.23848
1.486012
'''Detect the character encoding of the data. Returns: str: The name of the codec Raises: ValueError: The codec could not be detected. This error can only occur if fallback is not a "lossless" codec. ''' if encoding: encoding = normalize_codec_name(encoding) bs...
def detect_encoding(data, encoding=None, fallback='latin1', is_html=False)
Detect the character encoding of the data. Returns: str: The name of the codec Raises: ValueError: The codec could not be detected. This error can only occur if fallback is not a "lossless" codec.
5.268528
3.848488
1.368986
'''Return whether the Python codec could decode the data.''' try: data.decode(encoding, 'strict') except UnicodeError: # Data under 16 bytes is very unlikely to be truncated if len(data) > 16: for trim in (1, 2, 3): trimmed_data = data[:-trim] ...
def try_decoding(data, encoding)
Return whether the Python codec could decode the data.
3.896964
3.215368
1.211981
'''Format the file size into a human readable text. http://stackoverflow.com/a/1094933/1524507 ''' for unit in ('B', 'KiB', 'MiB', 'GiB'): if -1024 < num < 1024: return format_str.format(num=num, unit=unit) num /= 1024.0 return format_str.format(num=num, unit='TiB')
def format_size(num, format_str='{num:.1f} {unit}')
Format the file size into a human readable text. http://stackoverflow.com/a/1094933/1524507
2.284372
1.664645
1.372287
'''Escape any control or non-ASCII characters from string. This function is intended for use with strings from an untrusted source such as writing to a console or writing to logs. It is designed to prevent things like ANSI escape sequences from showing. Use :func:`repr` or :func:`ascii` instea...
def printable_str(text, keep_newlines=False)
Escape any control or non-ASCII characters from string. This function is intended for use with strings from an untrusted source such as writing to a console or writing to logs. It is designed to prevent things like ANSI escape sequences from showing. Use :func:`repr` or :func:`ascii` instead for t...
5.763983
1.748889
3.295796
'''Convenience function for the print function. This function prints no newline. ''' string = ' '.join([str(arg) for arg in args]) print(string, end='', file=self._stream)
def _print(self, *args)
Convenience function for the print function. This function prints no newline.
5.995656
3.180701
1.885011
'''Convenience function for the print function.''' string = ' '.join([str(arg) for arg in args]) print(string, file=self._stream)
def _println(self, *args)
Convenience function for the print function.
5.02705
3.85938
1.302554
'''Print an entire status line including bar and stats.''' self._clear_line() self._print(' ') if self.max_value: self._print_percent() self._print(' ') self._print_bar() else: self._print_throbber() self._print(' ') ...
def _print_status(self)
Print an entire status line including bar and stats.
4.325681
3.549298
1.218743
'''Print an indefinite progress bar.''' self._print('[') for position in range(self._bar_width): self._print('O' if position == self._throbber_index else ' ') self._print(']') self._throbber_index = next(self._throbber_iter)
def _print_throbber(self)
Print an indefinite progress bar.
4.977401
4.73222
1.051811
'''Print a progress bar.''' self._print('[') for position in range(self._bar_width): position_fraction = position / (self._bar_width - 1) position_bytes = position_fraction * self.max_value if position_bytes < (self.continue_value or 0): self...
def _print_bar(self)
Print a progress bar.
3.501693
3.624364
0.966154
'''Print the elapsed download time.''' duration = int(time.time() - self._start_time) self._print(datetime.timedelta(seconds=duration))
def _print_duration(self)
Print the elapsed download time.
6.63668
4.474001
1.483388
'''Print the current speed.''' if self._bandwidth_meter.num_samples: speed = self._bandwidth_meter.speed() if self._human_format: file_size_str = wpull.string.format_size(speed) else: file_size_str = '{:.1f} b'.format(speed * 8) ...
def _print_speed(self)
Print the current speed.
5.260028
5.310452
0.990505
'''Print how much is done in percentage.''' fraction_done = ((self.continue_value or 0 + self.current_value) / self.max_value) self._print('{fraction_done:.1%}'.format(fraction_done=fraction_done))
def _print_percent(self)
Print how much is done in percentage.
8.174711
6.509369
1.255838
'''Register hooks that can be connected.''' if name in self._callbacks: raise ValueError('Hook already registered') self._callbacks[name] = None if self._event_dispatcher is not None: self._event_dispatcher.register(name)
def register(self, name: str)
Register hooks that can be connected.
5.950173
3.973991
1.497279
'''Unregister hook.''' del self._callbacks[name] if self._event_dispatcher is not None: self._event_dispatcher.unregister(name)
def unregister(self, name: str)
Unregister hook.
7.525638
6.238605
1.206301
'''Add callback to hook.''' if not self._callbacks[name]: self._callbacks[name] = callback else: raise HookAlreadyConnectedError('Callback hook already connected.')
def connect(self, name, callback)
Add callback to hook.
7.454328
5.7646
1.293122
'''Invoke the callback.''' if self._event_dispatcher is not None: self._event_dispatcher.notify(name, *args, **kwargs) if self._callbacks[name]: return self._callbacks[name](*args, **kwargs) else: raise HookDisconnected('No callback is connected.')
def call(self, name: str, *args, **kwargs)
Invoke the callback.
5.632816
5.190449
1.085227
if PY_MAJOR_VERSION < 3: # The robot rules are stored internally as Unicode. The two lines # below ensure that the parameters passed to this function are # also Unicode. If those lines were not present and the caller # passed a non-Unicode user...
def is_allowed(self, user_agent, url, syntax=GYM2008)
True if the user agent is permitted to visit the URL. The syntax parameter can be GYM2008 (the default) or MK1996 for strict adherence to the traditional standard.
5.651988
5.321328
1.062139
# See is_allowed() comment about the explicit unicode conversion. if (PY_MAJOR_VERSION < 3) and (not isinstance(user_agent, unicode)): user_agent = user_agent.decode() for ruleset in self.__rulesets: if ruleset.does_user_agent_match(user_agent): ...
def get_crawl_delay(self, user_agent)
Returns a float representing the crawl delay specified for this user agent, or None if the crawl delay was unspecified or not a float.
5.615258
5.014761
1.119746
'''Decorator to close stream on error.''' @asyncio.coroutine @functools.wraps(func) def wrapper(self, *args, **kwargs): with wpull.util.close_on_error(self.close): return (yield from func(self, *args, **kwargs)) return wrapper
def close_stream_on_error(func)
Decorator to close stream on error.
3.930496
3.8134
1.030706
'''Return a filename from a URL. Args: url (str): The URL. index (str): If a filename could not be derived from the URL path, use index instead. For example, ``/images/`` will return ``index.html``. alt_char (bool): If True, the character for the query deliminato...
def url_to_filename(url, index='index.html', alt_char=False)
Return a filename from a URL. Args: url (str): The URL. index (str): If a filename could not be derived from the URL path, use index instead. For example, ``/images/`` will return ``index.html``. alt_char (bool): If True, the character for the query deliminator ...
3.594404
1.714337
2.096673
'''Return a list of directory parts from a URL. Args: url (str): The URL. include_protocol (bool): If True, the scheme from the URL will be included. include_hostname (bool): If True, the hostname from the URL will be included. alt_char (bool): If True, t...
def url_to_dir_parts(url, include_protocol=False, include_hostname=False, alt_char=False)
Return a list of directory parts from a URL. Args: url (str): The URL. include_protocol (bool): If True, the scheme from the URL will be included. include_hostname (bool): If True, the hostname from the URL will be included. alt_char (bool): If True, the char...
2.563679
1.655615
1.548475
'''Return a safe filename or path part. Args: filename (str): The filename or path component. os_type (str): If ``unix``, escape the slash. If ``windows``, escape extra Windows characters. no_control (bool): If True, escape control characters. ascii_only (bool): If T...
def safe_filename(filename, os_type='unix', no_control=True, ascii_only=True, case=None, encoding='utf8', max_length=None)
Return a safe filename or path part. Args: filename (str): The filename or path component. os_type (str): If ``unix``, escape the slash. If ``windows``, escape extra Windows characters. no_control (bool): If True, escape control characters. ascii_only (bool): If True, es...
2.550309
1.949946
1.307887
'''Return a directory path free of filenames. Args: dir_path (str): A directory path. suffix (str): The suffix to append to the part of the path that is a file. Returns: str ''' dir_path = os.path.normpath(dir_path) parts = dir_path.split(os.sep) for i...
def anti_clobber_dir_path(dir_path, suffix='.d')
Return a directory path free of filenames. Args: dir_path (str): A directory path. suffix (str): The suffix to append to the part of the path that is a file. Returns: str
2.818325
1.811555
1.555749
'''Parse a Content-Disposition header value.''' match = re.search(r'filename\s*=\s*(.+)', text, re.IGNORECASE) if not match: return filename = match.group(1) if filename[0] in '"\'': match = re.match(r'(.)(.+)(?!\\)\1', filename) if match: filename = match.gro...
def parse_content_disposition(text)
Parse a Content-Disposition header value.
3.469827
3.520371
0.985642
'''Return a safe filename or file part.''' return safe_filename( part, os_type=self._os_type, no_control=self._no_control, ascii_only=self._ascii_only, case=self._case, max_length=self._max_filename_length, )
def safe_filename(self, part)
Return a safe filename or file part.
5.432997
4.530481
1.19921