Skip to content

Commit

Permalink
Updates to satsify pep257 violations
Browse files Browse the repository at this point in the history
  • Loading branch information
radez committed Apr 4, 2024
1 parent 1073610 commit e18a85a
Show file tree
Hide file tree
Showing 23 changed files with 322 additions and 109 deletions.
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."""
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."""
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."""
if not isinstance(n, str):
raise TypeError('n must be a native str (got %s)' % type(n).__name__)

Expand Down
1 change: 0 additions & 1 deletion cherrypy/_cpreqbody.py
Original file line number Diff line number Diff line change
Expand Up @@ -773,7 +773,6 @@ def read(self, size=None, fp_out=None):
object that supports the 'write' method; all bytes read will be
written to the fp, and None is returned.
"""

if self.length is None:
if size is None:
remaining = inf
Expand Down
19 changes: 16 additions & 3 deletions cherrypy/_cprequest.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ def __init__(self, callback, failsafe=None, priority=None, **kwargs):

def __lt__(self, other):
"""
Less-Than Hook Operator.
:param other: A Hook Object to compare priority with
:type other: Hook
:return: Other Hook's priority is higher than this one
:rtype: Bool
Hooks sort by priority, ascending, such that
hooks of lower priority are run first.
"""
Expand Down Expand Up @@ -541,7 +549,7 @@ def close(self):
self.stage = 'close'

def run(self, method, path, query_string, req_protocol, headers, rfile):
r"""Process the Request. (Core)
r"""Process the Request (Core).
method, path, query_string, and req_protocol should be pulled directly
from the Request-Line (e.g. "GET /path?key=val HTTP/1.0").
Expand Down Expand Up @@ -896,8 +904,13 @@ def collapse_body(self):
return new_body

def _flush_body(self):
"""Discard self.body but consume any generator such that any
finalization can occur, such as is required by caching.tee_output()."""
"""_flush_body Response.
:rtype: None
Discard self.body but consume any generator such that any
finalization can occur, such as is required by caching.tee_output().
"""
consume(iter(self.body))

def finalize(self):
Expand Down
26 changes: 20 additions & 6 deletions cherrypy/_cptools.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class Tool(object):
namespace = 'tools'

def __init__(self, point, callable, name=None, priority=50):
"""Initialize Tool."""
self._point = point
self.callable = callable
self._name = name
Expand All @@ -66,10 +67,12 @@ def __init__(self, point, callable, name=None, priority=50):

@property
def on(self):
"""Property on."""
raise AttributeError(_attr_error)

@on.setter
def on(self, value):
"""Setter for on property."""
raise AttributeError(_attr_error)

def _setargs(self):
Expand Down Expand Up @@ -133,7 +136,7 @@ def tool_decorator(f):
return tool_decorator

def _setup(self):
"""Hook this tool into cherrypy.request.
"""Hooking this tool into cherrypy.request.
The standard CherryPy request object will automatically call
this method when the tool is "turned on" in config.
Expand All @@ -159,6 +162,7 @@ class HandlerTool(Tool):
"""

def __init__(self, callable, name=None):
"""Initialize HandlerTool."""
Tool.__init__(self, 'before_handler', callable, name)

def handler(self, *args, **kwargs):
Expand All @@ -183,7 +187,7 @@ def _wrapper(self, **kwargs):
cherrypy.serving.request.handler = None

def _setup(self):
"""Hook this tool into cherrypy.request.
"""Hooking this tool into cherrypy.request.
The standard CherryPy request object will automatically call
this method when the tool is "turned on" in config.
Expand Down Expand Up @@ -217,12 +221,14 @@ def interpolator(next_handler, *args, **kwargs):

def __init__(self, newhandler, point='before_handler', name=None,
priority=50):
"""Initialize HandlerWrapperTool."""
self.newhandler = newhandler
self._point = point
self._name = name
self._priority = priority

def callable(self, *args, **kwargs):
"""Make HandlerWrapperTool callable."""
innerfunc = cherrypy.serving.request.handler

def wrap(*args, **kwargs):
Expand All @@ -234,13 +240,14 @@ class ErrorTool(Tool):
"""Tool which is used to replace the default request.error_response."""

def __init__(self, callable, name=None):
"""Initialize ErrorTool."""
Tool.__init__(self, None, callable, name)

def _wrapper(self):
self.callable(**self._merged_args())

def _setup(self):
"""Hook this tool into cherrypy.request.
"""Hooking this tool into cherrypy.request.
The standard CherryPy request object will automatically call
this method when the tool is "turned on" in config.
Expand Down Expand Up @@ -270,14 +277,15 @@ class SessionTool(Tool):
"""

