Flask SQLAlchemy Database Dropping what has been commited



I have a simple Flask website using SQLAlchemy Database.The database works well I query all data on my python terminal and all is properly initialized.
I have hosted the application on Heroku and I can write blogs post events and also other updates from the admin panel.
Every time I do a new post it is created but over time I find the entire blogs and and events deleted. Users created with accounts still remain therefore the entire database is not droped.

Models.py Blogs

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    content1 = db.Column(db.Text, nullable=False)
    content2 = db.Column(db.Text, nullable=False)
    content3 = db.Column(db.Text, nullable=False)
    content4 = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    image_file = db.Column(db.String(20), nullable=False)

Models.py Events

class Event(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(20), unique=True, nullable=False)
    desc = db.Column(db.String(120), nullable=False)
    link = db.Column(db.String(120), unique=True, nullable=False)
    edate = db.Column(db.String(120), nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    def __repr__(self) -> str:
        return f"Event('{self.id}','{self.desc}','{self.image_file}')"

I later initialize what has been posted using

{% extends "Admin/layout.html" %}
{% block content %}
  <article class="media content-section">
    <img class="rounded-circle article-img" src="{{ url_for('static', filename='profile_pics/' + post.author.image_file) }}">
    <div class="media-body">
      <div class="article-metadata">
        <a class="mr-2" href="{{ url_for('user_posts', username=post.author.username) }}">{{ post.author.username }}</a>
        <small class="text-muted">{{ post.date_posted.strftime('%Y-%m-%d') }}</small>
        {% if post.author == current_user %}
            <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{{ url_for('update_post', post_id=post.id) }}">Update</a>
            <button type="button" class="btn btn-danger btn-sm m-1" data-toggle="modal" data-target="#deleteModal">Delete</button>
        {% endif %}
      <h2 class="article-title">{{ post.title }}</h2>
      <p class="article-content">{{ post.content }}</p>
  <!-- Modal -->
  <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="deleteModalLabel">Delete Post?</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <form action="{{ url_for('delete_post', post_id=post.id) }}" method="POST">
            <input class="btn btn-danger" type="submit" value="Delete">
{% endblock content %}

and call from the database using

<!-- Blog goes here -->
<div class="container">
  <section class="my-5">

    <!-- Section heading -->
    <div class="section-title">
      <h2 data-aos="fade-in">Recent Post</h2>
    <!-- Section description -->
    <p class="text-center dark-grey-text w-responsive mx-auto mb-5"> Visit this column for insights on good financial planning and investing activities  </p>
    <!-- Grid row -->

    {% for post in posts.items %}
     <div class="container ">
      <div class="row mt-4">

        <!-- Grid column -->
        <div class="col-lg-5">
            <!-- Featured image -->
            <div class="view overlay rounded z-depth-2 mb-lg-0 mb-4">
              <img src="{{url_for('static',filename='Admin/profile_pics/')}}{{ post.image_file }}" class="d-block w-100" alt="..."/>
                  <div class="mask rgba-white-slight"></div>
        <!-- Grid column -->
        <!-- Grid column -->
        <div class="col-lg-7">
            <!-- Post title -->
            <h3 class="font-weight-bold mb-3"><strong>{{ post.title }}</strong></h3>
            <!-- Excerpt -->
            <p>{{ post.content[:222]|safe }}</p>
            <!-- Post data -->
            <p>by <a><strong>{{ post.author.username }}</strong></a>, {{ post.date_posted.strftime('%d-%m-%Y') }}</p>
            <!-- Read more button -->
            <a href="{{ url_for('post', post_id=post.id) }}" class="btn btn-outline-info btn-md">Read more</a>
        <!-- Grid column -->
    <!-- Grid row -->
    <hr class="my-5">
    {% endfor %}

    {% for page_num in posts.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
      {% if page_num %}
        {% if posts.page == page_num %}
          <a class="btn btn-info mb-4 text-center" href="{{ url_for('blog', page=page_num) }}">{{ page_num }}</a>
        {% else %}
          <a class="btn btn-outline-info mb-4 text-center" href="{{ url_for('blog', page=page_num) }}">{{ page_num }}</a>
        {% endif %}
      {% else %}
      {% endif %}
    {% endfor %}


import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from flask_mdeditor import MDEditor

app = Flask(__name__)
app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
mdeditor = MDEditor(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
app.config['MAIL_SERVER'] = ''
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False

app.config['MAIL_USERNAME'] = ''
app.config['MAIL_PASSWORD'] = ''
mail = Mail(app)

from App import routes

Kindly assist.


First of all what kind of heroku dyno do you have? By default you have the free version.
The free version uses the free dyno.
This means that after 30 mins of inactivity the dyno will go to sleep, Until a user get back on. When your dyno goes to sleep the server shuts down. You may have noticed this if you see that your website sometimes take 20 secs to load. Next time you reload the website it will restore the database that you initially pushed.

I also struggle with this problem.
I have recently upgraded Dyno to the hobby dyno. Although my website will never sleep it still has a daily restart that also restores the original database.

I am still looking for this fix.


Answered By – Constantine Westerink

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More