使用 WTForms 中的数据填充 App Engine NDB 实体

Populate an App Engine NDB entity with data from WTForms

我正在寻找一种更优雅的方式来从 WTForms 模型填充 App Engine 数据存储区实体,而无需一次为每个属性分配一个属性。

我记得看到 getattr() 做过类似的事情。

编辑个人资料页面的 WTForm 模型,如下所示:

class EditProfile(Form):
    first_name = StringField('First Name')
    last_name = StringField('Last Name')
    [...]

NDB 用户模型:

class User(ndb.Model):
    first_name = ndb.StringProperty()
    last_name = ndb.StringProperty()
    [...]

注意:两个模型的所有属性名称相同。

编辑个人资料页面的请求处理程序:

@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfile()

    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.get_by_id(session.get('user_id'))

            ???

            user.put()

类似...:

for field in dir(form):
    if field.startswith('_'): continue  # skip private stuff
    if not user.hasattr(field): continue  # skip non-corresponding stuff
    value = getattr(form, field)
    setattr(user, field, value)

可能存在一些微妙之处,例如关于类型(需要对某些字段进行类型转换)或什至更高级的类型(也许我们需要使用 User.hasattr,即在 class 上,而不是实例),但对于在两种不同类型的 class 实例之间转录同名、类型兼容的字段来说,这是一个很好的起点。

使用populate_obj方法。

Populates the attributes of the passed obj with data from the form’s fields.

form.populate_obj(user)
user.put()