2017-08-12 54 views
0

我想使用twisted生成站點的所有頁面。它必須與generating a page dynamically相似。使用Twisted動態生成站點

我想出了這一點:

class Home(Resource): 
    isLeaf = False 

    def __init__(self, pathname): 
     Resource.__init__(self) 
     self.pathname = pathname 

    def getChild(self, name, request): 
     if name == '': 
      return self 
     return Resource.getChild(self, name, request) 

    def render_GET(self, request): 
     path = "/var/www/html/books.toscrape.com/catalogue/" 
     fname = path + self.pathname 
     if ".html" in self.pathname: 
      f = open(fname) 
      s=f.read() 
      return s 
     else: 
      fname = fname + "/index.html" 
      f = open(fname) 
      s=f.read() 
      return s 

class ElseSite(Resource): 
    def getChild(self,name,request): 
     return Home(name) 

resource = ElseSite() 
factory = Site(resource) 

我能夠生成的URL localhost:8080/foo頁,但我怎麼可以添加更多的斜線到它,即像localhost:8080/foo/bar

+0

你打算問一個問題嗎? –

+0

@ Jean-PaulCalderone對不起,加了我的懷疑。 –

回答

1

孩子可以有自己的孩子:

from twisted.web.resource import Resource 

class Foo(Resource): 
    def getChild(self, name, request): 
     return Bar(name) 

class Bar(Resource): 
    def getChild(self, name, request): 
     return Data(name) 

site = Site(Foo())  
... 

你也可能想看看Klein它提供了不同的樣式定義您的層次。來自Klein文檔:

from klein import Klein 
app = Klein() 

@app.route('/') 
def pg_root(request): 
    return 'I am the root page!' 

@app.route('/about') 
def pg_about(request): 
    return 'I am a Klein application!' 

app.run("localhost", 8080) 

原生Twisted Web風格適合非常動態的資源層次結構。 Klein風格對於相對固定的層次結構來說很不錯。

+0

感謝您的回答。這個答案幫助了我:https://stackoverflow.com/a/37689813/217088。 –

-1

此答案幫助了我:https://stackoverflow.com/a/37689813/217088

我定義了單個資源isLeaf = True,然後使用request.postpath在​​之後得到查詢。

我的代碼看起來像現在這樣:

class Home(Resource): 
    isLeaf = True 

    def __init__(self): 
     Resource.__init__(self) 

    def render_GET(self, request): 
     path = "/var/www/html/books.toscrape.com/" 
     filepath = '/'.join(request.postpath) 
     fname = path + filepath 
     f = open(fname) 
     s=f.read() 
     return s 

resource = Home() 
factory = Site(resource) 
+0

這是'render_GET'的一個非常有問題的實現。請考慮一個像'../../../../ etc/passwd'這樣的路徑請求。這不是實現資源的好方法。 –

+0

我明白這裏的錯。謝謝! –