0

I want to generate all the pages of a site using twisted. It has to be similar with generating a page dynamically.

I came up with this :

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)

I'm able to generate pages with the url localhost:8080/foo, but how can I add more slashes to it, i.e. something like localhost:8080/foo/bar?

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
Parth Verma
  • 95
  • 1
  • 10

2 Answers2

1

Children themselves can have children:

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

You may also want to take a look at Klein which provides for a different style of defining your hierarchy. From the Klein docs:

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)

The native Twisted Web style is nice for very dynamic resource hierarchies. The Klein style is nice for relatively fixed hierarchies.

Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122
-1

This answer helped me : https://stackoverflow.com/a/37689813/217088.

I defined a single resource with isLeaf = True, and then used request.postpath to get the query after http://localhost:8080/.

My code looks like this now :

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)
Parth Verma
  • 95
  • 1
  • 10