2017-10-21 73 views
0

在爲我的Flask應用程序進行測試時,我偶然發現了我無法理解的行爲。在我的測試中,我使用Flask documentation建議的方法來訪問和修改測試中的session爲什麼向瓶中的函數添加請求會在空POST中導致「錯誤請求」?

說我有,很基本的,項目結構:

root 
|-- my_app.py 
|-- tests 
    |-- test_my_app.py 

my_app.py

from flask import (
    Flask, 
    session, 
    request 
    ) 

app = Flask(__name__) 
app.secret_key = 'bad secret key' 

@app.route('/action/', methods=['POST']) 
def action(): 
    the_action = request.form['action'] 
    if session.get('test'): 
     return 'Test is set, action complete.' 
    else: 
     return 'Oy vey!' 

test_my_app.py

import flask 

from unittest import TestCase 
import my_app 

class TestApp(TestCase): 

    def setUp(self): 
     self.test_client = my_app.app.test_client() 

    def testUnsetKeyViaPostNegative(self): 
     with self.test_client as client: 
      response = client.post('/action/') 
      expected_response = 'Oy vey!'.encode('ascii') 
      self.assertTrue(expected_response == response.data) 

現在,如果我運行測試它會失敗,因爲響應返回400 Bad Request。如果the_action = request.form['action']被推薦出來,一切都順利。

我需要它的原因是因爲應用程序中存在邏輯(並隨後進行測試),這取決於接收到的data(爲簡潔起見,我省略了這一點)。

我認爲改變the_action = request.form['action']到類似the_action = request.form['action'] or ''會解決問題,但它不會。一個簡單的辦法來,這是一些存根data添加到發佈請求,像這樣response = client.post('/action/', data=dict(action='stub'))

這種感覺對我來說,我錯過了一些重要的點上如何訪問&自考工作會議修改,因此我無法理解所描述的行爲。

我想了解的是:

  1. 爲什麼僅僅讓從請求數據不添加任何其他邏輯(即線the_action = request.form['action']造成的空POST
  2. 400 Bad Request響應爲什麼不會the_action = request.form['action'] or ''the_action = request.form['action'] or 'stub'解決這個問題,在我看來情況就好像是空字符串或'stub'是通過POST發送的?
+0

也許我錯過了什麼,你在哪裏設置你發佈的數據? – chrisz

+1

您提到一個簡單的解決方法是將虛擬數據添加到發佈請求中。如果您試圖從數據請求中提取數據,則需要將數據放入。 – chrisz

+0

@chris我明白爲了將數據提取出來需要先將其發佈出來,這裏有什麼令我困惑的是_(因爲它在我看來,至少)_我沒有真正拉出任何東西,只是將值分配給變量(即'the_action = request.form ['action']')。由於它不影響'action'返回邏輯_(它只是坐在那裏)的任何部分,所以我不明白爲什麼'400 Bad Request'被返回。 –

回答

0

Ba通過chrisanswer to the linked question的sed的意見,我現在看到這個問題,基本上的What is the cause of the Bad Request Error when submitting form in Flask application?


從當前問題解決的問題點重複:

  1. 如果瓶是無法從argsform字典中找到任何密鑰,則會引發HTTP錯誤(本例中爲400 Bad Request)。無論以任何方式獲取密鑰影響應用的邏輯(即僅將其分配給變量the_action = request.form['action']將導致HTTP錯誤,如果action密鑰不存在於form中)。

這是由Sean Vieira總結了了評論linked question:當它無法找到在指定參數和形式字典的關鍵

瓶引發的HTTP錯誤。

  • the_action = request.form['action'] or ''the_action = request.form['action'] or 'stub'是不夠的,因爲瓶將嘗試在request.form['action']獲取不存在的鍵,未能因爲它是不存在和所得到400 Bad Request,前,將得到到or。這就是說 - or永遠不會被達到就好像request.form['action']有一個值 - the_action將被分配到這個值,否則將返回400 Bad Request
  • 爲了避免這種情況 - 應該使用字典的get()方法,同時傳遞一個默認值。所以the_action = request.form['action'] or 'stub'變成the_action = request.form.get('action', 'stub')。這樣空的POST不會導致400 Bad Request錯誤。

    相關問題