【问题标题】:Python twisted putChild not forwarding expectedlyPython 扭曲 putChild 未按预期转发
【发布时间】:2017-07-09 19:59:14
【问题描述】:

代码在这里。

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。

【问题讨论】:

  • 我无法重现该问题。我删除了一堆无关紧要的东西,但核心完好无损——它为我提供了一个目录列表。
  • 什么版本的Twisted、Python、什么操作系统等
  • Python 3.5,Windows 10。没有 venv。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-12-03
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多