我如何在 Twisted 中处理 POST 请求?

How do I handle POST requests in Twisted?

我正在尝试编写一个脚本,让某人可以在框中键入网站名称,然后我的脚本将呈现该网站的资源。我不确定该怎么做,我想它会像这样:

class FormPage(Resource):
    isLeaf = True
    def render_GET(self, request):
        return b"""<html><body><form method="POST"><input name="form-field" type="text"/><input type="submit" /></form></body></html>"""

    def render_POST(self, request):
        answer = request.content.read()[11:].decode()
        ReverseProxyResource(answer, 80, b'')

factory = Site(FormPage())
reactor.listenTCP(80, factory)
reactor.run()

此脚本无法正常工作,当脚本出现错误时:Request did not return bytes。谁能告诉我我做错了什么或者我在哪里可以了解更多关于这个主题的信息?谢谢!!

我有一段时间没有使用 Resources 和 Site 对象了,但我很确定你已经重载了 Resource.getChild() 方法和 return a ReverseProxyResource 来实现什么你要。如果你走那条路,我认为它会变得有点混乱。但是,在 klein 中,您尝试做的事情是微不足道的,很容易解决。您基本上设置了 branch=True,这使得 Resource 对象可以被 return 编辑。例如:

from klein import Klein
from twisted.web.proxy import ReverseProxyResource

app = Klein()

@app.route('/', methods=['GET'])
def render_GET(request):
    return b"""<html><body><form method="POST"><input name="form-field" type="text"/><input type="submit" /></form></body></html>"""

@app.route('/', methods=['POST'])
def render_POST(request, branch=True):        # branch=True lets you return Resources
    answer = request.args.get(b'form-field', b'localhost').decode('utf-8')        # also use request.args instead
    return ReverseProxyResource(answer, 80, '')

app.run('localhost', 80)

最后一件事,您在 Python 3.x 上 运行 进行此操作,但似乎 ReverseProxyResource 尚未完全移植。因此,如果您 运行 Python 3 中的此代码,您将获得回溯。