[Python] Return error code and message to API caller

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have a web application that put some data into a database using the SQLAlchemy: if the element does not exist into the table it is added else it doesn't. In both cases it shows a popup message to the user telling if the operation was successful or not using the flash command, so it works fine.

    The problem is that if I do a POST HTTP request to that service using an external device (for example an Android app or a separate Python script) the response returns always status code 200 even if the record exists into the table.

    What I would like to do is:

    1. The user add the record
    2. If the record does not exists it is added into the database and redirect me to the homepage of the website /home
    3. If the record exists return an error code/message to the user so that I can manage that case on client side and redirect to the homepage of the website /home

    Code of the python flask:

    # creating of the model
    class Product(db.Model):
    id = db.Column(db.String(100), primary_key=True)
    total = db.Column(db.Integer())


    # home route
    @app.route('/')
    def home():
    product = Product.query.all()
    return render_template('index.html', products=product)


    # route for adding todos
    @app.route('/add', methods=['POST'])
    def add():
    if request.is_json:
    data = request.get_json()
    else:
    data = request.form

    product = Product(id=data['product_id'], total=data['product_quantity'])
    product_exist = Product.query.filter_by(id=product.id).first()

    if product_exist:
    flash(f"{product.id} already in list", category="error")
    else:
    db.session.add(product)
    db.session.commit()
    flash(f"{product.total} {product.id} added successfully.", category="success")

    return redirect(url_for('home'))

    Continue reading...

Compartilhe esta Página