当我使用flask-sqlalchemy时,如何设置wtforms-alchemy的会话?

时间:2014-03-12 14:08:02

标签: python flask flask-sqlalchemy flask-wtforms

我在init_app()的应用程序中使用flask-sqlalchemy和init SQLAlchemy(),如下所示:

in config file :

SQLALCHEMY_DATABASE_URI = 'sqlite:///example.db'
---------------------    
in extension file :

from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()
---------------------
in application file: 

#in my application file that generate my app
from ----- import db 

db.init_app(app)

我的模特是:

from -------- import db

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, autoincrement=True , primary_key=True)
    username = db.Column(db.String(50),unique=True)
    password = db.Column(db.String(50))
    email = db.Column(db.String(50),unique=True)

    def __repr__(self):
        return '<User %r>' % self.username

现在当我在form.py中使用wtforms-alchemy时:

from wtforms_alchemy import ModelForm

class UserForm(ModelForm):
    class Meta:
        model = User

我有这个错误:

File "/usr/local/lib/python2.7/dist-packages/wtforms_components/validators.py", line 220, in _check_for_session
raise Exception('Could not obtain SQLAlchemy session.')

Exception: Could not obtain SQLAlchemy session.

我该如何修复这个错误?

1 个答案:

答案 0 :(得分:1)

来自WTForms-Alchemy advanced section

  

为了让WTForms-Alchemy与Flask-WTF合作,您需要以下代码段:

from flask.ext.wtf import Form
from wtforms_alchemy import model_form_factory

ModelForm = model_form_factory(Form)
     

您可以像以前一样使用ModelForm:

class UserForm(ModelForm):
    class Meta:
        model = User

确实依赖User拥有.query个对象;例如您的User模型必须来自db.Model。如果它没有,那么您需要在表单上定义get_session方法

class UserForm(ModelForm):
    class Meta:
        model = User

    def get_session(self):
        return db.session