def __init__(self):
"""Initialize SessionTool."""
# _sessions.init must be bound after headers are read
Tool.__init__(self, 'before_request_body', _sessions.init)

def _lock_session(self):
cherrypy.serving.session.acquire_lock()

def _setup(self):
"""Hook this tool into cherrypy.request.
"""Hooking this tool into cherrypy.request.
The standard CherryPy request object will automatically call
this method when the tool is "turned on" in config.
Expand Down Expand Up @@ -360,6 +368,7 @@ class XMLRPCController(object):

@expose
def default(self, *vpath, **params):
"""Handle default XMLRPCController."""
rpcparams, rpcmethod = _xmlrpc.process_body()

subhandler = self
Expand All @@ -384,6 +393,8 @@ def default(self, *vpath, **params):


class SessionAuthTool(HandlerTool):
"""Stub for SessionAuthTool."""

pass


Expand All @@ -402,7 +413,7 @@ def _wrapper(self, **kwargs):
_wrapper.priority = 90

def _setup(self):
"""Hook caching into cherrypy.request."""
"""Hooking caching into cherrypy.request."""
conf = self._merged_args()

p = conf.pop('priority', None)
Expand All @@ -419,9 +430,11 @@ class Toolbox(object):
"""

def __init__(self, namespace):
"""Initialize Toolbox."""
self.namespace = namespace

def __setattr__(self, name, value):
"""Set attribute for Toolbox."""
# If the Tool._name is None, supply it from the attribute name.
if isinstance(value, Tool):
if value._name is None:
Expand Down Expand Up @@ -449,7 +462,8 @@ def __exit__(self, exc_type, exc_val, exc_tb):
tool._setup()

def register(self, point, **kwargs):
"""
"""Register Toolbox.
Return a decorator which registers the function
at the given hook point.
"""
Expand Down
50 changes: 31 additions & 19 deletions cherrypy/_cpwsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@


def downgrade_wsgi_ux_to_1x(environ):
"""Return a new environ dict for WSGI 1.x from the given WSGI u.x environ.
"""
"""Return new environ dict for WSGI 1.x from provided WSGI u.x environ."""
env1x = {}

