Python扭曲putChild不会转发

时间:2017-02-20 13:47:07

标签: python-3.x twisted twisted.web

此处代码。

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

正如你所看到的那样,我在事情结束时做了root.putChild,期待当我到达http://site/rcs时,我会得到./images内容的目录列表,但当然这不会发生。我错过了什么?我尝试了here建议的许多事情。另外this one不起作用,因为它只是提供静态文件。无论是否指定了putChild,它都会一直进入getChild。

1 个答案:

答案 0 :(得分:7)

在Python 3上,像"rcs"这样的字符串字符串是一个unicode字符串(Python 3称之为“str”,但为了避免歧义,我称之为“unicode”)。

但是,twisted.web.resource.Resource.putChild需要一个字节字符串作为其第一个参数。相反,当给予unicode时,它行为不当。使您的路径段成为字节字符串(例如b"rcs"),服务器在Python 3上的表现会更好。