2014-11-25 58 views
0

我正在使用Flask使用Blueprint建立一個實驗性應用程序。這裏是我的項目的結構:使用SQLAlchemy設置瓶頸Blueprint會產生UnboundExecutionError

-myproject/ 
requirements.txt 
run.py 
-apps/ 
    -static/ 
    -template/ 
    -database/ 
    __init__.py 
    views.py 
    model.py 
    auth.py 
    message.py 

我在初始化初始化的.py我的應用程序,使用藍圖整合應用程序的其他部分。

app = Flask(__name__) 
from .views import views 
from .model import model, db 
from .auth import auth, login_manager 

db.init_app(app) 

app.register_blueprint(views) 
app.register_blueprint(model) 
app.register_blueprint(auth) 

然後在views.py

from flask import Flask, request, redirect, render_template, session, g, url_for, Blueprint 
views = Blueprint('views', __name__) 
from sqlalchemy.orm import scoped_session, relation, sessionmaker 

# ORM Session 
orm_session = scoped_session(sessionmaker()) 
@views.route('/courses') 
def courses(): 
    courses = orm_session.query(Course).order_by('-id') 
    return render_template('courses.html', courses=courses) 

Course類在model.py定義:

class Course(db.Model): 
    __tablename__ = 'course' 
    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.String(255), nullable=False) 
    subjects = db.relationship('Subject', secondary='course_subject_link') 
    students = db.relationship('Student', secondary='course_student_link') 
    active = db.Column(db.Boolean) 
    def __repr__(self): 
     return "<{0}:{1.name}:{1.subjects!r}:{1.students!r}>".format(Course, self) 

在模板文件夾中,我已經把類似的東西在模板文件{% for course in courses %}{% set active_page = "courses" %}。當我運行應用程序,它給了我這個錯誤:

UnboundExecutionError: Could not locate a bind configured on mapper Mapper|Course|course, SQL expression or this Session 

我以前沒有使用藍圖,所使用的應用能夠運行。但在使用Blueprint之後,這些網址似乎被破壞了。我怎樣才能解決這個問題?

回答

0

我知道問題出在哪裏。

從錯誤消息中的提示我猜我忘了create_engine並將引擎傳遞給會話製作者使用bind=engine

這是我在views.py改變了代碼:

from os.path import join, dirname 
_cwd = dirname(__file__) 
engine = create_engine('sqlite:///' + join(_cwd, 'database/courses.sqlite')) 
Session = scoped_session(sessionmaker(autocommit=False, 
             autoflush=False, 
             bind=engine)) 
orm_session = Session() 

這裏database/courses.sqlite是我的數據庫文件的位置。

+0

我建議您編輯答案以更好地描述您的解決方案,然後接受它 – 2014-11-25 13:54:55