如何处理Twisted中的POST请求 [英] How to Handle POST requests in Twisted
问题描述
我有一个非常简单的扭曲脚本,您可以在其中处理POST请求:
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!!
推荐答案
找到了解决方案.我在这里做了很长时间,在Python3中做了"O'Reily Twisted".这是对我有用的东西:
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)
我想我遇到麻烦的第一个原因是可以在python代码中提取的表单字段是字节字符串.只有在检查了请求参数之后,我才意识到了这一点.我想在python2中,它是常规字符串.
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.
这篇关于如何处理Twisted中的POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!