【问题标题】:Can't get POST parameters无法获取 POST 参数
【发布时间】:2017-04-26 17:34:09
【问题描述】:

我正在使用 WebApp2 作为框架在 Python 中开发一个 Web 应用程序。 填表提交的http POST请求参数获取不到。

这是我创建的表单的 HTML 代码

<html>
<head>
<title>Normal Login Page </title>
</head>
<body>
<form method="post" action="/loginN/" enctype="text/plain" >
eMail: <input type="text" name="eMail"><br/>
password: <input type="text" name="pwd"><br/>
<input type="submit">
</form>
</body>

这是按下提交按钮后POST请求的结果

POST /loginN/ HTTP/1.1
Accept: 
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control: max-age=0
Content-Length: 33
Content-Type: text/plain
Content_Length: 33
Content_Type: text/plain
Cookie: 
session=############
Host: ###########
Origin: ###########
Referer: ############
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
X-Appengine-City: #######
X-Appengine-Citylatlong: ########
X-Appengine-Country: ##
X-Appengine-Region: ##
X-Cloud-Trace-Context: ##

eMail=mymail@email.com
pwd=mypwd

这是 POST 请求处理程序的代码

class loginN(BaseHandler):
    def post(self):
        w = self.response.write
        self.response.headers['Content-Type'] = 'text/html'
        logging.info(self.request)
        logging.info(self.request.POST.get('eMail'))
        logging.info(self.request.POST.get('pwd'))
        email = self.request.POST.get('eMail')
        pwd = self.request.POST.get('pwd')
        w('<html>')
        w('<head>')
        w('<title>Data Page </title>')
        w('</head>')
        w('<p>Welcome! Your mail is: %s</p>' % email)
        w('<p>Your pwd is: %s</p>' % pwd)
        w('</body>')  

BaseHandler 是 webapp2.RequestHandler 扩展用于处理会话(我也尝试使用 webapp2.RequestHandler 并且得到了相同的结果)。

我每次得到的两个参数都没有。

关于如何解决问题的任何建议?我也尝试了 self.request.get,而不是 self.request.POST.get,但它也没有用(我也没有得到 None)

【问题讨论】:

    标签: python http post parameters webapp2


    【解决方案1】:

    尝试从表单中删除enctype="text/plain" 属性,然后使用self.request.POST.get('eMail')self.request.POST.get('pwd')

    编辑:删除enctype="text/plain" 起作用的原因是您希望enctype 为"text/html"(这是默认值),以便webapp2 将表单作为html 表单读取。当它只是设置为"text/plain" 时,表单的输出仅作为文本包含在请求的正文中,这就是您在打印出请求时看到的内容。如果您使用"text/plain",那么您可以使用以下命令将表单的输出作为字符串访问:

    form_string = str(self.request.body)
    

    然后您可以解析该字符串以获取键值对。正如您已经知道的那样,将 enctype 设置为 html 以获得标准的 http-form 功能更容易。

    我无法在文档中具体找到enctype 信息,但如果您对请求对象有其他疑问,我建议您阅读Webob Documentation 以获取请求对象。 Webapp2 使用 Webob 请求,因此文档是了解您的请求对象的地方。

    【讨论】:

    • 它可以在没有 enctype="text/plain" 的情况下工作 谢谢!你能解释一下为什么吗?
    • 我很高兴它成功了!我在回答中添加了解释。
    • 非常好!谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 2013-06-19
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多