Flask-MySQL - 命令不同步

时间:2012-11-16 01:55:44

标签: python mysql flask

我遇到了使用游标从mysql读取数据并通过烧瓶在HTTP上显示数据的问题。每次我运行这段代码:

import os
from flask import Flask, request, session, url_for, redirect, \
     render_template, abort, g, flash, _app_ctx_stack
from flaskext.mysql import MySQL
from contextlib import closing
from hashlib import md5
from datetime import datetime
import time
import os
from werkzeug import check_password_hash, generate_password_hash
import config

app = Flask(__name__)
mysql = MySQL()

app.config['MYSQL_DATABASE_HOST'] = config.MYSQL_DATABASE_HOST
app.config['MYSQL_DATABASE_PORT'] = config.MYSQL_DATABASE_PORT
app.config['MYSQL_DATABASE_USER'] = config.MYSQL_DATABASE_USER
app.config['MYSQL_DATABASE_PASSWORD'] = config.MYSQL_DATABASE_PASSWORD
app.config['MYSQL_DATABASE_DB'] = config.MYSQL_DATABASE_DB

mysql.init_app(app)

if 'SECRET_KEY' in os.environ:
    app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
else:
    app.config['SECRET_KEY'] = os.urandom(24)

###
# Routing for your application.
###

def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('init.sql') as f:
            db.cursor().execute(f.read())
        db.commit()


def connect_db():
    return mysql.connect()


 if __name__ == '__main__':
    init_db()
    app.run(debug=True)

我得到了这个结果:

(venv)λ fh → λ git master* → python app.py                                              
Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't ru
n this command now") in <bound method Cursor.__del__ of <MySQLdb.cursors.Cursor object a
t 0x10bc3ddd0>> ignored                                                                 
Traceback (most recent call last):                                                      
  File "app.py", line 124, in <module>                                                  
    init_db()                                                                           
  File "app.py", line 38, in init_db                                                    
    db.commit()                                                                         
_mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this com
mand now")  

有什么想法吗?我是烧瓶的新手。

1 个答案:

答案 0 :(得分:-1)

似乎您需要在尝试执行数据库之前启动应用程序,因为您正在通过Flask访问数据库。我对Flask没有经验,所以我不确定如何在启动服务器后访问数据库,但如果你不知道我可以查看。基本上,

init_db()
app.run(debug=True)

需要逆转

app.run(debug=True)
init_db()

以某种方式。