2014-10-18 24 views
0

我想做一個極簡主義網站,只接受兩個請求。首先對'/'發出GET請求,它應該回復一些簡單的字符串。第二個是'/ put_url'的PUT請求,它接受數據的查詢。這是我到目前爲止:極簡主義櫻桃網站PUT方法

import cherrypy 

class Main(object): 
    @cherrypy.expose 
    def index(self): 
     return "Hy?" 

class Uploader(object): 
    exposed = True 
    def PUT(self, data): 
     print "hello" 
     print data 

if __name__ == '__main__': 
    conf = { 
     '/put_url': { 
      'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 
      'tools.response_headers.on': True, 
      'tools.response_headers.headers': [('Content-Type', 'text/plain')] 
      } 
     } 

    webapp = Main() 
    webapp.put_url = Uploader() 
    cherrypy.quickstart(webapp, '/', conf) 

我該如何得到這個東西的工作?出於某種原因,我無法弄清楚這一點。謝謝。

+0

從文檔中查看[this example](http://docs.cherrypy.org/zh/latest/tutorials.html#tutorial-7-give-us-a-rest) – 2014-10-18 11:44:51

回答

1

添加接受標題。爲此,請在您的PUT方法中添加一個裝飾器。

class Uploader(object): 
    exposed = True 
    @cherrypy.tools.accept(media='text/plain') 
    def PUT(self, data): 
     print "hello" 
     print data 

您可能並不總是希望使用text/plain作爲接受標題。這取決於你的應用程序。

來測試你可以使用

curl -X PUT -d data=xyz localhost:8080/put_url 
1

的問題是,你是在同一個應用程序混合調度。

例如調度移動到應用程序的根目錄的改變主要對象有方法HTTP方法,你將有這樣的事情:

import cherrypy as cp 

class Main(object): 
    exposed = True 

    def GET(self): 
     return "Hy?" 

class Uploader(object): 
    exposed = True 

    def PUT(self, data): 
     cp.log.error("hello") 
     cp.log.error(data) 
     return "The data {} has been puted".format(data) 

if __name__ == '__main__': 
    conf = { 
     '/': { 
      'request.dispatch': cp.dispatch.MethodDispatcher() 
     }, 
     '/put_url': { 
      'tools.response_headers.on': True, 
      'tools.response_headers.headers': [('Content-Type', 'text/plain')] 
     } 
    } 
    webapp = Main() 
    webapp.put_url = Uploader() 
    cp.quickstart(webapp, '/', conf) 

也可以混合默認調度員該方法調度,例如:

import cherrypy as cp 

class Main(object): 
    @cp.expose 
    def index(self): 
     return "Hy?" 


class Uploader(object): 
    exposed = True 

    def PUT(self, data): 
     cp.log.error("hello") 
     cp.log.error(data) 
     return "The data {} has been puted".format(data) 


class API(object): 
    exposed = True 

    def __init__(self): 
     self.put_url = Uploader() 

    def GET(self): 
     return "Welcome to the API!" 


if __name__ == '__main__': 
    cp.tree.mount(Main()) 
    cp.tree.mount(API(), '/api', config={ 
     '/': { 
      'request.dispatch': cp.dispatch.MethodDispatcher() 
     }, 
     '/put_url': { 
      'tools.response_headers.on': True, 
      'tools.response_headers.headers': [('Content-Type', 'text/plain')] 
     } 
    }) 
    cp.engine.start() 
    cp.engine.block() 

通知的API對象如何安裝在/api。若要PUTput_url方法只需使用網址/api/put_url。用於cherrypy.tree.mount的配置部分與安裝點相關,在本例中爲/api