-1

I'm working with Python and Flask for the first time. I'm trying to create a simple query select to my database and display the data.


from flask import Flask
from flaskext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'myuser'
app.config['MYSQL_DATABASE_PASSWORD'] = 'mypass'
app.config['MYSQL_DATABASE_DB'] = 'mydb'
app.config['MYSQL_DATABASE_HOST'] = 'my server'
mysql.init_app(app)

@app.route("/")
def hello():
    cursor = mysql.connect().cursor()
    cursor.execute("Select * From Users Where UserID = 215")
    data = cursor.fetchone()
    return data

if __name__ == "__main__":
    app.run()

It is giving me the error: The view function did not return a valid response tuple.

Thanks

myTest532 myTest532
  • 2,091
  • 3
  • 35
  • 78
  • 3
    I believe Flask view functions must either return plain strings, or Response objects. But `fetchone()` returns a tuple, and view functions can't return a tuple. – John Gordon Jul 11 '19 at 20:52

1 Answers1

1

You can jsonify the response:

from flask import Flask
import json
from flaskext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'myuser'
app.config['MYSQL_DATABASE_PASSWORD'] = 'mypass'
app.config['MYSQL_DATABASE_DB'] = 'mydb'
app.config['MYSQL_DATABASE_HOST'] = 'my server'
mysql.init_app(app)

@app.route("/")
def hello():
    cursor = mysql.connect().cursor()
    cursor.execute("Select * From Users Where UserID = 215")
    data = cursor.fetchone()
    return json.dumps(data)

if __name__ == "__main__":
    app.run()
kudeh
  • 883
  • 1
  • 5
  • 16
  • try adding `print(data)` right before `return json.dumps(data)` to see what is returned when the query is executed – kudeh Jul 31 '19 at 21:24