首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flask-SQLAlchemy更改不会持久

Flask-SQLAlchemy更改不会持久
EN

Stack Overflow用户
提问于 2017-07-10 16:52:32
回答 1查看 620关注 0票数 2

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

以下是视图的代码:

代码语言:javascript
复制
@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(),试图解决这个问题,但这并不起作用。

更改(记录的食物)存储在此处:

代码语言:javascript
复制
@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"))

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

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-05 05:42:46

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

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

代码语言:javascript
复制
@app.route('/')
def home():
    '''homepage for application'''

    db.session.commit()
    ...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45007620

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档