我是第一次使用Python和Flask。我正在尝试为数据库创建一个简单的查询选择并显示数据。
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()
这是给我的错误:视图函数未返回有效的响应元组。
谢谢
答案 0 :(得分:1)
您可以对响应进行json处理:
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()