Flask - SQLAlchemy OperationalError

时间:2014-03-09 03:02:09

标签: python flask flask-sqlalchemy operationalerror

我遇到了以下错误:

sqlalchemy.exc.OperationalError
OperationalError: (OperationalError) no such table: user u'SELECT user.id AS user_id, user.name AS user_name, user.password AS user_password \nFROM user \nWHERE user.id = ?' (1,)

我不知道如何调试这个,但我认为它必须要来,因为它没有加载我使用models.py文件生成的db文件。我已经加载了这个db文件,并确保users表存在,并且它确实存在数据,但我无法弄清楚如何将我的flask应用程序连接到数据库。

这是我之前运行的models.py来生成表格(我没有在其上面加上声明):

from datetime import datetime
import os
from sqlalchemy import Column, ForeignKey
from sqlalchemy import Boolean, DateTime, Integer, String, Text
from sqlalchemy.orm import relationship, synonym, backref

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


""" User """
class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String(200))
    password = Column(String(100))

    def __init__(self, name, password):
        self.name = name
        self.password = password

    def __repr__(self):
        return '<User %r>' % self.name
if __name__ == '__main__':
    from datetime import timedelta

    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker

    PWD = os.path.abspath(os.curdir)

    engine = create_engine('sqlite:///{}/arkaios.db'.format(PWD), echo=True)

    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()

    # Add a sample user
    user = User(name='Philip House', password="test")
    session.add(user)
    session.commit()

这是app.py:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask import render_template

from arkaios.models import Base, User
from arkaios import config

app = Flask(__name__)
app.config.from_object(config)

db = SQLAlchemy(app)
db.Model = Base

@app.route('/admin/large-group')
def largeGroupOverview():
    user = db.session.query(User).filter_by(id=1)
    return render_template('largegroup/overview.html', user=user)

@app.route('/admin/large-group/<int:event_id>')
def largeGroupAttendance(event_id):
    return render_template('largegroup/attendance.html')

@app.route('/focus')
def largegroup():
    return 'Focus work'

最后,app.py指的是下面的config.py:

import os
PWD = os.path.abspath(os.curdir)

DEBUG=True
SQLALCHEMY_DATABASE_URI = 'sqlite:///{}/arkaios.db'.format(PWD)
SECRET_KEY = 'thisissecret'
SESSION_PROTECTION = 'strong'

如果需要,我也可以发布堆栈跟踪!从概念上讲,我一直在思考如何连接Flask和SQLAlchemy,但我无法理解它。

感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

您是否在python models.py app之前运行python app.py来创建数据库?从if __name__ == "__main__"导入文件时,app.py将阻止该部分代码运行。

我还要确保db使用sqlite3有效并运行.tables命令。