我正在使用flask和flask-mysqldb 每次我要创建或执行sql查询时,光标都应在烧瓶路径内 我想在其他功能而不是在路线中使用光标 我也想定义一个光标,所以我不必在每个路径中键入相同的代码 这是我的代码:
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
import yaml
import json
app = Flask(__name__)
# config the database connection
db = yaml.safe_load(open('db.yaml'))
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASSWORD'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
mysql = MySQL(app)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# get the inputs from the form
user_details = request.form
# the key value is from the html name attriput
name = user_details['name']
email = user_details['email']
cur = mysql.connection.cursor()
cur.execute(
" INSERT INTO users(name,email ) VALUES(%s, %s)", (name, email))
mysql.connection.commit()
cur.close()
return 'success'
return render_template('index.html')
@app.route('/users')
def users():
cur = mysql.connection.cursor()
result_value = cur.execute(" SELECT * FROM users ")
if result_value > 0:
user_details = cur.fetchall()
return render_template('users.html', user_details=user_details)
#convert users data to json file
def json_conv():
cur = mysql.connection.cursor()
cur.execute("SHOW GLOBAL STATUS")
mysql.commit()
rs = cur.fetchall()
result = dict(rs)
with open('users.json', 'w') as f:
json.dump(result, f)
json_conv()
if __name__ == '__main__':
app.run(debug=True)
注意:如果我运行该功能,则会弹出此错误:
Traceback (most recent call last):
File "app.py", line 74, in <module>
json_conv()
File "app.py", line 64, in json_conv
cur = mysql.connection.cursor()
AttributeError: 'NoneType' object has no attribute 'cursor'