2010-11-29 67 views
1

對於超基本的http扭曲前端。 我怎樣才能確保沒有HTML寫回,除非我告訴它。覆蓋來自Twisted.web的所有默認資源/響應

所以,我有我/動物園網址下面。 對於任何回溯,或'沒有這樣的資源'的迴應,我想刪除連接或返回一個空的迴應。

我想這是一個超級簡單的,但無法弄清楚:) 我知道我可以做到這一點,沒有我的具體兒童路徑,但想要做到這一點高效率,只是想放棄它作爲儘可能早..也許不使用資源?

class HttpApi(resource.Resource): 
    isLeaf = True 
    def render_POST(self, request): 
     return "post..." 


application = service.Application("serv") 

json_api = resource.Resource() 
json_api.putChild("zoo", HttpApi()) 
web_site = server.Site(json_api) 
internet.TCPServer(8001, web_site).setServiceParent(application) 

回答

2

一些基礎知識第一

twisted.web的工作原理是

有一個叫Site類,這是一個HTTP工廠的方式。 這是爲每個請求調用的。實際上,調用一個名爲getResourceFor的函數來獲取將提供此請求的適當資源。 本網站類使用根資源進行初始化。而根資源Site.getResourceFor調用resource.getChildForRequest功能

呼叫流程是:

Site.getResourceFor - > resource.getChildForRequest(根資源)

現在是時候看看在getChildForRequest:

def getChildForRequest(resource, request): 
    """ 
    Traverse resource tree to find who will handle the request. 
    """ 
    while request.postpath and not resource.isLeaf: 
     pathElement = request.postpath.pop(0) 
     request.prepath.append(pathElement) 
     resource = resource.getChildWithDefault(pathElement, request) 
    return resource 

會發生什麼是因爲資源註冊與putChild(路徑),他們成爲奇爾該資源的資源。 一個例子:

root_resource 
| 
|------------ resource r1 (path = 'help') 
|----resource r2 (path = 'login') | 
|         |----- resource r3 (path = 'registeration') 
|         |----- resource r4 (path = 'deregistration') 

的一些思考:

  1. 現在R1將與路徑服務器請求http://../help/
  2. 現在R3將與路徑服務器請求http://../help/registration/
  3. 現在R4將與路徑http://../help/deregistration/服務器請求

  1. R3將與路徑服務器請求http://../help/registration/xxx/
  2. R3將與路徑http://../help/registration/yyy/

對於解決服務器的請求:

您需要繼承站點到

  1. 檢查如果路徑excatly匹配與pathElement資源返回空,然後才處理它或
  2. 回報,這將是你的處理程序來處理其他方面

您必須創建自己的資源的資源

def render(self, request): 
    request.setResponseCode(...) 
    return ""