đây là database.py tôiBình làm thế nào để bạn sử dụng sqlalchemy declaratively với init_db()?
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)
và đây là 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)
Tôi nhận thấy một vài điều kỳ lạ của tôi:
- Khi tôi làm
python backend.py
Tôi nhìn thấy các bảng đang được tạo hai lần. Các câu lệnh tạo bảng giống nhau được thực thi - Khi tôi truy cập '/', tôi nhận được lỗi sau ngay cả khi tôi chắc chắn 100% rằng các bảng đã được tạo. Tại sao?
cursor.execute(statement, parameters) OperationalError: (OperationalError) no such table: users u'INSERT INTO users DEFAULT VALUES'()
Bạn cũng có thể đăng mã mô hình của mình không? Không chắc chính xác bạn đang cố gắng làm gì ở đây. Nói chung, bạn nên gọi tạo cơ sở dữ liệu (init_db) chỉ một lần. Tôi đề nghị ít nhất, lấy nó ra khỏi backend.py và chỉ gọi database.py một lần trước đây. – codegeek