我正在编写Flask / MySQL / Python / HTML Web应用程序。当我执行数据库更新时,我希望我的网页刷新回到博客本身以显示新条目。数据库确实会更新,但是浏览器不会刷新到主页。
这是应用程序的python代码。
import pymysql.cursors
from flask import Flask, render_template, request, json, redirect, url_for
import datetime
app = Flask(__name__)
connection = pymysql.connect(host='localhost',
user='root',
password='m0nkwork',
db='mydb',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
def FixDates(data):
for item in data:
date = item['published']
item['published'] = date.strftime("%A %B %d, %Y")
@app.route('/')
@app.route('/index')
def index():
cursor = connection.cursor()
sql = "SELECT * FROM blogentry"
cursor.execute(sql)
data = cursor.fetchall()
cursor.close()
FixDates(data)
return render_template('home.html', data=data)
@app.route('/NewBlog')
def NewBlog():
return render_template('newblog.html')
@app.route('/NewBlog',methods=['POST'])
def AddBlog():
# read the posted values from the UI
Title = request.form['inputTitle']
Text = request.form['inputText']
Author = request.form['inputAuthor']
# validate the received values
if Title and Text and Author:
cursor = connection.cursor()
# Create a new record
sql = "INSERT INTO blogentry (blogtitle, blogtext, blogauthor, published) VALUES (%s, %s, %s, %s)"
cursor.execute(sql, (Title, Text, Author, datetime.datetime.now()))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
return redirect(url_for('index'))
else:
connection.close()
return render_template('newblog.html')
if __name__ == '__main__':
app.run(debug=True)
AddBlog是包含用于添加新博客条目的表单的页面。重定向将转到索引函数,该索引函数应再次调用数据库,获取数据并将其发送到home.html页面并呈现该页面。这不会发生。调用此函数,但是render_template不刷新页面。 newblog.html页面保持不变。
编辑:我没有任何ajax代码,只是一个处理onclick并将其发送到python程序的Jquery。
这是我的newblog.html,其中包含表单和用于处理表单的jquery调用。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask Bucket List App</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container col-8">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="/">Home <span class="sr-only">(current)</span></a>
<a class="nav-item nav-link" href="NewBlog">Add New Blog</a>
</div>
</div>
</nav>
<div class="jumbotron">
<h1>Bucket List App</h1>
<form class="form-newblog">
<label for="inputTitle" class="sr-only">Blog Title</label>
<input type="name" name="inputTitle" id="inputTitle" class="form-control" placeholder="Add Blog Title"
required autofocus>
<p></p>
<label for="inputText" class="sr-only">Blog Text</label>
<textarea rows="5" cols="50" name="inputText" id="inputText" class="form-control" required
autofocus></textarea>
<p></p>
<label for="inputAuthor" class="sr-only">Author</label>
<input type="text" name="inputAuthor" id="inputAuthor" class="form-control" placeholder="Author"
required>
<p></p>
<button id="btnAddNewBlog" class="btn btn-lg btn-primary btn-block" type="button">Add New Entry</button>
</form>
</div>
<footer class="footer">
<p>© Company 2015</p>
</footer>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>
<script>
$(function () {
$('#btnAddNewBlog').click(function () {
$.ajax({
url: '/NewBlog',
data: $('form').serialize(),
type: 'POST',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
});
});
</script>
</body>
</html>
答案 0 :(得分:0)
尝试添加标题after_request,如下所示,
@app.after_request
def adding_header_content(head):
head.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
head.headers["Pragma"] = "no-cache"
head.headers["Expires"] = "0"
head.headers['Cache-Control'] = 'public, max-age=0'
return head
更新:更新后的答案,jQuery ajax调用代码,
服务器发送肯定响应后,使用window.location()重定向浏览器。
success: function (response) {
window.location("/index");
},