Skip to content

Commit

Permalink
Use expose decorator throughout the codebase.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Jun 5, 2016
1 parent f77bef6 commit 5e1a48f
Show file tree
Hide file tree
Showing 56 changed files with 351 additions and 345 deletions.
3 changes: 3 additions & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

* ``@cherrypy.expose`` now will also set the exposed
attribute on a class.
* Rewrote all tutorials and internal usage to prefer
the decorator usage of ``expose`` rather than setting
the attribute explicitly.

5.5.0
-----
Expand Down
2 changes: 1 addition & 1 deletion cherrypy/_cpconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@
class Demo:
_cp_config = {'tools.gzip.on': True}
@cherrypy.expose
def index(self):
return "Hello world"
index.exposed = True
index._cp_config = {'request.show_tracebacks': False}
.. note::
Expand Down
7 changes: 4 additions & 3 deletions cherrypy/_cptools.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import warnings

import cherrypy
from cherrypy._helper import expose


def _getargs(func):
Expand Down Expand Up @@ -113,10 +114,10 @@ def __call__(self, *args, **kwargs):
For example::
@expose
@tools.proxy()
def whats_my_base(self):
return cherrypy.request.base
whats_my_base.exposed = True
"""
if args:
raise TypeError("The %r Tool does not accept positional "
Expand Down Expand Up @@ -171,12 +172,12 @@ class Root:
nav = tools.staticdir.handler(section="/nav", dir="nav",
root=absDir)
"""
@expose
def handle_func(*a, **kw):
handled = self.callable(*args, **self._merged_args(kwargs))
if not handled:
raise cherrypy.NotFound()
return cherrypy.serving.response.body
handle_func.exposed = True
return handle_func

def _wrapper(self, **kwargs):
Expand Down Expand Up @@ -365,6 +366,7 @@ class XMLRPCController(object):
# would be if someone actually disabled the default_toolbox. Meh.
_cp_config = {'tools.xmlrpc.on': True}

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

Expand All @@ -387,7 +389,6 @@ def default(self, *vpath, **params):
conf.get('encoding', 'utf-8'),
conf.get('allow_none', 0))
return cherrypy.serving.response.body
default.exposed = True


class SessionAuthTool(HandlerTool):
Expand Down
11 changes: 7 additions & 4 deletions cherrypy/lib/covercp.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@
import re
import sys
import cgi
from cherrypy._cpcompat import quote_plus
import os
import os.path
localFile = os.path.join(os.path.dirname(__file__), "coverage.cache")

from cherrypy._cpcompat import quote_plus

import cherrypy

the_coverage = None
try:
from coverage import coverage
Expand Down Expand Up @@ -290,10 +293,11 @@ def __init__(self, coverage, root=None):
root = os.path.dirname(cherrypy.__file__)
self.root = root

@cherrypy.exposed
def index(self):
return TEMPLATE_FRAMESET % self.root.lower()
index.exposed = True

@cherrypy.exposed
def menu(self, base="/", pct="50", showpct="",
exclude=r'python\d\.\d|test|tut\d|tutorial'):

Expand Down Expand Up @@ -328,7 +332,6 @@ def menu(self, base="/", pct="50", showpct="",

yield "</div>"
yield "</body></html>"
menu.exposed = True

def annotated_file(self, filename, statements, excluded, missing):
source = open(filename, 'r')
Expand All @@ -352,6 +355,7 @@ def annotated_file(self, filename, statements, excluded, missing):
buffer = []
yield template % (lineno, cgi.escape(line))

@cherrypy.exposed
def report(self, name):
filename, statements, excluded, missing, _ = self.coverage.analysis2(
name)
Expand All @@ -366,7 +370,6 @@ def report(self, name):
yield '</table>'
yield '</body>'
yield '</html>'
report.exposed = True


def serve(path=localFile, port=8080, root=None):
Expand Down
8 changes: 4 additions & 4 deletions cherrypy/lib/cpstats.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ class StatsPage(object):
},
}

@cherrypy.exposed
def index(self):
# Transform the raw data into pretty output for HTML
yield """
Expand Down Expand Up @@ -578,7 +579,6 @@ def index(self):
</body>
</html>
"""
index.exposed = True

def get_namespaces(self):
"""Yield (title, scalars, collections) for each namespace."""
Expand Down Expand Up @@ -678,22 +678,22 @@ def get_list_collection(self, v, formatting):
return headers, subrows

if json is not None:
@cherrypy.expose
def data(self):
s = extrapolate_statistics(logging.statistics)
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps(s, sort_keys=True, indent=4)
data.exposed = True

@cherrypy.expose
def pause(self, namespace):
logging.statistics.get(namespace, {})['Enabled'] = False
raise cherrypy.HTTPRedirect('./')
pause.exposed = True
pause.cp_config = {'tools.allow.on': True,
'tools.allow.methods': ['POST']}

@cherrypy.expose
def resume(self, namespace):
logging.statistics.get(namespace, {})['Enabled'] = True
raise cherrypy.HTTPRedirect('./')
resume.exposed = True
resume.cp_config = {'tools.allow.on': True,
'tools.allow.methods': ['POST']}
4 changes: 2 additions & 2 deletions cherrypy/lib/gctools.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,11 @@ class GCRoot(object):
"Should be 1 in this request thread only."),
]

@cherrypy.expose
def index(self):
return "Hello, world!"
index.exposed = True

@cherrypy.expose
def stats(self):
output = ["Statistics:"]

Expand Down Expand Up @@ -214,4 +215,3 @@ def stats(self):
output.extend(t.format(tree))

