Search code examples
python-3.xtwistedtwisted.web

Python twisted putChild not forwarding expectedly


Code here.

from twisted.web.static import File
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import ssl, reactor
from twisted.python.modules import getModule
import secure_aes
import urllib.parse
import cgi
import json
import os
import hashlib
import coserver
import base64
import sim

if not os.path.exists(os.path.join(os.getcwd(),'images')):
    os.mkdir(os.path.join(os.getcwd(),'images'))


with open ('form.html','r') as f:
    fillout_form = f.read()
with open ('image.html','r') as f:
    image_output = f.read()


port = 80#int(os.environ.get('PORT', 17995))
class FormPage(Resource):
    #isLeaf = True
    def getChild(self, name, request):
        print('GC')
        if name == '':
            return self
        return Resource.getChild(self, name, request)


    def render_GET(self, request):
        print(request)
        #do stuff and return stuff

root = FormPage()
root.putChild('rcs', File("./images"))
#factory = Site(FormPage())
factory = Site(root)
reactor.listenTCP(port, factory)
reactor.run()

As you can see, I did root.putChild towards the end of things, expecting that when I got to http://site/rcs I get given a directory listing of the contents of ./images but of course that doesn't happen. What am I missing? I've tried many things suggested from here. Also this one doesn't work because that's just serving static files anyways. It goes to getChild all the time regardless of whether if have specified putChild or not.


Solution

  • On Python 3, a bare string literal like "rcs" is a unicode string (which Python 3 calls "str" but which I will call "unicode" to avoid ambiguity).

    However, twisted.web.resource.Resource.putChild requires a byte string as its first argument. It misbehaves rather poorly when given unicode, instead. Make your path segments into byte strings (eg b"rcs") and the server will behave better on Python 3.