from cherrypy import cpg
from cgi import escape
# Display elements from a dictionary as items in a list
def show_dict(d):
items = d.items()
items.sort()
yield "
\n"
for (name, value) in items:
yield "- " + escape(name) + " &mdash " + escape(repr(value)) + "\n"
yield "
\n"
class MyServer(object):
# A simple hello
def hello(self, username="root"):
yield "Hello, %s" % (escape(username,))
hello.exposed = True
# Add two numbers.
# Show how to change the reponse content-type
def add(self, a, b):
a = int(a)
b = int(b)
cpg.response.headerMap['Content-Type'] = "text/plain"
yield "%s + %s = %s" % (a, b, a+b)
add.exposed = True
# Print a lot of information about the request
# This gets called when the resource isn't found and when
# there is no 'index' resource.
def default(self, *args, **kwargs):
yield "Query parameters
\n"
for line in show_dict(kwargs):
yield line
yield "Request information
\n"
for line in show_dict(
{"remote address": cpg.request.remoteAddr,
"remote host": cpg.request.remoteHost,
"request line": cpg.request.requestLine,
"method": cpg.request.method,
"query string": cpg.request.queryString,
"path": cpg.request.path,
"base": cpg.request.base,
"browser URL": cpg.request.browserUrl,
}):
yield line
yield "Client HTTP headers
\n"
for line in show_dict(cpg.request.headerMap):
yield line
default.exposed = True
cpg.root = MyServer()
if __name__ == "__main__":
cpg.server.start()