0

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

Fidel Castro
  • 277
  • 2
  • 4
  • 10

2 Answers2

0

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()])
dirn
  • 19,454
  • 5
  • 69
  • 74
0

This is what I do in my test program to connect to mariadb or mysql and it's working:

@main.route('/mariadb')
def mariab():
    print current_app.config['MYSQL_USER']
    print current_app.config['MYSQL_DB']
    cur = mysql.connection.cursor()
    cur.execute('SELECT titlle from cards ORDER BY id desc')
    entries = cur.fetchall()
    print entries
    return render_template('mariadb.html',
                           database=current_app.config['MYSQL_DB'],
                           user=current_app.config['MYSQL_USER'],
                           entries=entries)