2017-10-29 2 views
1

私はBlueprint内にいくつかのビュー機能を持っています。彼らは、次のようなものです:フラスコテストクライアントがメソッドで間違ったビュー機能を取得する

@app.route('/panel/<int:id>', methods=['GET']) 
def get_panel(id): 
    panel = Panel.query.filter_by(id=id).first() 
    return jsonify(panel.getJson()) 


@app.route('/panel/<int:id>', methods=['POST']) 
def post_panel(id): 
    panel = request.get_json().get('panel') 
    # code for saving the data in database 
    return jsonify({"message": "Saved in database"}) 

私はビュー機能post_panel()をテストしようとすると、それは何らかの形でget_panel()をピックアップ。両方の機能のURLが同じで、私はそれが問題の原因だと思う。

周囲はありますか?

答えて

1

GETとPOSTを別々に処理する2つの関数を宣言することはできません。だから、あなたが書くことができ

@app.route('/login', methods=['GET', 'POST']) 
def login(): 
    if request.method == 'POST': 
     do_the_login() 
    else: 
     show_the_login_form() 

:あなたはdocsに、この例で示されたように、1つの機能、 と何をすべきかを決定するための条件、 を使用する必要があります

@app.route('/panel/<int:id>', methods=['GET', 'POST']) 
def handle_panel(id): 
    if request.method == 'POST': 
     return post_panel(id) 
    else: 
     return get_panel(id) 

def get_panel(id): 
    panel = Panel.query.filter_by(id=id).first() 
    return jsonify(panel.getJson()) 

def post_panel(id): 
    panel = request.get_json().get('panel') 
    # code for saving the data in database 
    return jsonify({"message": "Saved in database"}) 
1

これは、同じAPIエンドポイントに対して異なるリクエストタイプを処理する正しい方法ではありません。以下のアプローチを試してください

from flask import request  

@app.route('/panel/<int:id>', methods=['GET', 'POST']) 
    def get_panel(id): 
     if request.method == 'GET': 
      panel = Panel.query.filter_by(id=id).first() 
      return jsonify(panel.getJson()) 

     elif request.method == 'POST':   
      panel = request.get_json().get('panel') 
      # code for saving the data in database 
      return jsonify({"message": "Saved in database"}) 
関連する問題