Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updates to satisfy pep257 violations #2028

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 2 additions & 3 deletions .github/workflows/ci-cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,6 @@ jobs:
# - linkcheck-docs
# - metadata-validation
- pre-commit
- pre-commit-pep257
- setup-check
# - spellcheck-docs
fail-fast: false
Expand All @@ -574,7 +573,7 @@ jobs:
- name: Grab the source from Git
if: >-
contains(
fromJSON('["pre-commit", "pre-commit-pep257", "spellcheck-docs"]'),
fromJSON('["pre-commit", "spellcheck-docs"]'),
matrix.toxenv
)
uses: actions/checkout@v3
Expand All @@ -583,7 +582,7 @@ jobs:
- name: Retrieve the project source from an sdist inside the GHA artifact
if: >-
!contains(
fromJSON('["pre-commit", "pre-commit-pep257", "spellcheck-docs"]'),
fromJSON('["pre-commit", "spellcheck-docs"]'),
matrix.toxenv
)
uses: re-actors/checkout-python-sdist@release/v1
Expand Down
9 changes: 0 additions & 9 deletions .pre-commit-config-pep257.yaml

This file was deleted.

17 changes: 0 additions & 17 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,23 +39,6 @@ repos:
rev: 6.3.0
hooks:
- id: pydocstyle
exclude: |
(?x)
tests/dist|
cherrypy/(
_cp(
compat|modpy|logging|error|wsgi|dispatch|tools|reqbody|request
)|
(
lib/(
auth|auth_basic|auth_digest|caching|covercp|
cpstats|cptools|encoding|gctools|httpauth|httputil|
jsontools|lockfile|locking|profiler|reprconf|sessions
)|
process/(plugins|servers|win32)
).py|
test|tutorial
)

- repo: https://github.com/Lucas-C/pre-commit-hooks.git
rev: v1.5.4
Expand Down
9 changes: 3 additions & 6 deletions cherrypy/_cpcompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,14 @@


def ntob(n, encoding='ISO-8859-1'):
"""Return the given native string as a byte string in the given
encoding.
"""
"""Return given native string as a byte str in the given encoding."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
assert_native(n)
# In Python 3, the native string type is unicode
return n.encode(encoding)


def ntou(n, encoding='ISO-8859-1'):
"""Return the given native string as a unicode string with the given
encoding.
"""
"""Return given native string as a unicode str in the given encoding."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
assert_native(n)
# In Python 3, the native string type is unicode
return n
Expand All @@ -48,6 +44,7 @@ def tonative(n, encoding='ISO-8859-1'):


def assert_native(n):
"""Assert if native string."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
if not isinstance(n, str):
raise TypeError('n must be a native str (got %s)' % type(n).__name__)

Expand Down
21 changes: 17 additions & 4 deletions cherrypy/_cpdispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class PageHandler(object):
"""Callable which sets response.body."""

def __init__(self, callable, *args, **kwargs):
"""Initialize PageHandler."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
self.callable = callable
self.args = args
self.kwargs = kwargs
Expand All @@ -36,6 +37,7 @@ def args(self):

@args.setter
def args(self, args):
"""Setter for ordered args."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
cherrypy.serving.request.args = args
return cherrypy.serving.request.args

Expand All @@ -46,10 +48,12 @@ def kwargs(self):

@kwargs.setter
def kwargs(self, kwargs):
"""Setter for named kwargs."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
cherrypy.serving.request.kwargs = kwargs
return cherrypy.serving.request.kwargs

def __call__(self):
"""Call handler for PageHandler."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
try:
return self.callable(*self.args, **self.kwargs)
except TypeError:
Expand Down Expand Up @@ -203,15 +207,18 @@ def test_callable_spec(callable, callable_args, callable_kwargs):
import inspect
except ImportError:
def test_callable_spec(callable, args, kwargs): # noqa: F811
"""Test callable spec."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
return None
else:
def getargspec(callable):
"""Get arg spec."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
return inspect.getfullargspec(callable)[:4]


class LateParamPageHandler(PageHandler):
"""LateParamPageHandler PageHandler class.
webknjaz marked this conversation as resolved.
Show resolved Hide resolved

