解決 "OperationalError: (sqlite3.OperationalError) no such table: ..."問題


參考:flask/sqlalchemy - OperationalError: (sqlite3.OperationalError) no such table

在用Flask寫一個簡單的py文件,做一個表單時,發現在login界面登陸的時候,出現:

OperationalError: (sqlite3.OperationalError) no such table: ...

錯誤,這個問題肯定是與數據庫有關的;於是review了一下代碼,關於數據庫ORM的聲明類Switches如下:

class Switches(db.Model):
        __tablename__ = 'Switches'
        sid = db.Column(db.Integer, primary_key=True)
        sname = db.Column(db.String, unique=True, index=True)
        #sprice = db.Column(db.Integer)

        def __repr__(self):
                print('<Switch_id %d>' % id)

兩列Column,一個主key叫做sid,外加一個屬性sname,沒有問題;也排除了app.config的問題,那么就是視圖函數中的問題了。

但是看上去也沒有問題:

@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        sw = Switches.query.filter_by(sname=form.name.data).first() # filter the DB
        if sw is None:
            sw = sw(sname=form.name.data)
            db.session.add(sw)
            session['known'] = False
        else:
            session['known'] = True
        session['name'] = form.name.data
        return redirect(url_for('myindex'))
    return render_template('myindex.html', form=form, name=session.get('name'),
                           known=session.get('known', False))

邏輯語句if內是對表單的具體操作,在Swicthes數據庫中找名字為輸入數據的tuple,然后進行相關操作。

於是乎求助搜索引擎,在參考的那篇文章中回答者給出了這樣的解釋:

You're supposed to initialize/create the tables first. Please read the Creating the Database article in the official Flask documentation:

    Such systems need a schema that tells them how to store that information. So before starting the server for the first time it’s important to create that schema.

Here's Flask's example of using a schema SQL script to create the database, tables, etc:

sqlite3 /tmp/flaskr.db < schema.sql

The recommended way is to use db.create_all() within your app. For example, see: https://github.com/hypatia-software-org/staticfuzz/blob/master/staticfuzz.py#L391

大意是數據庫沒有創建這張表,一個推薦的解決方法是加入db.create_all()語句來創建表。

2017.3.30


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM