tanjibpa
tanjibpa

Reputation: 127

Flask testing client picking up wrong view function with method

I have some view functions within a Blueprint. They are like following:

@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"})

When I try to test the view function post_panel(), it somehow picks up the get_panel(). As both functions url are same and I think that's what causing the problem.

Is there any way around?

Upvotes: 1

Views: 436

Answers (2)

Priyank Mehta
Priyank Mehta

Reputation: 2513

This is not correct way to handle different request type for same API endpoint. Try below approach

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"})

Upvotes: 1

janos
janos

Reputation: 124724

It's not possible to declare two functions to handle GET and POST separately. You must use one function, and a conditional to decide what to do, as demonstrated in this example in the docs:

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

So you could write:

@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"})

Upvotes: 0

Related Questions