我正在使用 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/