Reputation: 586
I am programming a Flask/MySQL/Python/HTML web application. When I perform an update to the database I want my webpage to refresh back to the blog itself to display the new entry. The database does update, but the browser will not refresh to the main page.
This is the python code for the application.
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 is the page containing the form to add a new blog entry. The redirect is going to the index function which is supposed to call the database again, get the data and send it to the home.html page and render the page. This doesn't happen. This function is called but render_template does not refresh the page. The newblog.html page stays put.
Edit: I don't have any ajax code, just a Jquery that handles the onclick and sends it to the python program.
Here is my newblog.html which contains the form and the jquery call to process the form.
<!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>
Upvotes: 0
Views: 4589
Reputation: 250
Try adding the header after_request, something like below,
@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
UPDATE: Updating the answer after, the Jquery ajax call code,
Use window.location() to redirect the browser once the server sends a positive response.
success: function (response) {
window.location("/index");
},
Upvotes: 1