SQLAlchemy 2.0 无法读取 SQLite 表?

huangapple go评论123阅读模式
英文:

SQLAlchemy 2.0 can't read SQLite table?

问题

我已经测试了这个脚本中的SQLite数据库,它可以正常工作:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text

db = SQLAlchemy()
app = Flask(__name__)
db_name = 'sockmarket.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_name
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db.init_app(app)

@app.route('/')
def testdb():
    try:
        db.session.query(text('1')).from_statement(text('SELECT 1')).all()
        return '<h1>It works.</h1>'
    except Exception as e:
        error_text = "<p>The error:<br>" + str(e) + "</p>"
        hed = '<h1>Something is broken.</h1>'
        return hed + error_text

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

然后,我尝试使用新的SQLAlchemy选择命令,但它失败了:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text

db = SQLAlchemy()
app = Flask(__name__)
db_name = 'sockmarket.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_name
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db.init_app(app)

class Sock(db.Model):
    __tablename__ = 'socks'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    style = db.Column(db.String)
    color = db.Column(db.String)
    quantity = db.Column(db.Integer)
    price = db.Column(db.Float)
    updated = db.Column(db.String)

@app.route('/')
def index():
    try:
        socks = db.session.execute(db.select(Sock)
        .filter_by(style='mini')
        .order_by(Sock.name)).scalars()
        
        sock_text = '<ul>'
        for sock in socks:
            sock_text += '<li>' + sock.name + ', ' + sock.color + '</li>'
        sock_text += '</ul>'
        return sock_text
    except Exception as e:
        error_text = "<p>The error:<br>" + str(e) + "</p>"
        hed = '<h1>Something is broken.</h1>'
        return hed + error_text

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

我已经检查了模型多次。这个脚本生成了<ul>标签,但标签之间没有任何内容。它没有抛出错误。我还在Python解释器中运行了SQLAlchemy命令,以验证数据库存在且表可读取。这是一个已经存在的数据库和表。此外,这个设置在几个月前的SQLAlchemy旧版本中完美运行。同样的模型。旧版本中的选择语句如下:

socks = Sock.query.filter_by(style='mini').order_by(Sock.name).all()
英文:

I've tested the SQLite database with this script, and it works:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text

db = SQLAlchemy()
app = Flask(__name__)
db_name = &#39;sockmarket.db&#39;
app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;sqlite:///&#39; + db_name
app.config[&#39;SQLALCHEMY_TRACK_MODIFICATIONS&#39;] = True
db.init_app(app)

@app.route(&#39;/&#39;)
def testdb():
    try:
        db.session.query(text(&#39;1&#39;)).from_statement(text(&#39;SELECT 1&#39;)).all()
        return &#39;&lt;h1&gt;It works.&lt;/h1&gt;&#39;
    except Exception as e:
        error_text = &quot;&lt;p&gt;The error:&lt;br&gt;&quot; + str(e) + &quot;&lt;/p&gt;&quot;
        hed = &#39;&lt;h1&gt;Something is broken.&lt;/h1&gt;&#39;
        return hed + error_text

if __name__ == &#39;__main__&#39;:
    app.run(debug=True)

Then I try to use the new SQLAlchemy select command, and it fails:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text

db = SQLAlchemy()
app = Flask(__name__)
db_name = &#39;sockmarket.db&#39;
app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;sqlite:///&#39; + db_name
app.config[&#39;SQLALCHEMY_TRACK_MODIFICATIONS&#39;] = True
db.init_app(app)

class Sock(db.Model):
    __tablename__ = &#39;socks&#39;
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    style = db.Column(db.String)
    color = db.Column(db.String)
    quantity = db.Column(db.Integer)
    price = db.Column(db.Float)
    updated = db.Column(db.String)

@app.route(&#39;/&#39;)
def index():
    try:
        socks = db.session.execute(db.select(Sock)
        .filter_by(style=&#39;mini&#39;)
        .order_by(Sock.name)).scalars()
        
        sock_text = &#39;&lt;ul&gt;&#39;
        for sock in socks:
            sock_text += &#39;&lt;li&gt;&#39; + sock.name + &#39;, &#39; + sock.color + &#39;&lt;/li&gt;&#39;
        sock_text += &#39;&lt;/ul&gt;&#39;
        return sock_text
    except Exception as e:
        # e holds description of the error
        error_text = &quot;&lt;p&gt;The error:&lt;br&gt;&quot; + str(e) + &quot;&lt;/p&gt;&quot;
        hed = &#39;&lt;h1&gt;Something is broken.&lt;/h1&gt;&#39;
        return hed + error_text

if __name__ == &#39;__main__&#39;:
    # app.run(debug=True)

I've check the Model again and again. The script writes the UL tags but nothing in between them. It does not throw an error. I also ran SQLAlchemy commands in the Python interpreter to verify that, yes, the db is there and the table is readable. This is an already-existing database and table. Also, this setup worked perfectly with the old version of SQLAlchemy several months ago. Same Model. The select statement in the old version was this:

socks = Sock.query.filter_by(style=&#39;mini&#39;).order_by(Sock.name).all()

答案1

得分: 1

解决方案:尽管第一个脚本在没有路径的情况下运行正常,而第二个脚本曾经在没有路径的情况下运行正常,但现在第二个脚本需要为SQLite数据库指定路径 - 即使.db文件与此Python脚本在同一目录中,并且该目录中也有一个__init__.py文件。

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os.path

db = SQLAlchemy()
app = Flask(__name__)
db_name = 'sockmarket.db'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, db_name)

希望这可以帮助其他人节省我花费的时间。

英文:

Solution: Even though the first script works fine without a path, and the second script used to work fine without a path, it turns out that now the second script requires a path for the SQLite database - even though the .db file is in the same directory with this Python script and there is an __init__.py file in the dir as well.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os.path

db = SQLAlchemy()
app = Flask(__name__)
db_name = &#39;sockmarket.db&#39;
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, db_name)

I hope this saves someone else the hours it took me to solve it.

huangapple
  • 本文由 发表于 2023年4月11日 05:14:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定