python - Flask SQLAlchemy 数据库删除已提交的内容
问题描述
我有一个使用 SQLAlchemy 数据库的简单 Flask 网站。数据库运行良好,我在 python 终端上查询所有数据,并且所有数据都已正确初始化。我在 Heroku 上托管了该应用程序,我可以在管理面板上写博客帖子事件和其他更新。每次我发布新帖子时都会创建它,但随着时间的推移,我发现整个博客和事件都被删除了。使用帐户创建的用户仍然存在,因此不会删除整个数据库。
Models.py 博客
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 事件
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}')"
我稍后初始化已发布的内容
{% 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 %}
<div>
<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>
</div>
{% endif %}
</div>
<h2 class="article-title">{{ post.title }}</h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
<!-- 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">×</span>
</button>
</div>
<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">
</form>
</div>
</div>
</div>
</div>
{% endblock content %}
并使用从数据库调用
<!-- Blog goes here -->
<div class="container">
<section class="my-5">
<!-- Section heading -->
<div class="section-title">
<h2 data-aos="fade-in">Recent Post</h2>
</div>
<!-- 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="..."/>
<a>
<div class="mask rgba-white-slight"></div>
</a>
</div>
</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>
</div>
<!-- Grid column -->
</div>
</div>
<!-- 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 %}
初始化.py
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
请协助。谢谢
解决方案
您必须使用 Heroku Postgres 数据库。这很容易设置。
按照我使用的本教程进行操作:
https://medium.com/analytics-vidhya/heroku-deploy-your-flask-app-with-a-database-online-d19274a7a749
在本教程中,您最有可能完成了一些步骤。你可以跳过那些。
推荐阅读
- oracle - Oracle:TO_DATE 无法解析 TO_CHAR 的结果
- reactjs - MapDispatchToProps 包括所有动作
- angular - Angular 5+ Material Autocomplete 位置错误
- javascript - NodeJS Ajax 未传递数组,错误:“位置 0 处 JSON 中的意外标记 u”
- reactjs - 如何在 Jest/Enzyme 中断言元素“数组属性”?
- javascript - 关于在 react-native 项目上运行声纳分析得到与 sonar.java.binaries 属性相关的错误
- c++11 - 如何派生 std::vector?
- maven - Antlr 从 3.2 升级到 3.5.2 后生成的代码无效
- php - 将非 WP 数据库和搜索引擎导入 WordPress
- java - 没有设置器的对象的推土机映射