instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Write docstrings for utility functions | import six
from w3lib.url import safe_url_string
from scrapy.http.headers import Headers
from scrapy.utils.python import to_bytes
from scrapy.utils.trackref import object_ref
from scrapy.utils.url import escape_ajax
from scrapy.http.common import obsolete_setter
class Request(object_ref):
def __init__(self, url... | --- +++ @@ -1,3 +1,9 @@+"""
+This module implements the Request class which is used to represent HTTP
+requests in Scrapy.
+
+See documentation in docs/topics/request-response.rst
+"""
import six
from w3lib.url import safe_url_string
@@ -85,11 +91,15 @@ __repr__ = __str__
def copy(self):
+ """Retu... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/http/request/__init__.py |
Document functions with clear intent | import warnings
import six
from scrapy.utils.python import to_bytes
class Link(object):
__slots__ = ['url', 'text', 'fragment', 'nofollow']
def __init__(self, url, text='', fragment='', nofollow=False):
if not isinstance(url, str):
if six.PY2:
warnings.warn("Link urls mu... | --- +++ @@ -1,3 +1,9 @@+"""
+This module defines the Link object used in Link extractors.
+
+For actual link extractors implementation see scrapy.linkextractors, or
+its documentation in: docs/topics/link-extractors.rst
+"""
import warnings
import six
@@ -5,6 +11,7 @@
class Link(object):
+ """Link objects re... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/link.py |
Generate docstrings for script automation |
from abc import ABCMeta
from pprint import pformat
from copy import deepcopy
import collections
import six
from scrapy.utils.trackref import object_ref
if six.PY2:
MutableMapping = collections.MutableMapping
else:
MutableMapping = collections.abc.MutableMapping
class BaseItem(object_ref):
pass
clas... | --- +++ @@ -1,3 +1,8 @@+"""
+Scrapy Item
+
+See documentation in docs/topics/item.rst
+"""
from abc import ABCMeta
from pprint import pformat
@@ -16,10 +21,12 @@
class BaseItem(object_ref):
+ """Base class for all scraped items."""
pass
class Field(dict):
+ """Container of field metadata"""
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/item.py |
Add standardized docstrings across the file |
import six
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root_node
from w3lib.html import strip_html5_whitespace
from scrapy.http.request import Request
from scrapy.utils.python import to_bytes, is_listlike
from scrapy.utils.response import get_base_url
c... | --- +++ @@ -1,3 +1,9 @@+"""
+This module implements the FormRequest class which is a more convenient class
+(than Request) to generate Requests based on form data.
+
+See documentation in docs/topics/request-response.rst
+"""
import six
from six.moves.urllib.parse import urljoin, urlencode
@@ -70,6 +76,7 @@
def... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/http/request/form.py |
Add detailed docstrings explaining each function | from __future__ import print_function
import functools
import logging
from collections import defaultdict
from twisted.internet.defer import Deferred, DeferredList, _DefGen_Return
from twisted.python.failure import Failure
from scrapy.settings import Settings
from scrapy.utils.datatypes import SequenceExclude
from sc... | --- +++ @@ -47,6 +47,14 @@
def _key_for_pipe(self, key, base_class_name=None,
settings=None):
+ """
+ >>> MediaPipeline()._key_for_pipe("IMAGES")
+ 'IMAGES'
+ >>> class MyPipe(MediaPipeline):
+ ... pass
+ >>> MyPipe()._key_for_pipe("IMAGES", bas... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/pipelines/media.py |
Write docstrings for data processing functions | from six.moves.urllib.parse import urlparse
import warnings
from w3lib.url import safe_url_string
from scrapy.http import Request, Response
from scrapy.exceptions import NotConfigured
from scrapy import signals
from scrapy.utils.python import to_native_str
from scrapy.utils.httpobj import urlparse_cached
from scrapy.... | --- +++ @@ -1,3 +1,7 @@+"""
+RefererMiddleware: populates Request referer field, based on the Response which
+originated it.
+"""
from six.moves.urllib.parse import urlparse
import warnings
@@ -41,6 +45,19 @@ return self.origin(url)
def strip_url(self, url, origin_only=False):
+ """
+ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/spidermiddlewares/referer.py |
Add inline docstrings for readability |
import warnings
from parsel import Selector as _ParselSelector
from scrapy.utils.trackref import object_ref
from scrapy.utils.python import to_bytes
from scrapy.http import HtmlResponse, XmlResponse
from scrapy.utils.decorators import deprecated
__all__ = ['Selector', 'SelectorList']
def _st(response, st):
if ... | --- +++ @@ -1,3 +1,6 @@+"""
+XPath selectors based on lxml
+"""
import warnings
from parsel import Selector as _ParselSelector
@@ -23,9 +26,42 @@
class SelectorList(_ParselSelector.selectorlist_cls, object_ref):
+ """
+ The :class:`SelectorList` class is a subclass of the builtin ``list``
+ class, whic... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/selector/unified.py |
Add well-formatted docstrings |
import six
from six.moves.urllib.parse import urljoin
import parsel
from w3lib.encoding import html_to_unicode, resolve_encoding, \
html_body_declared_encoding, http_content_type_encoding
from w3lib.html import strip_html5_whitespace
from scrapy.http.request import Request
from scrapy.http.response import Respon... | --- +++ @@ -1,3 +1,9 @@+"""
+This module implements the TextResponse class which adds encoding handling and
+discovering (through HTTP headers) to base Response class.
+
+See documentation in docs/topics/request-response.rst
+"""
import six
from six.moves.urllib.parse import urljoin
@@ -56,10 +62,12 @@ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/http/response/text.py |
Generate docstrings for this script | import functools
import hashlib
import six
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
from PIL import Image
from scrapy.utils.misc import md5sum
from scrapy.utils.python import to_bytes
from scrapy.http import Request
from scrapy.settings import Settings
from sc... | --- +++ @@ -1,3 +1,8 @@+"""
+Images Pipeline
+
+See documentation in topics/media-pipeline.rst
+"""
import functools
import hashlib
import six
@@ -19,12 +24,17 @@
class NoimagesDrop(DropItem):
+ """Product with no images exception"""
class ImageException(FileException):
+ """General image error except... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/pipelines/images.py |
Add docstrings for internal functions |
from functools import partial
from scrapy.utils.python import get_func_args
def wrap_loader_context(function, context):
if 'loader_context' in get_func_args(function):
return partial(function, loader_context=context)
else:
return function | --- +++ @@ -1,9 +1,13 @@+"""Common functions used in Item Loaders code"""
from functools import partial
from scrapy.utils.python import get_func_args
def wrap_loader_context(function, context):
+ """Wrap functions that receive loader_context to contain the context
+ "pre-loaded" and expose a interface that... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/loader/common.py |
Replace inline comments with docstrings |
import copy
import warnings
import six
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.http import Request, HtmlResponse
from scrapy.utils.spider import iterate_spider_output
from scrapy.utils.python import get_func_args
from scrapy.spiders import Spider
def _identity(request, response):
ret... | --- +++ @@ -1,3 +1,9 @@+"""
+This modules implements the CrawlSpider which is the recommended spider to use
+for scraping typical web sites that requires crawling pages.
+
+See documentation in docs/topics/spiders.rst
+"""
import copy
import warnings
@@ -43,6 +49,10 @@ warnings.warn(msg, category=Scrapy... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/spiders/crawl.py |
Create docstrings for reusable components | from scrapy.spiders import Spider
from scrapy.utils.spider import iterate_spider_output
class InitSpider(Spider):
def start_requests(self):
self._postinit_reqs = super(InitSpider, self).start_requests()
return iterate_spider_output(self.init_request())
def initialized(self, response=None):
... | --- +++ @@ -3,13 +3,30 @@
class InitSpider(Spider):
+ """Base Spider with initialization facilities"""
def start_requests(self):
self._postinit_reqs = super(InitSpider, self).start_requests()
return iterate_spider_output(self.init_request())
def initialized(self, response=None):
+... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/spiders/init.py |
Generate helpful docstrings for debugging | import re
import logging
import warnings
from scrapy import signals
from scrapy.http import Request
from scrapy.utils.httpobj import urlparse_cached
logger = logging.getLogger(__name__)
class OffsiteMiddleware(object):
def __init__(self, stats):
self.stats = stats
@classmethod
def from_crawler... | --- +++ @@ -1,3 +1,8 @@+"""
+Offsite Spider Middleware
+
+See documentation in docs/topics/spider-middleware.rst
+"""
import re
import logging
import warnings
@@ -44,6 +49,7 @@ return bool(regex.search(host))
def get_host_regex(self, spider):
+ """Override this method to implement a different o... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/spidermiddlewares/offsite.py |
Write docstrings for backend logic |
import logging
from collections import deque
from twisted.python.failure import Failure
from twisted.internet import defer
from scrapy.utils.defer import defer_result, defer_succeed, parallel, iter_errback
from scrapy.utils.spider import iterate_spider_output
from scrapy.utils.misc import load_object
from scrapy.uti... | --- +++ @@ -1,3 +1,5 @@+"""This module implements the Scraper component which parses responses and
+extracts information from them"""
import logging
from collections import deque
@@ -20,6 +22,7 @@
class Slot(object):
+ """Scraper slot (one per running spider)"""
MIN_RESPONSE_SIZE = 1024
@@ -73,10 +7... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/core/scraper.py |
Generate NumPy-style docstrings | import re
import logging
import six
from scrapy.spiders import Spider
from scrapy.http import Request, XmlResponse
from scrapy.utils.sitemap import Sitemap, sitemap_urls_from_robots
from scrapy.utils.gz import gunzip, gzip_magic_number
logger = logging.getLogger(__name__)
class SitemapSpider(Spider):
sitemap_... | --- +++ @@ -32,6 +32,10 @@ yield Request(url, self._parse_sitemap)
def sitemap_filter(self, entries):
+ """This method can be used to filter sitemap entries by their
+ attributes, for example, you can filter locs with lastmod greater
+ than a given date (see docs).
+ """
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/spiders/sitemap.py |
Document classes and their methods | import logging
from scrapy.exceptions import IgnoreRequest
logger = logging.getLogger(__name__)
class HttpError(IgnoreRequest):
def __init__(self, response, *args, **kwargs):
self.response = response
super(HttpError, self).__init__(*args, **kwargs)
class HttpErrorMiddleware(object):
@cla... | --- +++ @@ -1,3 +1,8 @@+"""
+HttpError Spider Middleware
+
+See documentation in docs/topics/spider-middleware.rst
+"""
import logging
from scrapy.exceptions import IgnoreRequest
@@ -6,6 +11,7 @@
class HttpError(IgnoreRequest):
+ """A non-200 response was filtered"""
def __init__(self, response, *args... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/spidermiddlewares/httperror.py |
Please document this code using docstrings | from __future__ import absolute_import
from pydispatch import dispatcher
from scrapy.utils import signal as _signal
class SignalManager(object):
def __init__(self, sender=dispatcher.Anonymous):
self.sender = sender
def connect(self, receiver, signal, **kwargs):
kwargs.setdefault('sender', se... | --- +++ @@ -9,21 +9,63 @@ self.sender = sender
def connect(self, receiver, signal, **kwargs):
+ """
+ Connect a receiver function to a signal.
+
+ The signal can be any object, although Scrapy comes with some
+ predefined signals that are documented in the :ref:`topics-signals... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/signalmanager.py |
Generate docstrings for each module | import struct
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
from gzip import GzipFile
import six
import re
from scrapy.utils.decorators import deprecated
# - Python>=3.5 GzipFile's read() has issues returning leftover
# uncompressed data when input is corrupted... | --- +++ @@ -28,6 +28,10 @@
def gunzip(data):
+ """Gunzip the given data and return as much data as possible.
+
+ This is resilient to CRC checksum errors.
+ """
f = GzipFile(fileobj=BytesIO(data))
output_list = []
chunk = b'.'
@@ -54,6 +58,7 @@
@deprecated
def is_gzipped(response):
+ "... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/gz.py |
Insert docstrings into my code | from __future__ import print_function
import os
import signal
import warnings
from twisted.internet import reactor, threads, defer
from twisted.python import threadable
from w3lib.url import any_to_uri
from scrapy.crawler import Crawler
from scrapy.exceptions import IgnoreRequest, ScrapyDeprecationWarning
from scrap... | --- +++ @@ -1,3 +1,8 @@+"""Scrapy Shell
+
+See documentation in docs/topics/shell.rst
+
+"""
from __future__ import print_function
import os
@@ -158,10 +163,21 @@
def inspect_response(response, spider):
+ """Open a shell to inspect the given response"""
Shell(spider.crawler).start(response=response, spi... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/shell.py |
Document functions with clear intent | from scrapy.spiders import Spider
from scrapy.utils.iterators import xmliter, csviter
from scrapy.utils.spider import iterate_spider_output
from scrapy.selector import Selector
from scrapy.exceptions import NotConfigured, NotSupported
class XMLFeedSpider(Spider):
iterator = 'iternodes'
itertag = 'item'
n... | --- +++ @@ -1,3 +1,9 @@+"""
+This module implements the XMLFeedSpider which is the recommended spider to use
+for scraping from an XML feed.
+
+See documentation in docs/topics/spiders.rst
+"""
from scrapy.spiders import Spider
from scrapy.utils.iterators import xmliter, csviter
from scrapy.utils.spider import itera... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/spiders/feed.py |
Insert docstrings into my code | import re
import csv
import logging
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
from io import StringIO
import six
from scrapy.http import TextResponse, Response
from scrapy.selector import Selector
from scrapy.utils.python import re_rsearch, to_unicode
logger = l... | --- +++ @@ -16,6 +16,14 @@
def xmliter(obj, nodename):
+ """Return a iterator of Selector's over all nodes of a XML document,
+ given the name of the node to iterate. Useful for parsing XML feeds.
+
+ obj can be:
+ - a Response object
+ - a unicode string
+ - a string encoded as utf-8
+ """
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/iterators.py |
Add docstrings that explain inputs and outputs | import warnings
import six
from six.moves.html_parser import HTMLParser
from six.moves.urllib.parse import urljoin
from w3lib.url import safe_url_string
from w3lib.html import strip_html5_whitespace
from scrapy.link import Link
from scrapy.utils.python import unique as unique_list
from scrapy.exceptions import Scrapy... | --- +++ @@ -1,3 +1,6 @@+"""
+HTMLParser-based link extractor
+"""
import warnings
import six
from six.moves.html_parser import HTMLParser
@@ -84,4 +87,6 @@ self.current_link.text = self.current_link.text + data
def matches(self, url):
- return True+ """This extractor matches with any... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/linkextractors/htmlparser.py |
Add detailed documentation for each class | import six
from w3lib.http import headers_dict_to_raw
from scrapy.utils.datatypes import CaselessDict
from scrapy.utils.python import to_unicode
class Headers(CaselessDict):
def __init__(self, seq=None, encoding='utf-8'):
self.encoding = encoding
super(Headers, self).__init__(seq)
def normke... | --- +++ @@ -5,15 +5,18 @@
class Headers(CaselessDict):
+ """Case insensitive http headers dictionary"""
def __init__(self, seq=None, encoding='utf-8'):
self.encoding = encoding
super(Headers, self).__init__(seq)
def normkey(self, key):
+ """Normalize key to bytes"""
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/http/headers.py |
Add detailed documentation for each class |
import weakref
from six.moves.urllib.parse import urlparse
_urlparse_cache = weakref.WeakKeyDictionary()
def urlparse_cached(request_or_response):
if request_or_response not in _urlparse_cache:
_urlparse_cache[request_or_response] = urlparse(request_or_response.url)
return _urlparse_cache[request_or_... | --- +++ @@ -1,3 +1,4 @@+"""Helper functions for scrapy.http objects (Request, Response)"""
import weakref
@@ -5,6 +6,9 @@
_urlparse_cache = weakref.WeakKeyDictionary()
def urlparse_cached(request_or_response):
+ """Return urlparse.urlparse caching the result, where the argument can be a
+ Request or Respo... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/httpobj.py |
Add docstrings to my Python code | from __future__ import print_function
import os
import gzip
import logging
from six.moves import cPickle as pickle
from importlib import import_module
from time import time
from weakref import WeakKeyDictionary
from email.utils import mktime_tz, parsedate_tz
from w3lib.http import headers_raw_to_dict, headers_dict_to_r... | --- +++ @@ -285,6 +285,7 @@ pass
def retrieve_response(self, spider, request):
+ """Return response if present in cache, or None otherwise."""
metadata = self._read_meta(spider, request)
if metadata is None:
return # not cached
@@ -301,6 +302,7 @@ return res... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/extensions/httpcache.py |
Write docstrings including parameters and return values |
import os
import sys
import logging
import posixpath
from tempfile import NamedTemporaryFile
from datetime import datetime
import six
from six.moves.urllib.parse import urlparse
from ftplib import FTP
from zope.interface import Interface, implementer
from twisted.internet import defer, threads
from w3lib.url import f... | --- +++ @@ -1,3 +1,8 @@+"""
+Feed Exports extension
+
+See documentation in docs/topics/feed-exports.rst
+"""
import os
import sys
@@ -25,12 +30,17 @@
class IFeedStorage(Interface):
+ """Interface that all Feed Storages must implement"""
def __init__(uri):
+ """Initialize the storage with the p... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/extensions/feedexport.py |
Create structured documentation for my script | import six
import json
import copy
import collections
from importlib import import_module
from pprint import pformat
from scrapy.settings import default_settings
if six.PY2:
MutableMapping = collections.MutableMapping
else:
MutableMapping = collections.abc.MutableMapping
SETTINGS_PRIORITIES = {
'defaul... | --- +++ @@ -24,6 +24,11 @@
def get_settings_priority(priority):
+ """
+ Small helper function that looks up a given string priority in the
+ :attr:`~scrapy.settings.SETTINGS_PRIORITIES` dictionary and returns its
+ numerical value, or directly returns a given numerical priority.
+ """
if isinsta... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/settings/__init__.py |
Add docstrings following best practices | from __future__ import absolute_import
from mimetypes import MimeTypes
from pkgutil import get_data
from io import StringIO
import six
from scrapy.http import Response
from scrapy.utils.misc import load_object
from scrapy.utils.python import binary_is_text, to_bytes, to_native_str
class ResponseTypes(object):
C... | --- +++ @@ -1,3 +1,7 @@+"""
+This module implements a class which returns the appropriate Response class
+based on different criteria.
+"""
from __future__ import absolute_import
from mimetypes import MimeTypes
from pkgutil import get_data
@@ -37,6 +41,7 @@ self.classes[mimetype] = load_object(cls)
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/responsetypes.py |
Add clean documentation to messy code | # -*- coding: utf-8 -*-
import sys
import logging
import warnings
from logging.config import dictConfig
from twisted.python.failure import Failure
from twisted.python import log as twisted_log
import scrapy
from scrapy.settings import Settings
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils.... | --- +++ @@ -18,11 +18,22 @@
def failure_to_exc_info(failure):
+ """Extract exc_info from Failure instances"""
if isinstance(failure, Failure):
return (failure.type, failure.value, failure.getTracebackObject())
class TopLevelFormatter(logging.Filter):
+ """Keep only top level loggers's name ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/log.py |
Fully document this Python code with docstrings |
from __future__ import print_function
import hashlib
import weakref
from six.moves.urllib.parse import urlunparse
from w3lib.http import basic_auth_header
from scrapy.utils.python import to_bytes, to_native_str
from w3lib.url import canonicalize_url
from scrapy.utils.httpobj import urlparse_cached
_fingerprint_cac... | --- +++ @@ -1,3 +1,7 @@+"""
+This module provides some useful functions for working with
+scrapy.http.Request objects
+"""
from __future__ import print_function
import hashlib
@@ -13,6 +17,32 @@
_fingerprint_cache = weakref.WeakKeyDictionary()
def request_fingerprint(request, include_headers=None):
+ """
+ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/request.py |
Add docstrings that explain logic | import six
import signal
import logging
import warnings
import sys
from twisted.internet import reactor, defer
from zope.interface.verify import verifyClass, DoesNotImplement
from scrapy import Spider
from scrapy.core.engine import ExecutionEngine
from scrapy.resolver import CachingThreadedResolver
from scrapy.interf... | --- +++ @@ -112,12 +112,25 @@
@defer.inlineCallbacks
def stop(self):
+ """Starts a graceful stop of the crawler and returns a deferred that is
+ fired when the crawler is stopped."""
if self.crawling:
self.crawling = False
yield defer.maybeDeferred(self.engine... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/crawler.py |
Document this code for team use | import hashlib
import logging
from collections import namedtuple
from queuelib import PriorityQueue
from scrapy.utils.reqser import request_to_dict, request_from_dict
logger = logging.getLogger(__name__)
def _path_safe(text):
pathable_slot = "".join([c if c.isalnum() or c in '-._' else '_'
... | --- +++ @@ -11,6 +11,16 @@
def _path_safe(text):
+ """
+ Return a filesystem-safe version of a string ``text``
+
+ >>> _path_safe('simple.org').startswith('simple.org')
+ True
+ >>> _path_safe('dash-underscore_.org').startswith('dash-underscore_.org')
+ True
+ >>> _path_safe('some@symbol?').sta... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/pqueues.py |
Document helper functions with docstrings | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from collections import defaultdict
import traceback
import warnings
from zope.interface import implementer
from scrapy.interfaces import ISpiderLoader
from scrapy.utils.misc import walk_modules
from scrapy.utils.spider import iter_spider_classes
@imple... | --- +++ @@ -13,6 +13,10 @@
@implementer(ISpiderLoader)
class SpiderLoader(object):
+ """
+ SpiderLoader is a class which locates and loads spiders
+ in a Scrapy project.
+ """
def __init__(self, settings):
self.spider_modules = settings.getlist('SPIDER_MODULES')
self.warn_only = se... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/spiderloader.py |
Document this script properly |
from __future__ import print_function
import weakref
from time import time
from operator import itemgetter
from collections import defaultdict
import six
NoneType = type(None)
live_refs = defaultdict(weakref.WeakKeyDictionary)
class object_ref(object):
__slots__ = ()
def __new__(cls, *args, **kwargs):
... | --- +++ @@ -1,3 +1,13 @@+"""This module provides some functions and classes to record and report
+references to live object instances.
+
+If you want live objects for a particular class to be tracked, you only have to
+subclass from object_ref (instead of object).
+
+About performance: This library has a minimal perfor... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/trackref.py |
Write beginner-friendly docstrings | import logging
import warnings
from scrapy import signals
from scrapy.http import Request
from scrapy.utils.trackref import object_ref
from scrapy.utils.url import url_is_from_spider
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils.deprecate import method_is_overridden
class Spider(object_ref... | --- +++ @@ -1,3 +1,8 @@+"""
+Base class for Scrapy spiders
+
+See documentation in docs/topics/spiders.rst
+"""
import logging
import warnings
@@ -10,6 +15,9 @@
class Spider(object_ref):
+ """Base class for scrapy spiders. All spiders must inherit from this
+ class.
+ """
name = None
custom... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/spiders/__init__.py |
Document helper functions with docstrings | import os
import weakref
import webbrowser
import tempfile
from twisted.web import http
from scrapy.utils.python import to_bytes, to_native_str
from w3lib import html
_baseurl_cache = weakref.WeakKeyDictionary()
def get_base_url(response):
if response not in _baseurl_cache:
text = response.text[0:4096]
... | --- +++ @@ -1,3 +1,7 @@+"""
+This module provides some useful functions for working with
+scrapy.http.Response objects
+"""
import os
import weakref
import webbrowser
@@ -10,6 +14,7 @@
_baseurl_cache = weakref.WeakKeyDictionary()
def get_base_url(response):
+ """Return the base url of the given response, joine... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/response.py |
Add docstrings that explain inputs and outputs | import six
from scrapy.http import Request
from scrapy.utils.python import to_unicode, to_native_str
from scrapy.utils.misc import load_object
def request_to_dict(request, spider=None):
cb = request.callback
if callable(cb):
cb = _find_method(spider, cb)
eb = request.errback
if callable(eb):
... | --- +++ @@ -1,3 +1,6 @@+"""
+Helper functions for serializing (and deserializing) requests.
+"""
import six
from scrapy.http import Request
@@ -6,6 +9,11 @@
def request_to_dict(request, spider=None):
+ """Convert Request object to a dict.
+
+ If a spider is given, it will try to find out the name of the s... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/reqser.py |
Write Python docstrings for this snippet | import warnings
from functools import wraps
from twisted.internet import defer, threads
from scrapy.exceptions import ScrapyDeprecationWarning
def deprecated(use_instead=None):
def deco(func):
@wraps(func)
def wrapped(*args, **kwargs):
message = "Call to deprecated function %s." % f... | --- +++ @@ -7,6 +7,9 @@
def deprecated(use_instead=None):
+ """This is a decorator which can be used to mark functions
+ as deprecated. It will result in a warning being emitted
+ when the function is used."""
def deco(func):
@wraps(func)
@@ -25,13 +28,17 @@
def defers(func):
+ """De... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/decorators.py |
Add docstrings including usage examples | import logging
import inspect
import six
from scrapy.spiders import Spider
from scrapy.utils.misc import arg_to_iter
logger = logging.getLogger(__name__)
def iterate_spider_output(result):
return arg_to_iter(result)
def iter_spider_classes(module):
# this needs to be imported here until get rid of the s... | --- +++ @@ -14,6 +14,9 @@
def iter_spider_classes(module):
+ """Return an iterator over all spider classes defined in the given module
+ that can be instantiated (ie. which have name)
+ """
# this needs to be imported here until get rid of the spider manager
# singleton in scrapy.spider.spiders
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/spider.py |
Write docstrings for this repository |
import copy
import collections
import warnings
import six
from scrapy.exceptions import ScrapyDeprecationWarning
if six.PY2:
Mapping = collections.Mapping
else:
Mapping = collections.abc.Mapping
class MultiValueDictKeyError(KeyError):
def __init__(self, *args, **kwargs):
warnings.warn(
... | --- +++ @@ -1,3 +1,9 @@+"""
+This module contains data types used by Scrapy which are not included in the
+Python Standard Library.
+
+This module must not depend on any module outside the Standard Library.
+"""
import copy
import collections
@@ -26,6 +32,22 @@
class MultiValueDict(dict):
+ """
+ A subcla... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/datatypes.py |
Add concise docstrings to each method | from functools import wraps
from collections import OrderedDict
def _embed_ipython_shell(namespace={}, banner=''):
try:
from IPython.terminal.embed import InteractiveShellEmbed
from IPython.terminal.ipapp import load_default_config
except ImportError:
from IPython.frontend.terminal.embe... | --- +++ @@ -2,6 +2,7 @@ from collections import OrderedDict
def _embed_ipython_shell(namespace={}, banner=''):
+ """Start an IPython Shell"""
try:
from IPython.terminal.embed import InteractiveShellEmbed
from IPython.terminal.ipapp import load_default_config
@@ -23,6 +24,7 @@ return wra... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/console.py |
Add docstrings for internal functions | import os
import sys
import numbers
from operator import itemgetter
import six
if six.PY2:
from ConfigParser import SafeConfigParser as ConfigParser
else:
from configparser import ConfigParser
from scrapy.settings import BaseSettings
from scrapy.utils.deprecate import update_classpath
from scrapy.utils.python... | --- +++ @@ -15,6 +15,7 @@
def build_component_list(compdict, custom=None, convert=update_classpath):
+ """Compose a component list from a { class: order } dictionary."""
def _check_components(complist):
if len({convert(c) for c in complist}) != len(complist):
@@ -38,6 +39,7 @@ return ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/conf.py |
Generate missing documentation strings | import posixpath
import re
from six.moves.urllib.parse import (ParseResult, urldefrag, urlparse, urlunparse)
# scrapy.utils.url was moved to w3lib.url and import * ensures this
# move doesn't break old code
from w3lib.url import *
from w3lib.url import _safe_chars, _unquotepath
from scrapy.utils.python import to_unico... | --- +++ @@ -1,3 +1,10 @@+"""
+This module contains general purpose URL functions not found in the standard
+library.
+
+Some of the functions that used to be imported from this module have been moved
+to the w3lib.url module. Always import those from there instead.
+"""
import posixpath
import re
from six.moves.urll... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/url.py |
Generate NumPy-style docstrings | import time
from six.moves.http_cookiejar import (
CookieJar as _CookieJar, DefaultCookiePolicy, IPV4_RE
)
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.python import to_native_str
class CookieJar(object):
def __init__(self, policy=None, check_expired_frequency=10000):
self.policy... | --- +++ @@ -83,6 +83,12 @@
def potential_domain_matches(domain):
+ """Potential domain matches for a cookie
+
+ >>> potential_domain_matches('www.example.com')
+ ['www.example.com', 'example.com', '.www.example.com', '.example.com']
+
+ """
matches = [domain]
try:
start = domain.index... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/http/cookies.py |
Expand my code with proper documentation strings |
import warnings
import inspect
from scrapy.exceptions import ScrapyDeprecationWarning
def attribute(obj, oldattr, newattr, version='0.12'):
cname = obj.__class__.__name__
warnings.warn("%s.%s attribute is deprecated and will be no longer supported "
"in Scrapy %s, use %s.%s attribute instead" % \
... | --- +++ @@ -1,3 +1,4 @@+"""Some helpers for deprecation messages"""
import warnings
import inspect
@@ -21,6 +22,30 @@ "from {new}.",
instance_warn_message="{cls} is deprecated, "\
"instantiate {new} instead."):
+ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/deprecate.py |
Fill in missing docstrings in my code |
from twisted.internet import defer, reactor, task
from twisted.python import failure
from scrapy.exceptions import IgnoreRequest
def defer_fail(_failure):
d = defer.Deferred()
reactor.callLater(0.1, d.errback, _failure)
return d
def defer_succeed(result):
d = defer.Deferred()
reactor.callLater(0... | --- +++ @@ -1,3 +1,6 @@+"""
+Helper functions for dealing with Twisted deferreds
+"""
from twisted.internet import defer, reactor, task
from twisted.python import failure
@@ -5,11 +8,23 @@ from scrapy.exceptions import IgnoreRequest
def defer_fail(_failure):
+ """Same as twisted.internet.defer.fail but delay ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/defer.py |
Annotate my code with docstrings | import gc
import os
import re
import inspect
import weakref
import errno
import six
from functools import partial, wraps
from itertools import chain
import sys
from scrapy.utils.decorators import deprecated
def flatten(x):
return list(iflatten(x))
def iflatten(x):
for el in x:
if is_listlike(el):
... | --- +++ @@ -1,3 +1,6 @@+"""
+This module contains essential stuff that should've come with Python itself ;)
+"""
import gc
import os
import re
@@ -13,10 +16,29 @@
def flatten(x):
+ """flatten(sequence) -> list
+
+ Returns a single, flat list which contains all elements retrieved
+ from the sequence and ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/python.py |
Add clean documentation to messy code |
import warnings
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils.decorators import deprecated
from w3lib.http import *
warnings.warn("Module `scrapy.utils.http` is deprecated, "
"Please import from `w3lib.http` instead.",
ScrapyDeprecationWarning, stacklevel=2)
... | --- +++ @@ -1,3 +1,8 @@+"""
+Transitional module for moving to the w3lib library.
+
+For new code, always import from w3lib.http instead of this module
+"""
import warnings
@@ -13,6 +18,13 @@
@deprecated
def decode_chunked_transfer(chunked_body):
+ """Parsed body received with chunked transfer encoding, and ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/http.py |
Add docstrings to make code maintainable |
from __future__ import print_function
from time import time # used in global tests code
def get_engine_status(engine):
tests = [
"time()-engine.start_time",
"engine.has_capacity()",
"len(engine.downloader.active)",
"engine.scraper.is_idle()",
"engine.spider.name",
"... | --- +++ @@ -1,8 +1,10 @@+"""Some debugging functions for working with the Scrapy engine"""
from __future__ import print_function
from time import time # used in global tests code
def get_engine_status(engine):
+ """Return a report of the current engine status"""
tests = [
"time()-engine.start_ti... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/engine.py |
Generate consistent documentation across files |
from __future__ import absolute_import, division, print_function
import warnings
from cryptography.x509 import (
DNSName,
ExtensionOID,
IPAddress,
NameOID,
ObjectIdentifier,
OtherName,
UniformResourceIdentifier,
)
from cryptography.x509.extensions import ExtensionNotFound
from pyasn1.code... | --- +++ @@ -1,3 +1,6 @@+"""
+`cryptography.x509 <https://github.com/pyca/cryptography>`_-specific code.
+"""
from __future__ import absolute_import, division, print_function
@@ -33,6 +36,25 @@
def verify_certificate_hostname(certificate, hostname):
+ """
+ Verify whether *certificate* is valid for *hostn... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/service_identity/cryptography.py |
Add docstrings for production code |
from __future__ import absolute_import, division, print_function
import warnings
import six
from pyasn1.codec.der.decoder import decode
from pyasn1.type.char import IA5String
from pyasn1.type.univ import ObjectIdentifier
from pyasn1_modules.rfc2459 import GeneralNames
from ._common import (
DNS_ID,
Certifi... | --- +++ @@ -1,3 +1,6 @@+"""
+`pyOpenSSL <https://github.com/pyca/pyopenssl>`_-specific code.
+"""
from __future__ import absolute_import, division, print_function
@@ -27,6 +30,21 @@
def verify_hostname(connection, hostname):
+ """
+ Verify whether the certificate of *connection* is valid for *hostname*.
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/service_identity/pyopenssl.py |
Document this script properly |
import logging
from twisted.internet.defer import maybeDeferred, DeferredList, Deferred
from twisted.python.failure import Failure
from pydispatch.dispatcher import Any, Anonymous, liveReceivers, \
getAllReceivers, disconnect
from pydispatch.robustapply import robustApply
from scrapy.utils.log import failure_to_... | --- +++ @@ -1,3 +1,4 @@+"""Helper functions for working with signals"""
import logging
@@ -17,6 +18,9 @@
def send_catch_log(signal=Any, sender=Anonymous, *arguments, **named):
+ """Like pydispatcher.robust.sendRobust but it also logs errors and returns
+ Failures instead of exceptions.
+ """
dont... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/signal.py |
Add docstrings for production code | from twisted.internet import reactor, error
def listen_tcp(portrange, host, factory):
assert len(portrange) <= 2, "invalid portrange: %s" % portrange
if not hasattr(portrange, '__iter__'):
return reactor.listenTCP(portrange, factory, interface=host)
if not portrange:
return reactor.listenTC... | --- +++ @@ -1,6 +1,7 @@ from twisted.internet import reactor, error
def listen_tcp(portrange, host, factory):
+ """Like reactor.listenTCP but tries different ports in a range."""
assert len(portrange) <= 2, "invalid portrange: %s" % portrange
if not hasattr(portrange, '__iter__'):
return reacto... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/reactor.py |
Add detailed documentation for each class | import os
import re
import hashlib
from contextlib import contextmanager
from importlib import import_module
from pkgutil import iter_modules
import six
from w3lib.html import replace_entities
from scrapy.utils.python import flatten, to_unicode
from scrapy.item import BaseItem
_ITERABLE_SINGLE_VALUES = dict, BaseIt... | --- +++ @@ -1,3 +1,4 @@+"""Helper functions which don't fit anywhere else"""
import os
import re
import hashlib
@@ -16,6 +17,11 @@
def arg_to_iter(arg):
+ """Convert an argument to an iterable. The argument can be a None, single
+ value, or an iterable.
+
+ Exception: if arg is a dict, [arg] will be ret... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/misc.py |
Add concise docstrings to each method | # -*- test-case-name: twisted._threads.test.test_team -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division, print_function
from collections import deque
from zope.interface import implementer
from . import IWorker
from ._convenience import Quit... | --- +++ @@ -2,6 +2,10 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Implementation of a L{Team} of workers; a thread-pool that can allocate work to
+workers.
+"""
from __future__ import absolute_import, division, print_function
@@ -14,6 +18,20 @@
class Statistics(object):
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/_threads/_team.py |
Write clean docstrings for readability | import os
from six.moves import cPickle as pickle
import warnings
from importlib import import_module
from os.path import join, dirname, abspath, isabs, exists
from scrapy.utils.conf import closest_scrapy_cfg, get_config, init_env
from scrapy.settings import Settings
from scrapy.exceptions import NotConfigured
ENVVA... | --- +++ @@ -26,6 +26,7 @@
def project_data_dir(project='default'):
+ """Return the current project data dir, creating it if it doesn't exist"""
if not inside_project():
raise NotConfigured("Not inside a project")
cfg = get_config()
@@ -42,6 +43,10 @@
def data_path(path, createdir=False):
+... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/project.py |
Provide docstrings following PEP 257 |
import lxml.etree
from six.moves.urllib.parse import urljoin
class Sitemap(object):
def __init__(self, xmltext):
xmlp = lxml.etree.XMLParser(recover=True, remove_comments=True, resolve_entities=False)
self._root = lxml.etree.fromstring(xmltext, parser=xmlp)
rt = self._root.tag
se... | --- +++ @@ -1,9 +1,17 @@+"""
+Module for processing Sitemaps.
+
+Note: The main purpose of this module is to provide support for the
+SitemapSpider, its API is subject to change without notice.
+"""
import lxml.etree
from six.moves.urllib.parse import urljoin
class Sitemap(object):
+ """Class to parse Sitem... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/sitemap.py |
Write docstrings for data processing functions |
from __future__ import absolute_import, division, print_function
import attr
class SubjectAltNameWarning(DeprecationWarning):
@attr.s
class VerificationError(Exception):
errors = attr.ib()
def __str__(self):
return self.__repr__()
@attr.s
class DNSMismatch(object):
mismatched_id = attr.ib... | --- +++ @@ -1,3 +1,9 @@+"""
+All exceptions and warnings thrown by ``service_identity``.
+
+Separated into an own package for nicer tracebacks, you should still import
+them from __init__.py.
+"""
from __future__ import absolute_import, division, print_function
@@ -5,10 +11,18 @@
class SubjectAltNameWarning(De... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/service_identity/exceptions.py |
Document all endpoints with docstrings | from scrapy.utils.misc import load_object
from scrapy.utils.serialize import ScrapyJSONEncoder
from twisted.internet.threads import deferToThread
from . import connection, defaults
default_serialize = ScrapyJSONEncoder().encode
class RedisPipeline(object):
def __init__(self, server,
key=defau... | --- +++ @@ -9,10 +9,32 @@
class RedisPipeline(object):
+ """Pushes serialized item into a redis list/queue
+
+ Settings
+ --------
+ REDIS_ITEMS_KEY : str
+ Redis key where to store items.
+ REDIS_ITEMS_SERIALIZER : str
+ Object path to serializer function.
+
+ """
def __init_... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy_redis/pipelines.py |
Add clean documentation to messy code | import logging
import time
from scrapy.dupefilters import BaseDupeFilter
from scrapy.utils.request import request_fingerprint
from . import defaults
from .connection import get_redis_from_settings
logger = logging.getLogger(__name__)
# TODO: Rename class to RedisDupeFilter.
class RFPDupeFilter(BaseDupeFilter):
... | --- +++ @@ -13,10 +13,27 @@
# TODO: Rename class to RedisDupeFilter.
class RFPDupeFilter(BaseDupeFilter):
+ """Redis-based request duplicates filter.
+
+ This class can also be used with default Scrapy's scheduler.
+
+ """
logger = logger
def __init__(self, server, key, debug=False):
+ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy_redis/dupefilter.py |
Write docstrings that follow conventions | # -*- test-case-name: twisted.test.test_application,twisted.test.test_twistd -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division, print_function
import sys
import os
import pdb
import getpass
import traceback
import signal
import warnings
from ... | --- +++ @@ -29,6 +29,14 @@
class _BasicProfiler(object):
+ """
+ @ivar saveStats: if C{True}, save the stats information instead of the
+ human readable format
+ @type saveStats: C{bool}
+
+ @ivar profileOutput: the name of the file use to print profile data.
+ @type profileOutput: C{str}
+ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/app.py |
Generate docstrings for each module | # -*- test-case-name: twisted.application.test.test_internet,twisted.test.test_application,twisted.test.test_cooperator -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division
from random import random as _goodEnoughRandom
from twisted.python impo... | --- +++ @@ -2,6 +2,40 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Reactor-based Services
+
+Here are services to run clients, servers and periodic services using
+the reactor.
+
+If you want to run a server service, L{StreamServerEndpointService} defines a
+service that can wrap ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/internet.py |
Add concise docstrings to each method |
import os
import re
import string
def render_templatefile(path, **kwargs):
with open(path, 'rb') as fp:
raw = fp.read().decode('utf8')
content = string.Template(raw).substitute(**kwargs)
render_path = path[:-len('.tmpl')] if path.endswith('.tmpl') else path
with open(render_path, 'wb') as f... | --- +++ @@ -1,3 +1,4 @@+"""Helper functions for working with templates"""
import os
import re
@@ -19,4 +20,13 @@
CAMELCASE_INVALID_CHARS = re.compile(r'[^a-zA-Z\d]')
def string_camelcase(string):
- return CAMELCASE_INVALID_CHARS.sub('', string.title())+ """ Convert a word to its CamelCase version and remo... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy/utils/template.py |
Add professional docstrings to my codebase | # -*- test-case-name: twisted.test.test_application -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division
from zope.interface import Interface, Attribute, implementer
from twisted.plugin import IPlugin, getPlugins
from twisted.python.reflect imp... | --- +++ @@ -2,6 +2,10 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Plugin-based system for enumerating available reactors and installing one of
+them.
+"""
from __future__ import absolute_import, division
@@ -12,6 +16,9 @@
class IReactorInstaller(Interface):
+ """
+ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/reactors.py |
Create docstrings for all classes and functions | import six
from scrapy.utils.misc import load_object
from . import defaults
# Shortcut maps 'setting name' -> 'parmater name'.
SETTINGS_PARAMS_MAP = {
'REDIS_URL': 'url',
'REDIS_HOST': 'host',
'REDIS_PORT': 'port',
'REDIS_ENCODING': 'encoding',
}
def get_redis_from_settings(settings):
params =... | --- +++ @@ -15,6 +15,36 @@
def get_redis_from_settings(settings):
+ """Returns a redis client instance from given Scrapy settings object.
+
+ This function uses ``get_client`` to instantiate the client and uses
+ ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You
+ can override ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy_redis/connection.py |
Improve my code by adding docstrings |
from __future__ import absolute_import, division, print_function
import ipaddress
import re
import attr
from ._compat import maketrans, text_type
from .exceptions import (
CertificateError,
DNSMismatch,
IPAddressMismatch,
SRVMismatch,
URIMismatch,
VerificationError,
)
try:
import idna
... | --- +++ @@ -1,3 +1,6 @@+"""
+Common verification code.
+"""
from __future__ import absolute_import, division, print_function
@@ -25,12 +28,22 @@
@attr.s(slots=True)
class ServiceMatch(object):
+ """
+ A match of a service id and a certificate pattern.
+ """
service_id = attr.ib()
cert_patte... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/service_identity/_common.py |
Create structured documentation for my script | # -*- test-case-name: twisted.test.test_strports -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division
from twisted.application.internet import StreamServerEndpointService
from twisted.internet import endpoints
def service(description, factory,... | --- +++ @@ -2,6 +2,12 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Construct listening port services from a simple string description.
+
+@see: L{twisted.internet.endpoints.serverFromString}
+@see: L{twisted.internet.endpoints.clientFromString}
+"""
from __future__ import absol... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/strports.py |
Add detailed documentation for each class | # -*- test-case-name: twisted._threads.test.test_convenience -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division, print_function
from ._ithreads import AlreadyQuit
class Quit(object):
def __init__(self):
self.isSet = False
... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Common functionality used within the implementation of various workers.
+"""
from __future__ import absolute_import, division, print_function
@@ -9,16 +12,35 @@
class Quit(object):
+ """
+ A flag repr... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/_threads/_convenience.py |
Add docstrings that explain purpose and usage | # -*- test-case-name: twisted._threads.test.test_threadworker -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division, print_function
from zope.interface import implementer
from ._ithreads import IExclusiveWorker
from ._convenience import Quit
_s... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Implementation of an L{IWorker} based on native threads and queues.
+"""
from __future__ import absolute_import, division, print_function
@@ -14,8 +17,28 @@
@implementer(IExclusiveWorker)
class ThreadWorker(... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/_threads/_threadworker.py |
Add docstrings with type hints explained | # -*- test-case-name: twisted._threads.test.test_memory -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division, print_function
from zope.interface import implementer
from . import IWorker
from ._convenience import Quit
NoMoreWork = object()
@im... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Implementation of an in-memory worker that defers execution.
+"""
from __future__ import absolute_import, division, print_function
@@ -14,24 +17,49 @@
@implementer(IWorker)
class MemoryWorker(object):
+ "... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/_threads/_memory.py |
Add docstrings that explain purpose and usage | from scrapy.utils.reqser import request_to_dict, request_from_dict
from . import picklecompat
class Base(object):
def __init__(self, server, spider, key, serializer=None):
if serializer is None:
# Backward compatibility.
# TODO: deprecate pickle.
serializer = pickleco... | --- +++ @@ -4,8 +4,23 @@
class Base(object):
+ """Per-spider base queue class"""
def __init__(self, server, spider, key, serializer=None):
+ """Initialize per-spider redis queue.
+
+ Parameters
+ ----------
+ server : StrictRedis
+ Redis client instance.
+ spi... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy_redis/queue.py |
Fill in missing docstrings in my code | # -*- test-case-name: twisted.application.runner.test.test_pidfile -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
import errno
from os import getpid, kill, name as SYSTEM_NAME
from zope.interface import Interface, implementer
from twisted.logger import Logger
class IPIDFile(Interface... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+PID file.
+"""
import errno
from os import getpid, kill, name as SYSTEM_NAME
@@ -13,38 +16,107 @@
class IPIDFile(Interface):
+ """
+ Manages a file that remembers a process ID.
+ """
def read... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/runner/_pidfile.py |
Write docstrings that follow conventions | # -*- test-case-name: twisted.conch.test.test_knownhosts,twisted.conch.test.test_default -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import print_function
from twisted.python import log
from twisted.python.compat import (
nativeString, raw_input, _PY3, _b64decodeby... | --- +++ @@ -2,6 +2,14 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Various classes and functions for implementing user-interaction in the
+command-line conch client.
+
+You probably shouldn't use anything in this module directly, since it assumes
+you are sitting at an interactive... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/client/default.py |
Include argument descriptions in docstrings | # -*- test-case-name: twisted.application.runner.test.test_exit -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from sys import stdout, stderr, exit as sysexit
from constantly import Values, ValueConstant
def exit(status, message=None):
if isinstance(status, ValueConstant):
... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+System exit support.
+"""
from sys import stdout, stderr, exit as sysexit
@@ -10,6 +13,15 @@
def exit(status, message=None):
+ """
+ Exit the python interpreter with the given status and an optional m... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/runner/_exit.py |
Write docstrings describing functionality | # -*- test-case-name: twisted._threads.test -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division, print_function
from threading import Thread, Lock, local as LocalStorage
try:
from Queue import Queue
except ImportError:
from queue import... | --- +++ @@ -2,6 +2,10 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Top level thread pool interface, used to implement
+L{twisted.python.threadpool}.
+"""
from __future__ import absolute_import, division, print_function
@@ -19,6 +23,33 @@
def pool(currentLimit, threadFacto... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/_threads/_pool.py |
Create docstrings for reusable components | import importlib
import six
from scrapy.utils.misc import load_object
from . import connection, defaults
# TODO: add SCRAPY_JOB support.
class Scheduler(object):
def __init__(self, server,
persist=False,
flush_on_start=False,
queue_key=defaults.SCHEDULER_QUEUE... | --- +++ @@ -8,6 +8,28 @@
# TODO: add SCRAPY_JOB support.
class Scheduler(object):
+ """Redis-based scheduler
+
+ Settings
+ --------
+ SCHEDULER_PERSIST : bool (default: False)
+ Whether to persist or clear redis queue.
+ SCHEDULER_FLUSH_ON_START : bool (default: False)
+ Whether to flus... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy_redis/scheduler.py |
Add docstrings including usage examples | # -*- test-case-name: twisted.application.twist.test.test_twist -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
import sys
from twisted.python.usage import UsageError
from ..service import Application, IService
from ..runner._exit import exit, ExitStatus
from ..runner._runner import Runne... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Run a Twisted application.
+"""
import sys
@@ -16,9 +19,21 @@
class Twist(object):
+ """
+ Run a Twisted application.
+ """
@staticmethod
def options(argv):
+ """
+ Parse ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/twist/_twist.py |
Help me document legacy Python code | # -*- test-case-name: twisted.application.twist.test.test_options -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from sys import stdout, stderr
from textwrap import dedent
from twisted.copyright import version
from twisted.python.usage import Options, UsageError
from twisted.logger impor... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Command line options for C{twist}.
+"""
from sys import stdout, stderr
from textwrap import dedent
@@ -23,6 +26,9 @@
class TwistOptions(Options):
+ """
+ Command line options for C{twist}.
+ """
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/twist/_options.py |
Help me comply with documentation standards | # -*- test-case-name: twisted.conch.test.test_default -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
import os
from twisted.conch.ssh import agent, channel, keys
from twisted.internet import protocol, reactor
from twisted.python import log
class SSHAgentClient(agent.SSHAgentClient):
... | --- +++ @@ -2,6 +2,11 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Accesses the key agent for user authentication.
+
+Maintainer: Paul Swartz
+"""
import os
@@ -28,6 +33,10 @@
def getPublicKey(self):
+ """
+ Return a L{Key} from the first blob in C{self.... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/client/agent.py |
Add docstrings that explain logic | # -*- test-case-name: twisted.application.test.test_service -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division
from zope.interface import implementer, Interface, Attribute
from twisted.persisted import sob
from twisted.python.reflect import n... | --- +++ @@ -2,6 +2,17 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Service architecture for Twisted.
+
+Services are arranged in a hierarchy. At the leafs of the hierarchy,
+the services which actually interact with the outside world are started.
+Services can be named or anonymou... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/service.py |
Expand my code with proper documentation strings | # -*- test-case-name: twisted._threads.test -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division, print_function
from zope.interface import Interface
class AlreadyQuit(Exception):
class IWorker(Interface):
def do(task):
def quit()... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Interfaces related to threads.
+"""
from __future__ import absolute_import, division, print_function
@@ -9,14 +12,50 @@
class AlreadyQuit(Exception):
+ """
+ This worker worker is dead and cannot exec... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/_threads/_ithreads.py |
Document my Python code with docstrings | from scrapy import signals
from scrapy.exceptions import DontCloseSpider
from scrapy.spiders import Spider, CrawlSpider
from . import connection, defaults
from .utils import bytes_to_str
class RedisMixin(object):
redis_key = None
redis_batch_size = None
redis_encoding = None
# Redis client placehold... | --- +++ @@ -7,6 +7,7 @@
class RedisMixin(object):
+ """Mixin class to implement reading urls from a redis queue."""
redis_key = None
redis_batch_size = None
redis_encoding = None
@@ -15,9 +16,14 @@ server = None
def start_requests(self):
+ """Returns a batch of start requests fro... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/scrapy_redis/spiders.py |
Add docstrings that explain logic | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
#
from twisted.conch.ssh.transport import SSHClientTransport, SSHCiphers
from twisted.python import usage
from twisted.python.compat import unicode
import sys
class ConchOptions(usage.Options):
optParameters = [['user', 'l', None, 'Log in u... | --- +++ @@ -59,9 +59,11 @@ self.conns = None
def opt_identity(self, i):
+ """Identity for public-key authentication"""
self.identitys.append(i)
def opt_ciphers(self, ciphers):
+ "Select encryption algorithms"
ciphers = ciphers.split(',')
for cipher in ciphe... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/client/options.py |
Generate docstrings for each module | # -*- test-case-name: twisted.conch.test.test_recvline -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
import string
from zope.interface import implementer
from twisted.conch.insults import insults, helper
from twisted.python import log, reflect
from twisted.python.compat import iterbyt... | --- +++ @@ -2,6 +2,11 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Basic line editing support.
+
+@author: Jp Calderone
+"""
import string
@@ -14,6 +19,13 @@
_counters = {}
class Logging(object):
+ """
+ Wrapper which logs attribute lookups.
+
+ This was useful in... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/recvline.py |
Add structured docstrings to improve clarity | # -*- test-case-name: twisted.application.runner.test.test_runner -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from sys import stderr
from signal import SIGTERM
from os import kill
from attr import attrib, attrs, Factory
from twisted.logger import (
globalLogBeginner, textFileLogO... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Twisted application runner.
+"""
from sys import stderr
from signal import SIGTERM
@@ -22,6 +25,52 @@
@attrs(frozen=True)
class Runner(object):
+ """
+ Twisted application runner.
+
+ @cvar _log: The... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/application/runner/_runner.py |
Create structured documentation for my script | # -*- test-case-name: twisted.conch.test.test_conch -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
#
# $Id: conch.py,v 1.65 2004/03/11 00:29:14 z3p Exp $
#""" Implementation module for the `conch` command.
#"""
from __future__ import print_function
from twisted.conch.client import conn... | --- +++ @@ -62,6 +62,9 @@ remoteForwards = []
def opt_escape(self, esc):
+ """
+ Set escape character; ``none'' = disable
+ """
if esc == 'none':
self['escape'] = None
elif esc[0] == '^' and len(esc) == 2:
@@ -73,6 +76,9 @@
def opt_localforward(self... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/scripts/conch.py |
Add docstrings for production code | # -*- test-case-name: twisted.conch.test.test_endpoints -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
__all__ = [
'AuthenticationFailed', 'SSHCommandAddress', 'SSHCommandClientEndpoint']
from struct import unpack
from os.path import expanduser
import signal
from zope.interface imp... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Endpoint implementations of various SSH interactions.
+"""
__all__ = [
'AuthenticationFailed', 'SSHCommandAddress', 'SSHCommandClientEndpoint']
@@ -35,20 +38,68 @@
class AuthenticationFailed(Exception):
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/endpoints.py |
Write Python docstrings for this snippet | # -*- test-case-name: twisted.conch.test.test_insults -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from zope.interface import implementer, Interface
from twisted.internet import protocol, defer, interfaces as iinternet
from twisted.python.compat import intToBytes, iterbytes, networkStr... | --- +++ @@ -2,6 +2,11 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+VT102 and VT220 terminal manipulation.
+
+@author: Jp Calderone
+"""
from zope.interface import implementer, Interface
@@ -12,14 +17,43 @@
class ITerminalProtocol(Interface):
def makeConnection(transpor... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/insults/insults.py |
Add docstrings to my Python code | # -*- test-case-name: twisted.conch.test.test_checkers -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division
import sys
import binascii
import errno
try:
import pwd
except ImportError:
pwd = None
else:
import crypt
try:
import s... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Provide L{ICredentialsChecker} implementations to be used in Conch protocols.
+"""
from __future__ import absolute_import, division
@@ -41,11 +44,29 @@
def verifyCryptedPassword(crypted, pw):
+ """
+ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/checkers.py |
Create docstrings for all classes and functions | # -*- test-case-name: twisted.conch.test.test_knownhosts -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division
import hmac
from binascii import Error as DecodeError, b2a_base64, a2b_base64
from contextlib import closing
from hashlib import sha1
i... | --- +++ @@ -2,6 +2,11 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+An implementation of the OpenSSH known_hosts database.
+
+@since: 8.2
+"""
from __future__ import absolute_import, division
@@ -24,11 +29,32 @@
def _b64encode(s):
+ """
+ Encode a binary string as ba... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/client/knownhosts.py |
Create structured documentation for my script | # -*- test-case-name: twisted.conch.test.test_cftp -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import division, print_function
import os, sys, getpass, struct, tty, fcntl, stat
import fnmatch, pwd, glob
from twisted.conch.client import connect, default, options
from twi... | --- +++ @@ -2,6 +2,9 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Implementation module for the I{cftp} command.
+"""
from __future__ import division, print_function
import os, sys, getpass, struct, tty, fcntl, stat
import fnmatch, pwd, glob
@@ -410,6 +413,15 @@
def cmd... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/scripts/cftp.py |
Add docstrings for utility scripts | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division
import struct
from twisted.conch.ssh.common import NS, getNS, getMP
from twisted.conch.error import ConchError, MissingKeyStoreError
from twisted.conch.ssh import keys
from twisted.internet impor... | --- +++ @@ -1,6 +1,13 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Implements the SSH v2 key agent protocol. This protocol is documented in the
+SSH source code, in the file
+U{PROTOCOL.agent<http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent>}.
+
+Maintainer: P... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/ssh/agent.py |
Add return value explanations in docstrings | # -*- test-case-name: twisted.conch.test.test_window -*-
import array
from twisted.conch.insults import insults, helper
from twisted.python import text as tptext
from twisted.python.compat import (_PY3, _bytesChr as chr)
class YieldFocus(Exception):
class BoundedTerminalWrapper(object):
def __init__(self, te... | --- +++ @@ -1,5 +1,10 @@ # -*- test-case-name: twisted.conch.test.test_window -*-
+"""
+Simple insults-based widget library
+
+@author: Jp Calderone
+"""
import array
@@ -8,6 +13,9 @@ from twisted.python.compat import (_PY3, _bytesChr as chr)
class YieldFocus(Exception):
+ """
+ Input focus manipulation... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/insults/window.py |
Add docstrings to clarify complex logic | # -*- test-case-name: twisted.conch.test.test_helper -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import print_function
import re, string
from zope.interface import implementer
from incremental import Version
from twisted.internet import defer, protocol, reactor
from... | --- +++ @@ -2,6 +2,11 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Partial in-memory terminal emulator
+
+@author: Jp Calderone
+"""
from __future__ import print_function
@@ -24,6 +29,13 @@
class _FormattingState(_textattributes._FormattingStateMixin):
+ """
+ Repre... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/insults/helper.py |
Generate docstrings for exported functions | # -*- test-case-name: twisted.conch.test.test_mixin -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet import reactor
class BufferingMixin:
_delayedWriteCall = None
data = None
DELAY = 0.0
def schedule(self):
return reactor.callLater(self.DELAY... | --- +++ @@ -2,10 +2,21 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Experimental optimization
+
+This module provides a single mixin class which allows protocols to
+collapse numerous small writes into a single larger one.
+
+@author: Jp Calderone
+"""
from twisted.internet imp... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/mixin.py |
Help me add docstrings to my project | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from zope.interface import Interface, Attribute
class IConchUser(Interface):
conn = Attribute('The SSHConnection object for this user.')
def lookupChannel(channelType, windowSize, maxPacket, data):
def lookupSubsystem(subsystem, d... | --- +++ @@ -1,38 +1,125 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+This module contains interfaces defined for the L{twisted.conch} package.
+"""
from zope.interface import Interface, Attribute
class IConchUser(Interface):
+ """
+ A user who has been authenticated to... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/interfaces.py |
Document all endpoints with docstrings | # -*- test-case-name: twisted.conch.test.test_ssh -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import absolute_import, division
import struct
from cryptography.utils import int_from_bytes, int_to_bytes
from twisted.python.compat import unicode
from twisted.python.depr... | --- +++ @@ -2,6 +2,11 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Common functions for the SSH classes.
+
+Maintainer: Paul Swartz
+"""
from __future__ import absolute_import, division
@@ -18,6 +23,9 @@
def NS(t):
+ """
+ net string
+ """
if isinstance(t, u... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/ssh/common.py |
Expand my code with proper documentation strings | # -*- test-case-name: twisted.conch.test.test_text -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from incremental import Version
from twisted.conch.insults import helper, insults
from twisted.python import _textattributes
from twisted.python.deprecate import deprecatedModuleAttribute
... | --- +++ @@ -2,6 +2,59 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Character attribute manipulation API.
+
+This module provides a domain-specific language (using Python syntax)
+for the creation of text with additional display attributes associated
+with it. It is intended as an... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/insults/text.py |
Generate consistent documentation across files | # -*- test-case-name: twisted.conch.test.test_manhole -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from zope.interface import implementer
from twisted.conch import avatar, interfaces as iconch, error as econch
from twisted.conch.ssh import factory, session
from twisted.python import co... | --- +++ @@ -2,6 +2,11 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+insults/SSH integration support.
+
+@author: Jp Calderone
+"""
from zope.interface import implementer
@@ -13,6 +18,12 @@
class _Glue:
+ """
+ A feeble class for making one attribute look like another... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/manhole_ssh.py |
Add docstrings explaining edge cases | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import division, absolute_import
from twisted.internet import protocol
from twisted.python import log
from twisted.conch import error
from twisted.conch.ssh import (_kex, transport, userauth, connection)
import random
class S... | --- +++ @@ -1,6 +1,13 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+A Factory for SSH servers.
+
+See also L{twisted.conch.openssh_compat.factory} for OpenSSH compatibility.
+
+Maintainer: Paul Swartz
+"""
from __future__ import division, absolute_import
@@ -14,6 +21,9 @@
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/ssh/factory.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.