python - Flask 如何通过 init_db() 声明性地使用 sqlalchemy?

标签 python sqlalchemy flask

这是我的数据库.py

engine = create_engine('sqlite:///:memory:', echo=True)
session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = session.query_property()

def init_db():
  # import all modules here that might define models so that
  # they will be registered properly on the metadata.  Otherwise
  # you will have to import them first before calling init_db()
  import models
  Base.metadata.create_all(engine)

这是我的 backend.py

from flask import Flask, session, g, request, render_template
from database import init_db, session
from models import *

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

# Serve static file during debug 
if app.config['DEBUG']:
  from werkzeug import SharedDataMiddleware
  import os
  app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
    '/': os.path.join(os.path.dirname(__file__), 'static')
  })

@app.route('/')
def foo():
  session.add(User())
  session.commit()
  return "NOTHING HERE."

if __name__ == "__main__":
  init_db()
  app.run(port=8888)

我注意到一些奇怪的事情:

  1. 当我执行 python backend.py 时,我看到表被创建了两次。执行同样的建表语句
  2. 当我访问“/”时,即使我 100% 确定表已创建,我仍收到以下错误。为什么?

cursor.execute(statement, parameters) OperationalError: (OperationalError) no such table: users u'INSERT INTO users DEFAULT VALUES' ()

最佳答案

当您在内存中创建 SQLite 数据库时,它只能由创建它的特定线程访问 - 将 create_engine('sqlite:///:memory:') 更改为 create_engine( 'sqlite:////some/file/path/db.sqlite' 并且您的表将存在。

至于为什么您会看到创建了两次表 - 默认情况下,Flask 在 Debug模式下与服务器一起运行,该服务器在您每次更改代码时都会重新加载。为了在启动时生成一个实际运行服务器的新进程 - 因此在启动服务器之前调用 init_db 函数,然后在服务器创建子进程时再次调用它服务请求。

关于python - Flask 如何通过 init_db() 声明性地使用 sqlalchemy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11860804/

相关文章:

python - 如何忽略 CSV 文件中的第一个值?

python - 带音频释放的计时器

python - 如何在 3 个表上的 SQLAlchemy 中执行 JOIN,其中一个在其他两个表之间进行映射?

javascript - Flask:资源被解释为样式表但以 MIME 类型文本/html 传输

python - 蓝图的蓝图(Flask)

python - 使用 Flask-Login 注销特定用户

python - 所有任务的单个工作线程还是多个特定的工作线程?

python - 为什么通过 Web 服务 API 调用 Azure ML 分类模型不返回概率分数?

python - Elixir 过时了吗?

python - SQLAlchemy 模型循环导入