"""When passing cherrypy.request.params to the page handler, we do not
When passing cherrypy.request.params to the page handler, we do not
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
want to capture that dict too early; we want to give tools like the
decoding tool a chance to modify the params dict in-between the lookup
of the handler and the actual calling of the handler. This subclass
Expand All @@ -221,14 +228,15 @@ class LateParamPageHandler(PageHandler):

@property
def kwargs(self):
"""Page handler kwargs (with cherrypy.request.params copied in)."""
"""Page handler kwargs with cherrypy.request.params copied in."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
kwargs = cherrypy.serving.request.params.copy()
if self._kwargs:
kwargs.update(self._kwargs)
return kwargs

@kwargs.setter
def kwargs(self, kwargs):
"""Setter for kwargs."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
cherrypy.serving.request.kwargs = kwargs
self._kwargs = kwargs

Expand All @@ -238,6 +246,7 @@ def kwargs(self, kwargs):
string.punctuation, '_' * len(string.punctuation))

def validate_translator(t):
"""Validate translator."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
if not isinstance(t, str) or len(t) != 256:
raise ValueError(
'The translate argument must be a str of len 256.')
Expand All @@ -246,6 +255,7 @@ def validate_translator(t):
string.punctuation, '_' * len(string.punctuation))

def validate_translator(t):
"""Validate translator."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
if not isinstance(t, dict):
raise ValueError('The translate argument must be a dict.')

Expand Down Expand Up @@ -273,6 +283,7 @@ class Dispatcher(object):

def __init__(self, dispatch_method_name=None,
translate=punctuation_to_underscores):
"""Initialize Dispatcher."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
validate_translator(translate)
self.translate = translate
if dispatch_method_name:
Expand Down Expand Up @@ -389,8 +400,7 @@ def find_handler(self, path):
object_trail.append([name, node, nodeconf, segleft])

def set_conf():
"""Collapse all object_trail config into cherrypy.request.config.
"""
"""Collapse all object_trail conf into cherrypy.request.config."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
base = cherrypy.config.copy()
# Note that we merge the config from each node
# even if that node was None.
Expand Down Expand Up @@ -505,10 +515,12 @@ def __init__(self, full_result=False, **mapper_options):
self.mapper.controller_scan = self.controllers.keys

def connect(self, name, route, controller, **kwargs):
"""Connect."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
self.controllers[name] = controller
self.mapper.connect(name, route, controller=name, **kwargs)

def redirect(self, url):
"""Redirect."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
raise cherrypy.HTTPRedirect(url)

def __call__(self, path_info):
Expand Down Expand Up @@ -602,6 +614,7 @@ def merge(nodeconf):


def XMLRPCDispatcher(next_dispatcher=Dispatcher()):
"""Xml RPC Dispatcher class."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
from cherrypy.lib import xmlrpcutil

def xmlrpc_dispatch(path_info):
Expand Down
19 changes: 13 additions & 6 deletions cherrypy/_cperror.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ class Root:

class CherryPyException(Exception):
"""A base class for CherryPy exceptions."""

pass
webknjaz marked this conversation as resolved.
Show resolved Hide resolved


Expand All @@ -150,6 +151,7 @@ class InternalRedirect(CherryPyException):
"""

def __init__(self, path, query_string=''):
"""Initialize InternalRedirect."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
self.request = cherrypy.serving.request

self.query_string = query_string
Expand Down Expand Up @@ -202,6 +204,7 @@ class HTTPRedirect(CherryPyException):
"""The encoding when passed urls are not native strings."""

