Search code examples
mysqlpython-3.xflaskflask-mysql

display more than one record with mysql and flask


Im trying to get some content from a table

my code looks like:

@app.route('/')
def home():
    cursor = mysql.connect().cursor()
    cursor.execute("SELECT titlle from cards ORDER BY id desc")
    data = cursor.fetchone()
    return data

but it only shows me one because well... I'm using the fetchone() but when I used the fetchall() it says that there are too many records :/

how can I fix my code to actually display all titles from the table cards


Solution

  • You can't return arbitrary things from endpoints. You need to return response-like objects. That can be either a string, an instance of Response, or a tuple containing the response body, (optionally) the status code, and the headers.

    I'm guessing that you want to use the titles to do something in JavaScript. You probably want to send them in a JSON response. For that, use jsonify.

    from flask import jsonify
    
    # snip
    return jsonify(titles=[row['title'] for row in cursor.fetchall()])