一段python(flask)代码,可否写的更优雅或简洁一点?

@bp.route('/settings/<username>', methods=['GET', 'POST'])
@login_required
def settings():
    profile = User.query.get_or_404(username)
    form = SettingsForm()
    if form.validate_on_submit():
        profile.email = form.email.data
        profile.location = form.location.data
        profile.website = form.website.data
        profile.bio = form.bio.data
        profile.twitter = form.twitter.data
        profile.weibo = form.weibo.data
        profile.github = form.github.data
        profile.instagram = form.instagram.data

        db.session.add(profile)
        db.session.commit()

        return redirect(url_for('main.index'))

就是那几行profile.xxx = form.xxx.data

阅读 3.5k
2 个回答

直接上代码:

form.populate_obj(profile)
for k in form.__dict__:
  profile.__dict__[k] = form.__dict__[k].data
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题