def __init__(self, urls, status=None, encoding=None):
"""Initialize HTTPRedirect."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
self.urls = abs_urls = [
# Note that urljoin will "do the right thing" whether url is:
# 1. a complete URL with host (e.g. "http://www.example.com/test")
Expand All @@ -227,7 +230,7 @@ def __init__(self, urls, status=None, encoding=None):

@classproperty
def default_status(cls):
"""The default redirect status for the request.
"""Redirect status for the request, this is the default handler.
webknjaz marked this conversation as resolved.
Show resolved Hide resolved

RFC 2616 indicates a 301 response code fits our goal; however,
browser support for 301 is quite messy. Use 302/303 instead. See
Expand All @@ -242,8 +245,9 @@ def status(self):
return status

def set_response(self):
"""Modify cherrypy.response status, headers, and body to represent
self.
"""Modify cherrypy.response to represent self.
webknjaz marked this conversation as resolved.
Show resolved Hide resolved

Modifies status, headers, and body.

CherryPy uses this internally, but you can also use it to create
an HTTPRedirect object and set its output without *raising* the
Expand Down Expand Up @@ -366,6 +370,7 @@ class HTTPError(CherryPyException):
"""The HTTP Reason-Phrase string."""

def __init__(self, status=500, message=None):
"""Initialize HTTPError."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
self.status = status
try:
self.code, self.reason, defaultmsg = _httputil.valid_status(status)
Expand All @@ -381,8 +386,9 @@ def __init__(self, status=500, message=None):
CherryPyException.__init__(self, status, message)

def set_response(self):
"""Modify cherrypy.response status, headers, and body to represent
self.
"""Modify cherrypy.response to represent self.
webknjaz marked this conversation as resolved.
Show resolved Hide resolved

Modifies status, headers, and body.

CherryPy uses this internally, but you can also use it to create
an HTTPError object and set its output without *raising* the
Expand All @@ -408,6 +414,7 @@ def set_response(self):
_be_ie_unfriendly(self.code)

def get_error_page(self, *args, **kwargs):
"""Get error page."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
return get_error_page(*args, **kwargs)

def __call__(self):
Expand All @@ -432,6 +439,7 @@ class NotFound(HTTPError):
"""

def __init__(self, path=None):
"""Initialize NotFound HTTPError."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
if path is None:
request = cherrypy.serving.request
path = request.script_name + request.path_info
Expand Down Expand Up @@ -600,7 +608,6 @@ def bare_error(extrabody=None):
is set in the body. If extrabody is a string, it will be appended
as-is to the body.
"""

# The whole point of this function is to be a last line-of-defense
# in handling errors. That is, it must not raise any errors itself;
# it cannot be allowed to fail. Therefore, don't add to it!
Expand Down
14 changes: 11 additions & 3 deletions cherrypy/_cplogging.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""
Cherrpy Logging module.
webknjaz marked this conversation as resolved.
Show resolved Hide resolved

Simple config
=============

Expand Down Expand Up @@ -126,12 +128,15 @@ class NullHandler(logging.Handler):
"""A no-op logging handler to silence the logging.lastResort handler."""

def handle(self, record):
"""Handle stub."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
pass

def emit(self, record):
"""Emit stub."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
pass

def createLock(self):
"""Create Lock stub."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
self.lock = None


Expand Down Expand Up @@ -167,6 +172,7 @@ class LogManager(object):
"""

def __init__(self, appid=None, logger_root='cherrypy'):
"""Initialize LogManager."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
self.logger_root = logger_root
self.appid = appid
if appid is None:
Expand Down Expand Up @@ -217,11 +223,11 @@ def error(self, msg='', context='', severity=logging.INFO,
)

def __call__(self, *args, **kwargs):
"""An alias for ``error``."""
"""Call handler, An alias for ``error``."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
return self.error(*args, **kwargs)

def access(self):
"""Write to the access log (in Apache/NCSA Combined Log format).
r"""Write to the access log (in Apache/NCSA Combined Log format).

See the
`apache documentation
Expand Down Expand Up @@ -414,7 +420,7 @@ def wsgi(self, newvalue):


class WSGIErrorHandler(logging.Handler):
"A handler class which writes logging records to environ['wsgi.errors']."
"""Handler class that writes logging records to environ['wsgi.errors']."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved

def flush(self):
"""Flushes the stream."""
Expand Down Expand Up @@ -450,6 +456,8 @@ def emit(self, record):


class LazyRfc3339UtcTime(object):
"""LazyRfc3339UtcTime class."""
webknjaz marked this conversation as resolved.
Show resolved Hide resolved

def __str__(self):
"""Return datetime in RFC3339 UTC Format."""
iso_formatted_now = datetime.datetime.now(
Expand Down