【问题标题】:Flask-SQLAlchemy changes don't persistFlask-SQLAlchemy 更改不会持续存在
【发布时间】:2017-07-10 08:52:31
【问题描述】:

我正在制作一个 Web 应用程序,其中用户操作会影响一些条形图(见下面的 gif)。有时,更改不会保存。当我重新加载页面时,会显示更改的条形图(表明用户的操作已保存)。当我再次重新加载页面时,有时会显示更新的条形图和相应的列表。其他时候,他们不是。

这是视图的代码:

@app.route('/')
def home():
    '''homepage for application'''

    # redirect users who go to home page but aren't logged in
    if not current_user.is_authenticated:
        return redirect(url_for("landing"))

    # reset the session
    db.session.flush()

    # get most recent entered weight
    try:
        last_weight = WeightEntry.query.filter_by(user_id = current_user.user_id).order_by(WeightEntry.date)[-1]
    except IndexError:
        return error("No weight recorded. Please contact support.")

    return render_template("home.html",
                            today= Today(current_user.user_id),
                            foods = [food for food in FoodEntry.query.filter_by(user_id=current_user.user_id).all() if food.is_today() == True],
                            options =  sorted(Food.query.filter(Food.user_id==current_user.user_id).all(), key=lambda x: x.name),
                            last_weight = last_weight)

我添加了db.session.flush() 以尝试解决问题,但没有奏效。

更改(记录的食物)存储在这里:

@app.route("/log_food", methods=["POST", "GET"])
@login_required
def log_food():
    # add foods given by the user
    if request.method == "POST":
        for food in request.form.getlist("logged_food"):
            try:
                added_food = Food.query.filter_by(user_id=current_user.user_id, name=food).first()
                x = FoodEntry(
                    food_id = added_food.food_id,
                    user_id = current_user.user_id)
                db.session.add(x)
                db.session.commit()
            except:
                return error("Unable to log food.")

        return redirect(url_for("home"))

如果能得到任何帮助,我将不胜感激。

谢谢!

【问题讨论】:

  • 请添加保存更改的代码,以及引擎配置

标签: python flask sqlalchemy flask-sqlalchemy


【解决方案1】:

我通过将db.session.commit() 添加到页面函数来修复它。

例如,对于主页:我做了:

@app.route('/')
def home():
    '''homepage for application'''

    db.session.commit()
    ...

【讨论】:

  • 你已经在问题中有那行代码,有什么区别?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 2016-04-13
  • 2017-02-08
  • 1970-01-01
  • 2014-05-27
相关资源
最近更新 更多