Brumor
Brumor

Reputation: 95

Flask : Data not saved on server restart/close

I just started learning to develop on Flask (through the 'fullstack' course on Udacity).

But I was wondering, is it normal that when I restart/close my server all the data I had changed from my "website" while the server was previously up, is gone? (I don't know if I clearly explained the problem).

If yes, how to make it so that the data is saved in the database even if I close the server?

this is an example of what the code looks like:

from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem


app = Flask(__name__)
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()


(...)


@app.route('/restaurants/<int:restaurant_id>/new', methods=['GET', 'POST'])
def newMenuItem(restaurant_id):

    if request.method == 'POST':

        newItem = MenuItem(name=request.form['name'], description=request.form['description'], price=request.form['price'], course=request.form['course'], restaurant_id=restaurant_id)
        session.add(newItem)
        session.commit
        flash("new menu item created !")

        return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))

    else:

        return render_template('newmenuitem.html', restaurant_id=restaurant_id)


(...)


if __name__ == '__main__':
    app.secret_key = 'super_secret_key'
    app.debug = True
    app.run(host = '0.0.0.0', port=5000)

Upvotes: 1

Views: 485

Answers (1)

Maarten
Maarten

Reputation: 492

Just copying my comment into an answer. If this is working code you posted try using session.commit() with he brackets. Right now you never call commit and nothing will be stored in the database.

Upvotes: 1

Related Questions