这是我的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)
这是我的后端.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)
我注意到一些奇怪的事情:
- 当我这样做
python backend.py
时,我看到表被创建了两次。执行相同的创建表语句 - 当我访问“/”时,即使我 100% 确定表已创建,我也会收到以下错误。为什么?
cursor.execute(statement, parameters) OperationalError: (OperationalError) no such table: users u'INSERT INTO users DEFAULT VALUES' ()