python - 无法获取 POST 参数

标签 python http post parameters webapp2

我正在使用 WebApp2 作为框架在 Python 中开发网络应用程序。 无法获取填表提交的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 的扩展,用于处理 session (我也尝试使用 webapp2.RequestHandler,我得到了相同的结果)。

我每次得到的两个参数都是 None。

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

最佳答案

尝试从表单中删除 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 表单功能会更容易。

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

关于python - 无法获取 POST 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43640970/

相关文章:

安全性——可以通过 HTTP GET 发送用户名和密码吗?

php - PHP 中发布的冷却时间

python - 当数据没有大/inf/nan 值时,sklearn 的 yeo-johnson PowerTransformer 抛出 "ValueError: Input contains infinity"

python - 将 Geodataframe 写入 geopandas 文件时出现“不支持的驱动程序”错误

http - 浏览器是否会根据协议(protocol)改变缓存内容?

windows - SSL 证书仅适用于本地网络

php - Laravel 无法检索保存在 POST 请求中的 session 数据

c++ - 如何在 Restinio 中使用 POST 处理程序?

python - 查找嵌套整数列表的总和

python - 我如何从生命线中的 coxPHFitter 函数和变量系数中提取基线危险