【问题标题】:How do I handle POST requests in Twisted?如何在 Twisted 中处理 POST 请求?
【发布时间】:2016-06-02 00:51:43
【问题描述】:

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

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。谁能告诉我我做错了什么或者我可以在哪里了解更多关于这个主题的信息?谢谢!!

【问题讨论】:

标签: linux python-3.x post twisted


【解决方案1】:

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

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 中运行此代码,您将获得回溯。

【讨论】:

    猜你喜欢
    • 2016-09-20
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 2012-10-08
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多