2014-02-10 345 views
4

我的應用程序中有一個受保護的視圖,它只接受POST請求。燒瓶 - login_required +下一個url參數

@app.route("/booking", methods=("POST",)) 
@login_required 
def booking(): 
    arg1 = request.form.get("arg1") 
    arg2 = request.form.get("arg2") 

當未經授權的用戶試圖訪問這個觀點,我希望他們能夠 登錄,然後被重定向到這裏。

現在,我的登錄視圖看起來是這樣的:

@app.route("/login", methods=("GET", "POST")) 
@login_required 
def login(): 
    do_login() 
    return redirect(request.args.get('next') or url_for('home')) 

那麼最終發生的是一個POST請求/預約(這是 「下一個」參數),我得到不被允許的錯誤。

問題是login()發出GET請求來預約()。我可以通過 解決這個問題,但我不確定如何從/ booking檢索原始POST 表單參數?任何想法來解決這個問題?

+0

如果你問如何讓這個重定向將用戶重定向到回'/ booking'作爲POST與原POST的身體,你不能這樣做,因爲HTTP的一部分。查看[這個問題]的答案(http://stackoverflow.com/questions/46582/response-redirect-with-post-instead-of-get)爲什麼。 HTTP重定向使用GET方法。這個問題是關於ASP.NET的,但答案總的來說是關於HTTP的。 –

+0

謝謝,我很高興做出重定向的GET請求,但我不確定如何保留原始POST請求的正文。 – signalseeker

+2

任何你想要的方式。當然,你不能繼續使用login_required裝飾器,因爲它假設你忘記了用戶發送的任何東西。您需要將您的視圖更改爲(如果用戶未登錄),請保存數據(在會話或數據庫中以識別用戶會話的方式),然後在用戶登錄後查看是否有任何「保存」的數據。如果是這樣,可以將它們轉發到屏幕上顯示「您是否想繼續此操作」,並使用可以POST的形式並從該數據繼續該過程。 –

回答

-1

爲什麼你只能在預訂視圖中使用POST?您可能正在渲染一個也應該允許GET的表單。

@app.route("/booking", methods=['GET','POST']) 
@login_required 
def booking(): 
    # render the form. something like 
    form = BookingForm() 

    # Check if POST 
    if request.method == 'POST': 
     # process the form now and do whatever you need. 
     return redirect(url_for('index')) 

    # code below will run if not POST. You should render the template here 
    return render_templte('booking.html')