code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
headers = response.getheaders() if response.version == 11: return not has_header_value(headers, 'Connection', 'Close') return has_header_value(headers, "Connection", "Keep-Alive")
def http_persistent (response)
See if the HTTP connection can be kept open according the the header values found in the response object. @param response: response instance @type response: httplib.HTTPResponse @return: True if connection is persistent @rtype: bool
4.384795
3.915157
1.119954
keepalive = headers.get("Keep-Alive") if keepalive is not None: try: keepalive = int(keepalive[8:].strip()) except (ValueError, OverflowError): keepalive = DEFAULT_KEEPALIVE else: keepalive = DEFAULT_KEEPALIVE return keepalive
def http_keepalive (headers)
Get HTTP keepalive value, either from the Keep-Alive header or a default value. @param headers: HTTP headers @type headers: dict @return: keepalive in seconds @rtype: int
2.506279
2.782407
0.900759
ptype = headers.get('Content-Type', 'application/octet-stream') if ";" in ptype: # split off not needed extension info ptype = ptype.split(';')[0] return ptype.strip().lower()
def get_content_type (headers)
Get the MIME type from the Content-Type header value, or 'application/octet-stream' if not found. @return: MIME type @rtype: string
5.084985
5.156287
0.986172
modules = plugins.get_plugin_modules(folders) pluginclasses = sorted(plugins.get_plugin_classes(modules), key=lambda x: x.__name__) for pluginclass in pluginclasses: print(pluginclass.__name__) doc = strformat.wrap(pluginclass.__doc__, 80) print(strformat.indent(doc)) p...
def print_plugins(folders, exit_code=0)
Print available plugins and exit.
3.446971
3.349348
1.029147
program = sys.argv[0] print(_("Error: %(msg)s") % {"msg": msg}, file=console.stderr) print(_("Execute '%(program)s -h' for help") % {"program": program}, file=console.stderr) sys.exit(exit_code)
def print_usage (msg, exit_code=2)
Print a program msg text to stderr and exit.
3.357999
3.173305
1.058202
get_url_from = checker.get_url_from url = checker.guess_url(url) url_data = get_url_from(url, 0, aggregate, extern=(0, 0)) aggregate.urlqueue.put(url_data)
def aggregate_url (aggregate, url, err_exit_code=2)
Append given commandline URL to input queue.
9.548537
8.040841
1.187505
msg = console.encode(self.format_help()) if fileutil.is_tty(file): strformat.paginate(msg) else: print(msg, file=file)
def print_help(self, file=sys.stdout)
Print a help message to stdout.
12.397985
12.12534
1.022486
m = Message(id=0) m.keyring = keyring m.request_mac = request_mac m.xfr = xfr m.origin = origin m.tsig_ctx = tsig_ctx m.multi = multi m.first = first reader = _WireReader(wire, m, question_only, one_rr_per_rrset) reader.read() return m
def from_wire(wire, keyring=None, request_mac='', xfr=False, origin=None, tsig_ctx = None, multi = False, first = True, question_only = False, one_rr_per_rrset = False)
Convert a DNS wire format message into a message object. @param keyring: The keyring to use if the message is signed. @type keyring: dict @param request_mac: If the message is a response to a TSIG-signed request, I{request_mac} should be set to the MAC of that request. @type request_mac: string...
2.159894
2.949133
0.732383
# 'text' can also be a file, but we don't publish that fact # since it's an implementation detail. The official file # interface is from_file(). m = Message() reader = _TextReader(text, m) reader.read() return m
def from_text(text)
Convert the text format message into a message object. @param text: The text format message. @type text: string @raises UnknownHeaderField: @raises dns.exception.SyntaxError: @rtype: dns.message.Message object
11.586649
10.26239
1.12904
if sys.hexversion >= 0x02030000: # allow Unicode filenames; turn on universal newline support str_type = basestring opts = 'rU' else: str_type = str opts = 'r' if isinstance(f, str_type): f = file(f, opts) want_close = True else: want...
def from_file(f)
Read the next text format message from the specified file. @param f: file or string. If I{f} is a string, it is treated as the name of a file to open. @raises UnknownHeaderField: @raises dns.exception.SyntaxError: @rtype: dns.message.Message object
3.570245
3.564301
1.001668
if isinstance(qname, (str, unicode)): qname = dns.name.from_text(qname) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) if isinstance(rdclass, (str, unicode)): rdclass = dns.rdataclass.from_text(rdclass) m = Message() m.flags |= dns.flags...
def make_query(qname, rdtype, rdclass = dns.rdataclass.IN, use_edns=None, want_dnssec=False)
Make a query message. The query name, type, and class may all be specified either as objects of the appropriate type, or as strings. The query will have a randomly choosen query id, and its DNS flags will be set to dns.flags.RD. @param qname: The query name. @type qname: dns.name.Name object ...
1.807928
1.702648
1.061833
if query.flags & dns.flags.QR: raise dns.exception.FormError('specified query message is not a query') response = dns.message.Message(query.id) response.flags = dns.flags.QR | (query.flags & dns.flags.RD) if recursion_available: response.flags |= dns.flags.RA response.set_opcod...
def make_response(query, recursion_available=False, our_payload=8192)
Make a message which is a response for the specified query. The message returned is really a response skeleton; it has all of the infrastructure required of a response, but none of the content. The response's question section is a shallow copy of the query's question section, so the query's questio...
3.370056
3.211416
1.049399
s = cStringIO.StringIO() print >> s, 'id %d' % self.id print >> s, 'opcode %s' % \ dns.opcode.to_text(dns.opcode.from_flags(self.flags)) rc = dns.rcode.from_flags(self.flags, self.ednsflags) print >> s, 'rcode %s' % dns.rcode.to_text(rc) print >> s...
def to_text(self, origin=None, relativize=True, **kw)
Convert the message to text. The I{origin}, I{relativize}, and any other keyword arguments are passed to the rrset to_wire() method. @rtype: string
2.218561
2.242769
0.989206
if other.flags & dns.flags.QR == 0 or \ self.id != other.id or \ dns.opcode.from_flags(self.flags) != \ dns.opcode.from_flags(other.flags): return False if dns.rcode.from_flags(other.flags, other.ednsflags) != \ dns.rcode.NOERROR: ...
def is_response(self, other)
Is other a response to self? @rtype: bool
2.608313
2.608461
0.999943
key = (self.section_number(section), name, rdclass, rdtype, covers, deleting) if not force_unique: if not self.index is None: rrset = self.index.get(key) if not rrset is None: return rrset else: ...
def find_rrset(self, section, name, rdclass, rdtype, covers=dns.rdatatype.NONE, deleting=None, create=False, force_unique=False)
Find the RRset with the given attributes in the specified section. @param section: the section of the message to look in, e.g. self.answer. @type section: list of dns.rrset.RRset objects @param name: the name of the RRset @type name: dns.name.Name object @param rdclass: ...
2.13459
2.132649
1.00091
try: rrset = self.find_rrset(section, name, rdclass, rdtype, covers, deleting, create, force_unique) except KeyError: rrset = None return rrset
def get_rrset(self, section, name, rdclass, rdtype, covers=dns.rdatatype.NONE, deleting=None, create=False, force_unique=False)
Get the RRset with the given attributes in the specified section. If the RRset is not found, None is returned. @param section: the section of the message to look in, e.g. self.answer. @type section: list of dns.rrset.RRset objects @param name: the name of the RRset @typ...
2.065255
2.430366
0.849771
if max_size == 0: if self.request_payload != 0: max_size = self.request_payload else: max_size = 65535 if max_size < 512: max_size = 512 elif max_size > 65535: max_size = 65535 r = dns.renderer.Rend...
def to_wire(self, origin=None, max_size=0, **kw)
Return a string containing the message in DNS compressed wire format. Additional keyword arguments are passed to the rrset to_wire() method. @param origin: The origin to be appended to any relative names. @type origin: dns.name.Name object @param max_size: The maximum s...
2.651559
2.502838
1.059421
self.keyring = keyring if keyname is None: self.keyname = self.keyring.keys()[0] else: if isinstance(keyname, (str, unicode)): keyname = dns.name.from_text(keyname) self.keyname = keyname self.keyalgorithm = algorithm ...
def use_tsig(self, keyring, keyname=None, fudge=300, original_id=None, tsig_error=0, other_data='', algorithm=dns.tsig.default_algorithm)
When sending, a TSIG signature using the specified keyring and keyname should be added. @param keyring: The TSIG keyring to use; defaults to None. @type keyring: dict @param keyname: The name of the TSIG key to use; defaults to None. The key must be defined in the keyring. If a...
1.680176
1.776354
0.945856
if edns is None or edns is False: edns = -1 if edns is True: edns = 0 if request_payload is None: request_payload = payload if edns < 0: ednsflags = 0 payload = 0 request_payload = 0 options = []...
def use_edns(self, edns=0, ednsflags=0, payload=1280, request_payload=None, options=None)
Configure EDNS behavior. @param edns: The EDNS level to use. Specifying None, False, or -1 means 'do not use EDNS', and in this case the other parameters are ignored. Specifying True is equivalent to specifying 0, i.e. 'use EDNS0'. @type edns: int or bool or None @param...
2.608375
2.288934
1.139559
if wanted: if self.edns < 0: self.use_edns() self.ednsflags |= dns.flags.DO elif self.edns >= 0: self.ednsflags &= ~dns.flags.DO
def want_dnssec(self, wanted=True)
Enable or disable 'DNSSEC desired' flag in requests. @param wanted: Is DNSSEC desired? If True, EDNS is enabled if required, and then the DO bit is set. If False, the DO bit is cleared if EDNS is enabled. @type wanted: bool
3.612409
3.301336
1.094227
(value, evalue) = dns.rcode.to_flags(rcode) self.flags &= 0xFFF0 self.flags |= value self.ednsflags &= 0x00FFFFFFL self.ednsflags |= evalue if self.ednsflags != 0 and self.edns < 0: self.edns = 0
def set_rcode(self, rcode)
Set the rcode. @param rcode: the rcode @type rcode: int
4.305597
4.014802
1.072431
self.flags &= 0x87FF self.flags |= dns.opcode.to_flags(opcode)
def set_opcode(self, opcode)
Set the opcode. @param opcode: the opcode @type opcode: int
11.306932
10.909726
1.036408
if self.updating and qcount > 1: raise dns.exception.FormError for i in xrange(0, qcount): (qname, used) = dns.name.from_wire(self.wire, self.current) if not self.message.origin is None: qname = qname.relativize(self.message.origin) ...
def _get_question(self, qcount)
Read the next I{qcount} records from the wire data and add them to the question section. @param qcount: the number of questions in the message @type qcount: int
3.999675
3.691026
1.083622
if self.updating or self.one_rr_per_rrset: force_unique = True else: force_unique = False seen_opt = False for i in xrange(0, count): rr_start = self.current (name, used) = dns.name.from_wire(self.wire, self.current) a...
def _get_section(self, section, count)
Read the next I{count} records from the wire data and add them to the specified section. @param section: the section of the message to which to add records @type section: list of dns.rrset.RRset objects @param count: the number of records to read @type count: int
3.353274
3.178708
1.054917
l = len(self.wire) if l < 12: raise ShortHeader (self.message.id, self.message.flags, qcount, ancount, aucount, adcount) = struct.unpack('!HHHHHH', self.wire[:12]) self.current = 12 if dns.opcode.is_update(self.message.flags): self.updat...
def read(self)
Read a wire format DNS message and build a dns.message.Message object.
4.857376
3.814273
1.273474
token = self.tok.get() what = token.value if what == 'id': self.message.id = self.tok.get_int() elif what == 'flags': while True: token = self.tok.get() if not token.is_identifier(): self.tok.unget(toke...
def _header_line(self, section)
Process one line from the text format header section.
2.204697
2.147302
1.026729
token = self.tok.get(want_leading = True) if not token.is_whitespace(): self.last_name = dns.name.from_text(token.value, None) name = self.last_name token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError # Cl...
def _question_line(self, section)
Process one line from the text format question section.
3.263526
3.167185
1.030418
deleting = None # Name token = self.tok.get(want_leading = True) if not token.is_whitespace(): self.last_name = dns.name.from_text(token.value, None) name = self.last_name token = self.tok.get() if not token.is_identifier(): raise...
def _rr_line(self, section)
Process one line from the text format answer, authority, or additional data sections.
2.700815
2.632459
1.025967
line_method = self._header_line section = None while 1: token = self.tok.get(True, True) if token.is_eol_or_eof(): break if token.is_comment(): u = token.value.upper() if u == 'HEADER': ...
def read(self)
Read a text format DNS message and build a dns.message.Message object.
3.008011
2.397087
1.254861
if text.isdigit(): value = int(text) if value >= 0 and value <= 15: return value value = _by_text.get(text.upper()) if value is None: raise UnknownOpcode return value
def from_text(text)
Convert text into an opcode. @param text: the textual opcode @type text: string @raises UnknownOpcode: the opcode is unknown @rtype: int
4.523632
3.240813
1.395832
output_dir = config["output_dir"] for dirpath, dirnames, filenames in os.walk(output_dir): for dirname in dirnames: os.chmod(os.path.join(dirpath, dirname), 0755) for filename in filenames: os.chmod(os.path.join(dirpath, filename), 0644)
def chmod(config)
Set correct file permissions.
1.710572
1.649609
1.036956
if patterns is None: _trace_filter.clear() else: _trace_filter.update(re.compile(pat) for pat in patterns)
def trace_filter (patterns)
Add given patterns to trace filter set or clear set if patterns is None.
3.729235
2.862144
1.302951
if event in ('call', 'c_call'): _trace_line(frame, event, arg) elif event in ('return', 'c_return'): _trace_line(frame, event, arg) print(" return:", arg) #elif event in ('exception', 'c_exception'): # _trace_line(frame, event, arg) return _trace
def _trace (frame, event, arg)
Trace function calls.
2.430442
2.365486
1.02746
if event == "line": _trace_line(frame, event, arg) else: _trace(frame, event, arg) return _trace_full
def _trace_full (frame, event, arg)
Trace every executed line.
2.775356
2.696747
1.029149
name = frame.f_globals["__name__"] if name in _trace_ignore: return _trace_line for pat in _trace_filter: if not pat.match(name): return _trace_line lineno = frame.f_lineno filename = frame.f_globals["__file__"] if filename.endswith((".pyc", ".pyo")): fil...
def _trace_line (frame, event, arg)
Print current executed line.
3.034243
2.927352
1.036515
if full: sys.settrace(_trace_full) else: sys.settrace(_trace)
def trace_on (full=False)
Start tracing of the current thread (and the current thread only).
3.195345
3.037872
1.051837
super(DOTLogger, self).start_output() if self.has_part("intro"): self.write_intro() self.writeln() self.writeln(u"digraph G {") self.writeln(u" graph [") self.writeln(u" charset=\"%s\"," % self.get_charset_encoding()) self.writeln(u" ...
def start_output (self)
Write start of checking info as DOT comment.
5.090195
4.36646
1.165749
self.write(u"// ") self.writeln(s=s, **args)
def comment (self, s, **args)
Write DOT comment.
10.602638
7.525035
1.408982
node = self.get_node(url_data) if node is not None: self.writeln(u' "%s" [' % dotquote(node["label"])) if self.has_part("realurl"): self.writeln(u' href="%s",' % dotquote(node["url"])) if node["dltime"] >= 0 and self.has_part("dltime"): ...
def log_url (self, url_data)
Write one node.
2.876639
2.789648
1.031184
source = dotquote(self.nodes[node["parent_url"]]["label"]) target = dotquote(node["label"]) self.writeln(u' "%s" -> "%s" [' % (source, target)) self.writeln(u' label="%s",' % dotquote(node["edge"])) if self.has_part("result"): self.writeln(u" valid=%d,...
def write_edge (self, node)
Write edge from parent to node.
5.423935
5.050733
1.073891
super(CustomXMLLogger, self).start_output() self.xml_start_output() attrs = {"created": strformat.strtime(self.starttime)} self.xml_starttag(u'linkchecker', attrs) self.flush()
def start_output (self)
Write start of checking info as xml comment.
10.897066
8.672801
1.256464
self.xml_starttag(u'urldata') if self.has_part('url'): self.xml_tag(u"url", unicode(url_data.base_url)) if url_data.name and self.has_part('name'): self.xml_tag(u"name", unicode(url_data.name)) if url_data.parent_url and self.has_part('parenturl'): ...
def log_url (self, url_data)
Log URL data in custom XML format.
1.895929
1.857907
1.020465
self.xml_endtag(u"linkchecker") self.xml_end_output() self.close_fileoutput()
def end_output (self, **kwargs)
Write XML end tag.
18.058275
12.585019
1.434902
dom = parseString(xml) for error in dom.getElementsByTagName('m:error'): warnmsg = _("%(w3type)s validation error at line %(line)s col %(column)s: %(msg)s") attrs = { "w3type": w3type, "line": getXmlText(error, "m:line"), "column": getXmlText(error, "m:co...
def check_w3_errors (url_data, xml, w3type)
Add warnings for W3C HTML or CSS errors in xml format. w3type is either "W3C HTML" or "W3C CSS".
3.34872
3.059166
1.094651
elem = parent.getElementsByTagName(tag)[0] # Yes, the DOM standard is awful. rc = [] for node in elem.childNodes: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc)
def getXmlText (parent, tag)
Return XML content of given tag in parent element.
3.871144
3.647188
1.061405
if time.time() - self.last_w3_call < W3Timer.SleepSeconds: time.sleep(W3Timer.SleepSeconds) self.last_w3_call = time.time()
def check_w3_time (self)
Make sure the W3C validators are at most called once a second.
4.023577
3.044552
1.321566
self.timer.check_w3_time() session = url_data.session try: body = {'uri': url_data.url, 'output': 'soap12'} response = session.post('http://validator.w3.org/check', data=body) response.raise_for_status() if response.headers.get('x-w3c-vali...
def check(self, url_data)
Check HTML syntax of given URL.
5.764654
5.465703
1.054696
super(SitemapXmlLogger, self).start_output() self.xml_start_output() attrs = {u"xmlns": u"http://www.sitemaps.org/schemas/sitemap/0.9"} self.xml_starttag(u'urlset', attrs) self.flush()
def start_output (self)
Write start of checking info as xml comment.
4.571213
3.819864
1.196695
self.stats.log_url(url_data, do_print) if self.disabled: return # initialize prefix and priority if self.prefix is None: if not url_data.url.startswith(HTTP_SCHEMES): log.warn(LOG_CHECK, "Sitemap URL %r does not start with http: or https:....
def log_filter_url(self, url_data, do_print)
Update accounting data and determine if URL should be included in the sitemap.
4.357512
4.226724
1.030943
self.xml_starttag(u'url') self.xml_tag(u'loc', url_data.url) if url_data.modified: self.xml_tag(u'lastmod', self.format_modified(url_data.modified, sep="T")) self.xml_tag(u'changefreq', self.frequency) self.xml_tag(u'priority', "%.2f" % priority) self...
def log_url (self, url_data, priority=None)
Log URL data in sitemap format.
2.922991
2.59645
1.125764
self.xml_endtag(u"urlset") self.xml_end_output() self.close_fileoutput()
def end_output (self, **kwargs)
Write XML end tag.
13.73325
9.091056
1.510633
super(HttpUrl, self).reset() # initialize check data # server headers self.headers = {} self.auth = None self.ssl_cipher = None self.ssl_cert = None
def reset (self)
Initialize HTTP specific variables.
10.71806
8.007605
1.338485
if not self.is_html(): return True # construct parser object handler = linkparse.MetaRobotsFinder() parser = htmlsax.parser(handler) handler.parser = parser if self.charset: parser.encoding = self.charset # parse try: ...
def content_allows_robots (self)
Return False if the content of this URL forbids robots to search for recursive links.
8.128972
7.72584
1.05218
if self.headers and "Content-Length" in self.headers and \ "Transfer-Encoding" not in self.headers: # Note that content-encoding causes size differences since # the content data is always decoded. try: self.size = int(self.getheader("Conten...
def add_size_info (self)
Get size of URL content from HTTP header.
5.223185
4.408673
1.184752
self.session = self.aggregate.get_request_session() # set the proxy, so a 407 status after this is an error self.set_proxy(self.aggregate.config["proxy"].get(self.scheme)) self.construct_auth() # check robots.txt if not self.allows_robots(self.url): s...
def check_connection (self)
Check a URL with HTTP protocol. Here is an excerpt from RFC 1945 with common response codes: The first digit of the Status-Code defines the class of response. The last two digits do not have any categorization role. There are 5 values for the first digit: - 1xx: Informational -...
8.655499
8.466906
1.022274
clientheaders = {} if (self.parent_url and self.parent_url.lower().startswith(HTTP_SCHEMAS)): clientheaders["Referer"] = self.parent_url kwargs = dict( method='GET', url=self.url, headers=clientheaders, ) if sel...
def build_request(self)
Build a prepared request object.
4.004943
3.67619
1.089428
# throttle the number of requests to each host self.aggregate.wait_for_host(self.urlparts[1]) kwargs = self.get_request_kwargs() kwargs["allow_redirects"] = False self._send_request(request, **kwargs)
def send_request(self, request)
Send request and store response in self.url_connection.
7.533194
7.16287
1.0517
log.debug(LOG_CHECK, "Send request %s with %s", request, kwargs) log.debug(LOG_CHECK, "Request headers %s", request.headers) self.url_connection = self.session.send(request, **kwargs) self.headers = self.url_connection.headers self._add_ssl_info()
def _send_request(self, request, **kwargs)
Send GET request.
4.271493
3.985696
1.071706
self.charset = httputil.get_charset(self.headers) self.set_content_type() self.add_size_info()
def _add_response_info(self)
Set info from established HTTP(S) connection.
7.954307
5.89707
1.348857
assert self.scheme == u"https", self raw_connection = self.url_connection.raw._connection if raw_connection.sock is None: # sometimes the socket is not yet connected # see https://github.com/kennethreitz/requests/issues/1966 raw_connection.connect() ...
def _get_ssl_sock(self)
Get raw SSL socket.
5.002155
4.796789
1.042813
if self.scheme == u'https': sock = self._get_ssl_sock() if hasattr(sock, 'cipher'): self.ssl_cert = sock.getpeercert() else: # using pyopenssl cert = sock.connection.get_peer_certificate() self.ssl_cert ...
def _add_ssl_info(self)
Add SSL cipher info.
4.144922
3.926074
1.055742
if self.auth: return _user, _password = self.get_user_password() if _user is not None and _password is not None: self.auth = (_user, _password)
def construct_auth (self)
Construct HTTP Basic authentication credentials if there is user/password information available. Does not overwrite if credentials have already been constructed.
3.23189
2.626359
1.230559
kwargs = dict(stream=True, timeout=self.aggregate.config["timeout"]) if self.proxy: kwargs["proxies"] = {self.proxytype: self.proxy} if self.scheme == u"https" and self.aggregate.config["sslverify"]: kwargs['verify'] = self.aggregate.config["sslverify"] e...
def get_request_kwargs(self)
Construct keyword parameters for Session.request() and Session.resolve_redirects().
3.681887
3.390948
1.085799
kwargs = self.get_request_kwargs() return self.session.resolve_redirects(self.url_connection, request, **kwargs)
def get_redirects(self, request)
Return iterator of redirects for given request.
9.114347
7.684524
1.186065
log.debug(LOG_CHECK, "follow all redirections") if self.is_redirect(): # run connection plugins for old connection self.aggregate.plugin_manager.run_connection_plugins(self) response = None for response in self.get_redirects(request): newurl =...
def follow_redirections(self, request)
Follow all redirections of http response.
5.749139
5.61517
1.023858
value = self.headers.get(name) if value is None: return default return unicode_safe(value, encoding=HEADER_ENCODING)
def getheader (self, name, default=None)
Get decoded header value. @return: decoded header value or default of not found @rtype: unicode or type of default
6.226853
7.251708
0.858674
if self.url_connection.status_code >= 400: self.set_result(u"%d %s" % (self.url_connection.status_code, self.url_connection.reason), valid=False) else: if self.url_connection.status_code == 204: # no content sel...
def check_response (self)
Check final result and log it.
3.20274
3.113125
1.028786
maxbytes = self.aggregate.config["maxfilesizedownload"] buf = StringIO() for data in self.url_connection.iter_content(chunk_size=self.ReadChunkBytes): if buf.tell() + len(data) > maxbytes: raise LinkCheckerError(_("File size too large")) buf.write...
def read_content(self)
Return data and data size for this URL. Can be overridden in subclasses.
7.255165
6.767167
1.072113
for linktype, linkinfo in self.url_connection.links.items(): url = linkinfo["url"] name = u"Link: header %s" % linktype self.add_url(url, name=name) if 'Refresh' in self.headers: from ..htmlutil.linkparse import refresh_re value = self...
def parse_header_links(self)
Parse URLs in HTTP headers Link:.
3.410165
3.25168
1.048739
if not self.valid: return False # some content types must be validated with the page content if self.content_type in ("application/xml", "text/xml"): rtype = mimeutil.guess_mimetype_read(self.get_content) if rtype is not None: # XXX si...
def is_parseable (self)
Check if content is parseable for recursion. @return: True if content is parseable @rtype: bool
6.32372
6.444752
0.98122
if type_str not in open_files: filename = type_str+".html" encoding = 'utf-8' fd = codecs.open(os.path.join(basedir, filename), 'w', encoding) open_files[type_str] = fd write_html_header(fd, type_str, encoding) return open_files[type_str]
def get_file(type_str, open_files, basedir)
Get already opened file, or open and initialize a new one.
2.348576
2.36068
0.994873
from .. import loader modules = loader.get_package_modules('logger') return list(loader.get_plugins(modules, [_Logger]))
def _get_loggers()
Return list of Logger classes.
12.728541
9.627336
1.322125
# number of logged URLs self.number = 0 # number of encountered URL errors self.errors = 0 # number of URL errors that were printed self.errors_printed = 0 # number of URL warnings self.warnings = 0 # number of URL warnings that were print...
def reset (self)
Reset all log statistics to default values.
3.702161
3.395718
1.090244
self.number += 1 if not url_data.valid: self.errors += 1 if do_print: self.errors_printed += 1 num_warnings = len(url_data.warnings) self.warnings += num_warnings if do_print: self.warnings_printed += num_warnings ...
def log_url (self, url_data, do_print)
Log URL statistics.
2.679624
2.602647
1.029577
args = dict(self.LoggerArgs) args.update(kwargs) return args
def get_args(self, kwargs)
Construct log configuration from default and user args.
8.494861
5.570655
1.52493
assert isinstance(s, unicode) return s.encode(self.output_encoding, self.codec_errors)
def encode (self, s)
Encode string with output encoding.
6.339068
4.585674
1.382363
self.filename = None self.close_fd = False self.fd = None if args.get('fileoutput'): self.filename = os.path.expanduser(args['filename']) elif 'fd' in args: self.fd = args['fd'] else: self.fd = self.create_fd()
def init_fileoutput (self, args)
Initialize self.fd file descriptor from args. For file output (used when the fileoutput arg is given), the self.fd initialization is deferred until the first self.write() call. This avoids creation of an empty file when no output is written.
3.439134
2.780755
1.236763
path = os.path.dirname(self.filename) try: if path and not os.path.isdir(path): os.makedirs(path) self.fd = self.create_fd() self.close_fd = True except IOError: msg = sys.exc_info()[1] log.warn(LOG_CHECK, ...
def start_fileoutput (self)
Start output to configured file.
4.623074
4.543968
1.017409
if self.filename is None: return i18n.get_encoded_writer(encoding=self.output_encoding, errors=self.codec_errors) return codecs.open(self.filename, "wb", self.output_encoding, self.codec_errors)
def create_fd (self)
Create open file descriptor.
5.605238
5.521812
1.015108
if self.fd is not None: try: self.flush() except IOError: # ignore flush errors pass if self.close_fd: try: self.fd.close() except IOError: # ignor...
def close_fileoutput (self)
Flush and close the file output denoted by self.fd.
3.041773
2.501473
1.215992
now = datetime.date.today() if now.day == 7 and now.month == 1: msg = _("Happy birthday for LinkChecker, I'm %d years old today!") self.comment(msg % (now.year - 2000))
def check_date (self)
Check for special dates.
8.49403
7.684529
1.105342
sep = os.linesep+os.linesep text = sep.join(lines) kwargs = dict(subsequent_indent=" "*self.max_indent, initial_indent=" "*self.max_indent, break_long_words=False, break_on_hyphens=False) return strformat.wrap(tex...
def wrap (self, lines, width)
Return wrapped version of given lines.
4.293724
3.919082
1.095594
if self.filename is not None: self.start_fileoutput() if self.fd is None: # Happens when aborting threads times out log.warn(LOG_CHECK, "writing to unitialized or closed file") else: try: self.fd.write(s, **args) ...
def write (self, s, **args)
Write string to output descriptor. Strips control characters from string before writing.
6.652895
6.474995
1.027475
self.write(u"%s%s" % (s, unicode(os.linesep)), **args)
def writeln (self, s=u"", **args)
Write string to output descriptor plus a newline.
5.19206
3.554209
1.46082
# map with spaces between part name and value if self.logparts is None: parts = Fields.keys() else: parts = self.logparts values = (self.part(x) for x in parts) # maximum indent for localized log part names self.max_indent = max(len(x) for...
def start_output (self)
Start log output.
7.146205
6.891617
1.036942
self.stats.log_url(url_data, do_print) if do_print: self.log_url(url_data)
def log_filter_url (self, url_data, do_print)
Log a new url with this logger if do_print is True. Else only update accounting data.
3.843946
3.121063
1.231614
self.comment(_("created by %(app)s at %(time)s") % {"app": configuration.AppName, "time": strformat.strtime(self.starttime)}) self.comment(_("Get the newest version at %(url)s") % {'url': configuration.Url}) self.comment(_("W...
def write_intro (self)
Write intro comments.
5.231422
4.847906
1.07911
self.stoptime = time.time() duration = self.stoptime - self.starttime self.comment(_("Stopped checking at %(time)s (%(duration)s)") % {"time": strformat.strtime(self.stoptime), "duration": strformat.strduration_long(duration)})
def write_outro (self)
Write outro comments.
6.042504
5.280645
1.144274
if modified is not None: return modified.strftime("%Y-%m-%d{0}%H:%M:%S.%fZ".format(sep)) return u""
def format_modified(self, modified, sep=" ")
Format modification date in UTC if it's not None. @param modified: modification date in UTC @ptype modified: datetime or None @return: formatted date or empty string @rtype: unicode
4.074614
3.618896
1.125927
# the environment variable CONTENT_LENGTH may be empty or missing try: request_body_size = int(environ.get('CONTENT_LENGTH', 0)) except ValueError: request_body_size = 0 # When the method is POST the query string will be sent # in the HTTP request body which is passed by the WS...
def application(environ, start_response)
WSGI interface: start an URL check.
3.155398
3.143653
1.003736
field = form.get(key) if isinstance(field, list): field = field[0] return field
def formvalue (form, key)
Get value with given key from WSGI form.
3.591297
3.211857
1.118137
if form is None: form = {} try: checkform(form, env) except LCFormError as errmsg: log(env, errmsg) yield encode(format_error(errmsg)) return out = ThreadsafeIO() config = get_configuration(form, out) url = strformat.stripurl(formvalue(form, "url")) ...
def checklink (form=None, env=os.environ)
Validates the CGI form and checks the given links.
9.616689
9.258551
1.038682
# check in background t = threading.Thread(target=director.check_urls, args=(aggregate,)) t.start() # time to wait for new data sleep_seconds = 2 # current running time run_seconds = 0 while not aggregate.is_finished(): yield out.get_data() time.sleep(sleep_seconds) ...
def start_check (aggregate, out)
Start checking in background and write encoded output to out.
4.943217
4.858125
1.017515
config = configuration.Configuration() config["recursionlevel"] = int(formvalue(form, "level")) config["logger"] = config.logger_new('html', fd=out, encoding=HTML_ENCODING) config["threads"] = 2 if "anchors" in form: config["enabledplugins"].append("AnchorCheck") if "errors" not in ...
def get_configuration(form, out)
Initialize a CGI configuration.
13.334446
13.129336
1.015622
# check lang support if "language" in form: lang = formvalue(form, 'language') if lang in _supported_langs: localestr = lang_locale[lang] try: # XXX this is not thread-safe, so think of something else locale.setlocale(locale.LC_ALL, lo...
def checkform (form, env)
Check form data. throw exception on error Be sure to NOT print out any user-given data as HTML code, so use only plain strings as exception text.
3.29707
3.278195
1.005758
for var, value in env.items(): log(env, var+"="+value) for key in form: log(env, str(formvalue(form, key)))
def dump (env, form)
Log environment and form.
7.608276
6.002946
1.267424
assert isinstance(data, unicode) if self.closed: raise IOError("Write on closed I/O object") if data: self.buf.append(data)
def write (self, data)
Write given unicode data to buffer.
5.232017
3.866363
1.353214
data = u"".join(self.buf) self.buf = [] return data
def get_data (self)
Get bufferd unicode data.
6.886942
4.236303
1.625696
if url_data.is_directory(): # both ftp and file links represent directories as HTML data key = "html" elif url_data.is_file() and firefox.has_sqlite and firefox.extension.search(url_data.url): key = "firefox" elif url_data.scheme == "itms-services": key = "itms_services"...
def parse_url(url_data)
Parse a URL.
8.35111
8.357999
0.999176
from ..bookmarks.opera import parse_bookmark_data for url, name, lineno in parse_bookmark_data(url_data.get_content()): url_data.add_url(url, line=lineno, name=name)
def parse_opera (url_data)
Parse an opera bookmark file.
6.060423
5.126855
1.182094