Вопрос

I know that in CherryPy requested pages are bound to the functions with the same names. For example

import cherrypy
class HelloWorld(object):
    def index(self):
        return "Hello World!"
    def hello(self):
        return "Hello Hello2!"
    index.exposed = True
    hello.exposed = True

cherrypy.quickstart(HelloWorld())

if we go to 127.0.0.1:8080/hello we get Hello Hello2!.

However, I need a more flexible behavior. I do not know in advance what URL will be requested, I just want to be able to determine with CherryPy the requested URL. For example if 127.0.0.1:8080/goodbye is requested, I want to know that some variable is equal to goodbye and than based on the found value, I start a certain functionality.

Это было полезно?

Решение

+1 For @Burhan's answer. However for a simple working example you'll only need something like this:

import cherrypy

class HelloWorld(object):
    @cherrypy.expose
    def default(self, *args, **kwargs):
        return "Hello world!" + cherrypy.url()

cherrypy.quickstart(HelloWorld())

Другие советы

CherryPy supports many kinds of route mapping (called dispatching). From the dispatch documentation:

def root_index(name):
    return "Hello, %s!" % name

def branch_leaf(size):
    return str(int(size) + 3)

mappings = [
    (r'^/([^/]+)$', root_index),
    (r'^/branch/leaf/(\d+)$', branch_leaf),
    ]

You can see the root_index method is taking any arbitrary URL; and passing the url as the first argument (in this case name) to the method.

You can modify the regular expression to be more inclusive - the expression in the documentation skips /, so /hello/world/ will not be captured.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top