return "\n".join(output)
stats.exposed = True
11 changes: 7 additions & 4 deletions cherrypy/lib/profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
class Root:
p = profiler.Profiler("/path/to/profile/dir")
@cherrypy.expose
def index(self):
self.p.run(self._index)
index.exposed = True
def _index(self):
return "Hello, world!"
Expand All @@ -34,6 +34,9 @@ def _index(self):
"""


import cherrypy


def new_func_strip_path(func_name):
"""Make profiler output more readable by adding `__init__` modules' parents
"""
Expand Down Expand Up @@ -110,6 +113,7 @@ def stats(self, filename, sortby='cumulative'):
sio.close()
return response

@cherrypy.expose
def index(self):
return """<html>
<head><title>CherryPy profile data</title></head>
Expand All @@ -119,8 +123,8 @@ def index(self):
</frameset>
</html>
"""
index.exposed = True

@cherrypy.expose
def menu(self):
yield "<h2>Profiling runs</h2>"
yield "<p>Click on one of the runs below to see profiling data.</p>"
Expand All @@ -129,13 +133,12 @@ def menu(self):
for i in runs:
yield "<a href='report?filename=%s' target='main'>%s</a><br />" % (
i, i)
menu.exposed = True

@cherrypy.expose
def report(self, filename):
import cherrypy
cherrypy.response.headers['Content-Type'] = 'text/plain'
return self.stats(filename)
report.exposed = True


class ProfileAggregator(Profiler):
Expand Down
2 changes: 1 addition & 1 deletion cherrypy/process/servers.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@
class HelloWorld:
\"""Sample request handler class.\"""
@cherrypy.expose
def index(self):
return "Hello world!"
index.exposed = True
cherrypy.tree.mount(HelloWorld())
# CherryPy autoreload must be disabled for the flup server to work
Expand Down
6 changes: 3 additions & 3 deletions cherrypy/scaffold/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class Root:
_cp_config = {'tools.log_tracebacks.on': True,
}

@cherrypy.expose
def index(self):
return """<html>
<body>Try some <a href='%s?a=7'>other</a> path,
Expand All @@ -32,19 +33,18 @@ def index(self):
<img src='%s' />
</body></html>""" % (url("other"), url("else"),
url("files/made_with_cherrypy_small.png"))
index.exposed = True

@cherrypy.expose
def default(self, *args, **kwargs):
return "args: %s kwargs: %s" % (args, kwargs)
default.exposed = True

@cherrypy.expose
def other(self, a=2, b='bananas', c=None):
cherrypy.response.headers['Content-Type'] = 'text/plain'
if c is None:
return "Have %d %s." % (int(a), b)
else:
return "Have %d %s, %s." % (int(a), b, c)
other.exposed = True

files = cherrypy.tools.staticdir.handler(
section="/files",
Expand Down
10 changes: 5 additions & 5 deletions cherrypy/test/_test_states_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,30 @@

class Root:

@cherrypy.expose
def index(self):
return "Hello World"
index.exposed = True

@cherrypy.expose
def mtimes(self):
return repr(cherrypy.engine.publish("Autoreloader", "mtimes"))
mtimes.exposed = True

@cherrypy.expose
def pid(self):
return str(os.getpid())
pid.exposed = True

@cherrypy.expose
def start(self):
return repr(starttime)
start.exposed = True

@cherrypy.expose
def exit(self):
# This handler might be called before the engine is STARTED if an
# HTTP worker thread handles it before the HTTP server returns
# control to engine.start. We avoid that race condition here
# by waiting for the Bus to be STARTED.
cherrypy.engine.wait(state=cherrypy.engine.states.STARTED)
cherrypy.engine.exit()
exit.exposed = True


def unsub_sig():
Expand Down
6 changes: 3 additions & 3 deletions cherrypy/test/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@

class Root:

@cherrypy.expose
def index(self):
return """<html>
<head>
Expand All @@ -65,18 +66,17 @@ def index(self):
</ul>
</body>
</html>"""
index.exposed = True

@cherrypy.expose
def hello(self):
return "Hello, world\r\n"
hello.exposed = True

@cherrypy.expose
def sizer(self, size):
resp = size_cache.get(size, None)
if resp is None:
size_cache[size] = resp = "X" * int(size)
return resp
sizer.exposed = True


cherrypy.config.update({
Expand Down
6 changes: 3 additions & 3 deletions cherrypy/test/sessiondemo.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,23 +131,23 @@ def page(self):
'expires': expires,
}

@cherrypy.expose
def index(self):
# Must modify data or the session will not be saved.
cherrypy.session['color'] = 'green'
return self.page()
index.exposed = True

@cherrypy.expose
def expire(self):
sessions.expire()
return self.page()
expire.exposed = True

@cherrypy.expose
def regen(self):
cherrypy.session.regenerate()
# Must modify data or the session will not be saved.
cherrypy.session['color'] = 'yellow'
return self.page()
regen.exposed = True

if __name__ == '__main__':
cherrypy.config.update({
Expand Down
6 changes: 3 additions & 3 deletions cherrypy/test/test_auth_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,23 @@ class BasicAuthTest(helper.CPWebCase):
def setup_server():
class Root:

@cherrypy.expose
def index(self):
return "This is public."
index.exposed = True

class BasicProtected:

@cherrypy.expose
def index(self):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
index.exposed = True

class BasicProtected2:

@cherrypy.expose
def index(self):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
index.exposed = True

userpassdict = {'xuser': 'xpassword'}
userhashdict = {'xuser': md5(ntob('xpassword')).hexdigest()}
Expand Down
Loading

0 comments on commit 5e1a48f

Please sign in to comment.