2014-03-12 3 views
0

CherryPy에서 요청한 페이지가 같은 이름의 함수에 바인딩되어 있다는 것을 알고 있습니다. 우리가 127.0.0.1:8080/hello에 가면 예를CherryPy에서 필요한 페이지의 이름을 얻는 방법?

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()) 

위해 우리는 Hello Hello2!를 얻을.

그러나 더 유연한 동작이 필요합니다. 어떤 URL이 요청 될지 미리 알지 못합니다. 요청한 URL을 CherryPy로 결정할 수 있기를 원합니다. 예를 들어 127.0.0.1:8080/goodbye이 요청 된 경우 일부 변수가 goodbye과 같으며 발견 된 값을 기준으로 특정 기능이 시작된다는 것을 알고 싶습니다.

답변

2

+1 @ Burhan의 대답. 그러나 간단한 예제의 경우 다음과 같이하면됩니다 :

import cherrypy 

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

cherrypy.quickstart(HelloWorld()) 
+0

매핑 예제가 더 유연하고 명확하지만 답변은 실제로 OP가 찾고있는 모든 +1이 될 수 있습니다. –

1

CherryPy는 많은 종류의 경로 매핑 (디스 패칭이라고 함)을 지원합니다.

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), 
    ] 

당신은 root_index 방법은 임의의 URL을 복용 볼 수 있으며 다음 dispatch documentation에서 메소드에 url을 첫 번째 인수 (이 경우 name)로 전달합니다.

일반 표현식을 더 포괄적으로 수정할 수 있습니다. 설명서의 표현은 /이므로 건너 뜁니다. 따라서 /hello/world/은 캡처되지 않습니다.