-1

I am not able to return a JSON string, although it is possible if I request just one entry.

This works:

@app.route('/incomeexpense/<id>', methods=['GET'])
def handle_incomexpense(id):
    incomeexpense = IncomeExpenseModel.query.get_or_404(id)

    if request.method == 'GET':
            response = {
                    "orderdate": incomeexpense.orderdate,
                    "who": incomeexpense.who,
                    "location": incomeexpense.location,
                    "income": incomeexpense.income,
                    "expense": incomeexpense.expense
            }
            return {"message": "success", "incomeexpense": response}

This does not work:

@app.route('/incomeexpense/all', methods=['GET'])
def handle_incomexpense_all():
    incomeexpense = IncomeExpenseModel.query.all();

    if request.method == 'GET':
            response = {
                    "orderdate": incomeexpense.orderdate,
                    "who": incomeexpense.who,
                    "location": incomeexpense.location,
                    "income": incomeexpense.income,
                    "expense": incomeexpense.expense
            }
            return {"message": "success", "incomeexpense": response}

Here is my model:

class IncomeExpenseModel(db.Model):
    __tablename__ = 'incomeexpense'

    id = db.Column(db.Integer, primary_key=True)
    orderdate = db.Column(db.String())
    who = db.Column(db.String())
    location = db.Column(db.Integer())
    income = db.Column(db.Numeric(16,2), nullable=True)
    expense = db.Column(db.Numeric(16,2), nullable=True)

    def __init__(self, orderdate, who, location, income, expense):
            self.orderdate = orderdate
            self.who = who
            self.location = location
            self.income = income
            self.expense = expense

Maybe someone can tell me how to return a JSON string?

0

1 Answer 1

1

incomeexpense = IncomeExpenseModel.query.all() This line returns list of objects.

If you want to return JSON with one object you can use indexing, like: incomeexpense = IncomeExpenseModel.query.all()[0]

Or If you want to return all of them, prepare response using loop:

responses = []
for incomeexpense in IncomeExpenseModel.query.all():
    responses.append({
        "orderdate": incomeepense.orderdate
        ...
    })
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.