3
I built a Flask API connected to a Mysql database, which has its entries displayed in an HTML page.
player_manager.py:
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql+pymysql://xre:sdhjsdhsj2562@localhost:3306/team'
db = SQLAlchemy(app)
@app.route("/", methods=["GET"])
def get():
try:
players = Player.query.all()
except Exception as e:
print("Failed")
print(e)
return render_template("home.html", players=players)
@app.route("/", methods=["POST"])
def post():
player = Player(
nome=request.args.get("nome"),
posicao=request.args.get("posicao"),
numero=request.args.get("numero"),
gols=request.args.get("gols"),
partidas=request.args.get("partidas"))
db.session.add(player)
db.session.commit()
return redirect("/")
class Player(db.Model):
nome = db.Column(db.String(80), unique=True, nullable=False, primary_key=False)
numero = db.Column(db.Integer, primary_key=True)
posicao = db.Column(db.String(80), unique=True, nullable=False, primary_key=False)
gols = db.Column(db.Integer, primary_key=False)
partidas = db.Column(db.Integer, primary_key=False)
def __repr__(self):
return "Nome: {}, Numero: {}, Posicao: {}, Gols: {}, Partidas: {}".format(
self.nome,
self.numero,
self.posicao,
self.gols,
self.partidas
)
if __name__ == "__main__":
app.run(debug=True)
home html.:
<html>
<body>
<h1>Jogadores</h1>
{% for player in players %}
<p>{{player}}</p>
{% endfor %}
</body>
</html>
</body>
</html>
I would like the page displaying bank entries to be automatically updated as new entries are added to the bank. From what I researched, it would be possible to achieve this result through Server Sent Event, as in this example, or through AJAX, such as in this another example. As I’m new to web development, I don’t know how to implement these changes in my code.
Attempt to use Ajax:
player_manager.py:
@app.route("/", methods=["POST"])
def post():
player = Player(
nome=request.args.get("nome"),
posicao=request.args.get("posicao"),
numero=request.args.get("numero"),
gols=request.args.get("gols"),
partidas=request.args.get("partidas"))
db.session.add(player)
db.session.commit()
return redirect("/")
home html.:
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var new_players = $(this).val();
$.ajax({
url: "/",
type: "get",
data: {jsdata: new_players},
success: function(response) {
$("#players_list").html(response);
},
error: function(xhr) {
//Do Something to handle error
}
});
</script>
<div id="players_list">
<h1>Jogadores</h1>
{% for player in players %}
<p>{{player}}</p>
{% endfor %}
</div>
</body>
</html>
</body>
</html>
However, I still can’t update the content without reloading the content.