0

我在使用光标从 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")  

有任何想法吗?我是烧瓶的新手。

4

1 回答 1

0

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

init_db()
app.run(debug=True)

需要反转为

app.run(debug=True)
init_db()

某种程度上来说。

于 2012-11-16T02:15:29.317 回答