url_encoding = environ[ntou('wsgi.url_encoding')]
Expand Down Expand Up @@ -54,33 +53,36 @@ class VirtualHost(object):
cherrypy.tree.graft(vhost)
"""
default = None
"""Required.
The default WSGI application.
"""

default = None
use_x_forwarded_host = True
"""If True (the default), any "X-Forwarded-Host"
request header will be used instead of the "Host" header. This
is commonly added by HTTP servers (such as Apache) when proxying."""

domains = {}
"""A dict of {host header value: application} pairs.
The incoming "Host" request header is looked up in this dict, and,
if a match is found, the corresponding WSGI application will be
called instead of the default. Note that you often need separate
entries for "example.com" and "www.example.com". In addition, "Host"
headers may contain the port number.
"""

def __init__(self, default, domains=None, use_x_forwarded_host=True):
"""
Initialize VirtualHost.
:param default: The default WSGI application
:type default: WSGI application
:param use_x_forwarded_host: If True (the default), any
"X-Forwarded-Host" request header will be used instead of the
"Host" header. This is commonly added by HTTP servers (such as
Apache) when proxying.
:type use_x_forwarded_host: Bool, optional
:param domains: A dict of {host header value: application} pairs.
The incoming "Host" request header is looked up in this dict, and,
if a match is found, the corresponding WSGI application will be
called instead of the default. Note that you often need separate
entries for "example.com" and "www.example.com". In addition,
"Host" headers may contain the port number.
:type domains: Dict, optional
"""
self.default = default
self.domains = domains or {}
self.use_x_forwarded_host = use_x_forwarded_host

def __call__(self, environ, start_response):
"""Call VirtualHost."""
domain = environ.get('HTTP_HOST', '')
if self.use_x_forwarded_host:
domain = environ.get('HTTP_X_FORWARDED_HOST', domain)
Expand All @@ -95,10 +97,12 @@ class InternalRedirector(object):
"""WSGI middleware that handles raised cherrypy.InternalRedirect."""

def __init__(self, nextapp, recursive=False):
"""Initialize InternalRedirector."""
self.nextapp = nextapp
self.recursive = recursive

def __call__(self, environ, start_response):
"""Initialize InternalRedirector."""
redirections = []
while True:
environ = environ.copy()
Expand Down Expand Up @@ -142,10 +146,12 @@ class ExceptionTrapper(object):
"""WSGI middleware that traps exceptions."""

def __init__(self, nextapp, throws=(KeyboardInterrupt, SystemExit)):
"""Initialize ExceptionTrapper."""
self.nextapp = nextapp
self.throws = throws

def __call__(self, environ, start_response):
"""Call ExceptionTrapper."""
return _TrappedResponse(
self.nextapp,
environ,
Expand Down Expand Up @@ -230,6 +236,7 @@ class AppResponse(object):
"""WSGI response iterable for CherryPy applications."""

def __init__(self, environ, start_response, cpapp):
"""Initialize AppResponse."""
self.cpapp = cpapp
try:
self.environ = environ
Expand Down Expand Up @@ -271,9 +278,11 @@ def __init__(self, environ, start_response, cpapp):
raise

def __iter__(self):
"""Handle iteration for AppResponse."""
return self

def __next__(self):
"""Handle next for AppResponse."""
return next(self.iter_response)

def close(self):
Expand Down Expand Up @@ -346,6 +355,7 @@ def run(self):
}

def recode_path_qs(self, path, qs):
"""Recode path qs AppResponse."""
# This isn't perfect; if the given PATH_INFO is in the
# wrong encoding, it may fail to match the appropriate config
# section URI. But meh.
Expand Down Expand Up @@ -416,6 +426,7 @@ class CPWSGIApp(object):
"""

def __init__(self, cpapp, pipeline=None):
"""Initialize CPWSGIApp."""
self.cpapp = cpapp
self.pipeline = self.pipeline[:]
if pipeline:
Expand All @@ -431,6 +442,7 @@ def tail(self, environ, start_response):
return self.response_class(environ, start_response, self.cpapp)

def __call__(self, environ, start_response):
"""Handle call to CPWSGIApp."""
head = self.head
if head is None:
# Create and nest the WSGI apps in our pipeline (in reverse order).
Expand Down
9 changes: 6 additions & 3 deletions cherrypy/lib/auth_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@


def checkpassword_dict(user_password_dict):
"""Returns a checkpassword function which checks credentials
"""Check credentials against a dictionary.
Returns a checkpassword function which checks credentials
against a dictionary of the form: {username : password}.
If you want a simple dictionary-based authentication scheme, use
Expand All @@ -48,7 +50,9 @@ def checkpassword(realm, user, password):


def basic_auth(realm, checkpassword, debug=False, accept_charset='utf-8'):
"""A CherryPy tool which hooks at before_handler to perform
"""Perform basic auth.
A CherryPy tool which hooks at before_handler to perform
HTTP Basic Access Authentication, as specified in :rfc:`2617`
and :rfc:`7617`.
Expand All @@ -69,7 +73,6 @@ def basic_auth(realm, checkpassword, debug=False, accept_charset='utf-8'):
returns True, else it returns False.
"""

fallback_charset = 'ISO-8859-1'

if '"' in realm:
Expand Down
Loading

0 comments on commit e18a85a

Please sign in to comment.