Search code examples
pythontwistedtwisted.web

Twisted non default root HTTP


  1. So I want to have all of the urls start with "/files".

  2. The rootpage located at "localhost:3000/files" will return a list of specific folders that will be shared. The default share does not let me limit what folders to share.

  3. I want to show all of the files in the folder when navigated to a folder. With the URL like "localhost:3000/files/Documents".

  4. I want to share the specific folders and files in the folders recursively. With the URL like "localhost:3000/files/Documents/Filename.pdf".

    from twisted.web.server import Site
    from twisted.web.resource import Resource
    from twisted.web.static import File
    from twisted.internet import reactor
    
    folder_list = ["Documents", "Downloads"]
    
    
    class RootPage(Resource):
        isLeaf = True
        def render_GET(self, request):
            print request.uri
            new_request = request.uri[7:]
            if len(new_request) <= 3:
                ret = ""
                for folders in folder_list:
                    ret += "<a href='%s'>%s</a></br>" % ("/files/" + folders.replace(" ", "-") , folders)
                return ret
    
    root = Resource()            
    #folders
    root.putChild('files', RootPage())
    
    for folders in folder_list:
        root.putChild( folders.replace(" ", "-"), File("/home/user1/" + folders))
    
    factory = Site(root)
    
    reactor.listenTCP(3000, factory)
    reactor.run()
    

Solution

  • Problems

    1) In the .putChild() call, you establish your folder URLs as children of the root, not children of /files.

    2) In the RootPage class definition, you set isLeaf to True. But you are creating an interior node, not a leaf node.


    Solution

    Delete the isLeaf line, and change the other relevant lines to this:

    root = Resource()
    rootpage = RootPage()
    #folders
    root.putChild('files', rootpage)
    
    for folders in folder_list:
        rootpage.putChild( folders.replace(" ", "-"), File("/home/user1/" + folders))
    
    factory = Site(root)