How to Handle POST requests in Twisted

房东的猫 提交于 2019-12-24 00:36:21

问题


I have a very simple twisted script where you can handle POST requests:

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

    def render_POST(self, request):
        return '<html><body>You submitted: %s</body></html>' % (cgi.escape(request.args["form-field"][0]),)

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

But whenever I run this and fill out the box, I get and error:

builtins.KeyError: 'form-field'

Could anybody tell me why this is? thanks!!


回答1:


I found a solution using request.content.read()

def render_POST(self, request):
    return '<html><body>You submitted: %s</body></html>' % (request.content.read())

It might not be the best solution, but It worked for me. Please comment If you have a better solution, thanks!




回答2:


Found the solution. I got stuck here for a long time doing the "O'Reily Twisted" in Python3. Here's what worked for me:

def render_POST(self, request):
    return_value = "<html><body>You submitted: %s </body></html>" % (cgi.escape(str(request.args[b"form-field"][0], 'utf-8')))
    return str.encode(return_value)

I guess the first reason I had trouble was that the form fields were that can be extracted in python code were in byte string. Only after I checked the request args that I realized that. I suppose in python2, it was regular string.



来源:https://stackoverflow.com/questions/37398611/how-to-handle-post-requests-in-twisted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!