0

I created a movie database and added a new entry in this database. At first run, code created two identical entries in database and I don't know why.

code:

from flask import Flask, render_template, redirect, url_for, request
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///day64.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

Bootstrap(app)

db = SQLAlchemy(app)

class Movie(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(250), nullable=False)
    year = db.Column(db.Integer, nullable=False)
    description = db.Column(db.String(250), nullable=False)
    rating = db.Column(db.Float, nullable=False)
    ranking = db.Column(db.Integer, nullable=False)
    review = db.Column(db.String(250), nullable=False)
    img_url = db.Column(db.String(250), nullable=False)
db.create_all()

@app.route("/")
def home():
    return render_template("index.html")

if __name__ == '__main__':
    new_movie = Movie(
        title="Phone Booth",
        year=2002,
        description="Publicist Stuart Shepard.",
        rating=7.3,
        ranking=10,
        review="My favourite.",
        img_url="https://image.tmdb.org/t/p/w500/tjrX2oWRCM3Tvarz38zlZM7Uc10.jpg"
    )
    db.session.add(new_movie)
    db.session.commit()
    app.run(debug=True)

database entries: Movie table

waxier358
  • 5
  • 2

1 Answers1

0

It looks like this is happening because of the way flask starts up in debug mode. If you add use_reloader=False to app.run that would resolve your issue, but then you wouldn't have live reloading.

app.run(debug=True, use_reloader=False)

It might be best to refactor this and move the movie creation out of the init.

Related to other stack overflow question/answer here