這是我database.pyFlask你如何用init_db()聲明地使用sqlalchemy?
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)
我注意到了幾個奇怪的事情:
- 當我做
python backend.py
我看到創建表兩次。執行相同的create table語句 - 當我訪問'/'時,即使在100%確定表已創建時,也會收到以下錯誤。爲什麼?
cursor.execute(statement, parameters) OperationalError: (OperationalError) no such table: users u'INSERT INTO users DEFAULT VALUES'()
你可以發佈你的模型代碼嗎?不知道你到底在做什麼。一般來說,您應該只調用一次數據庫創建(init_db)。我建議至少從backend.py中取出它,然後只調用一次database.py。 – codegeek 2012-08-08 14:51:02