database - Flask 存储和统计视图的数量
问题描述
我正在制作一个烧瓶博客,我添加了一个新功能 InIt,它可以帮助计算当前帖子有多少视图,但是有什么方法可以用 html 代码而不是返回来呈现。因为如果我想获得观看者的数量,我不会看到帖子,但是如果我想看到帖子,我不会看到数量,所以我想看到不同帖子的观看次数,如何我应该解决这个问题吗?
路线.py
@app.route("/post/<int:post_id>", methods=['GET', 'POST'])
@login_required
def post(post_id):
post = Post.query.get_or_404(post_id) # post = Get post by post_id
return render_template('post.html', title=post.title, post=post)
@app.route("/visit")
@login_required
def visit():
v = Visit.query.first()
if not v:
v = Visit()
v.count += 1
db.session.add(v)
v.count +=1
db.session.commit()
return jsonify(counter=v.count)
post.html
<html>
<!-- <p>{{ visit.count }}</p> -->
<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>
<br>
<small class="text-muted">{{ post.date_posted.strftime('%Y-%m-%d %H:%M') }}</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>
<div class="post-title">
<h2 class="article-title">{{ post.title }}</h2>
</div>
<article>
<div class="container">
<div class="row">
{{ post.content }}
</div>
</div>
</article>
<br>
<div class="post-tag">
<button type="button" class="btn btn-outline-info">{{ post.tag }}</button>
</div>
<br>
<hr>
<br>
<div>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<a class="nav-item nav-link" href="{{ url_for('allcomment', post_id=post.id ) }}"><i class='far fa-comment-alt'></i>See all comments</a>
<a class="nav-item nav-link" href="{{ url_for('commentpost', post_id=post.id ) }}"><i class='far fa-comment-alt'></i>Write comments</a>
</div>
</div>
</article>
</html>
解决方案
return redirect(next_page) if next_page else redirect(url_for('home'))
这条线看起来很可疑,返回不应该在 if 内吗?