Flask如何使用init_db()以声明方式使用sqlalchemy?

dis*_*dng 6 python sqlalchemy flask

这是我的database.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)
Run Code Online (Sandbox Code Playgroud)

这是我的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)
Run Code Online (Sandbox Code Playgroud)

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

  1. 当我这样做时,python backend.py我看到表被创建两次.执行相同的create table语句
  2. 当我访问'/'时,即使我100%确定已创建表,我也会收到以下错误.为什么?

cursor.execute(语句,参数)OperationalError:(OperationalError)没有这样的表:users u'INSERT INTO users DEFAULT VALUES'()

Sea*_*ira 9

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

至于为什么你看到创建表的两倍-默认运行与重新加载每次你改变你的代码时,服务器瓶在调试模式.为了在启动时执行它会生成一个实际运行服务器的新进程 - 因此init_db在启动服务器之前调用您的函数,然后在服务器创建子进程来为请求提供服务时再次调用它.