2017-04-26 115 views
1

我正在開發一個使用WebApp2作爲框架的Python應用程序。 我無法獲取通過填寫表單提交的http POST請求參數。無法獲取POST參數

這就是我創建

<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> 

形式的HTML代碼,這是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 protected] 
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)

回答

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請求,因此文檔是理解您的請求對象的地方。

+0

它的工作原理沒有enctype =「text/plain」 謝謝!你能解釋我爲什麼嗎? –

+0

我很高興它的工作!我在我的答案中添加了一個解釋。 –

+0

非常親切!謝謝 –