I previously posted this code for a different error, but I am getting a new error after that, so posting in a new post.
I have a basic Flask app, that logs user-agent strings and users local clock times in a database. My template file (templates/home.html
) is as follows:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type=text/javascript>
$(document).ready(function () {
console.log('Date Being Posted');
var clock = new Date();
console.log(JSON.stringify(clock));
$.ajax({
url:"/home",
clock: JSON.stringify(clock),
type:'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
</script>
</head>
<body>
<p>Your clock is being recorded on the loading of the webpage!</p>
{% for user in users %}
<p>{{user.clock}}</p>
{% endfor %}
</body>
</html>
And my main.py
is as follows:
import os
from flask import Flask
from flask import render_template
from flask import request
from sqlalchemy import exc
from flask_sqlalchemy import SQLAlchemy
project_dir = os.path.dirname(os.path.abspath(__file__))
#path to the database
database_file = "sqlite:///{}".format(os.path.join(project_dir, "userdatabase.db"))
app = Flask(__name__)
#indicate to the web application where the database will be stored
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
#initialize a connection to the database; use the db variable to interact with the databse
db = SQLAlchemy(app)
##define a model for the user
class User(db.Model):
user_id = db.Column(db.Integer, primary_key=True)
user_agent = db.Column(db.String(1024), index=True)
clock = db.Column(db.String(1024), index=True)
def __repr__(self):
return "<User-Agent: {}, Clock: {}".format(self.user_agent, self.clock)
@app.route("/home", methods=["GET", "POST"])
def home():
if request.method == "POST":
user_agent_received = request.headers.get('User-Agent')
clock_received = request.json['clock']
user = User(user_agent=user-agent_received, clock=clock_received)
print (user)
try:
db.session.add(user)
db.session.commit()
except exc.IntegrityError as e:
db.session().rollback()
users = User.query.all()
return render_template("home.html", users=users)
if __name__ == "__main__":
app.run(debug=True)
Over here, I am:
a) initializing the database and creating a Model for the Users
b) receiving the clock times posted via ajax request inside home.html
and storing it inside the database, while at the same time sending it to the home.html
page to be displayed.
The database was created separately on the Python3
Interpretor.
However, on the server, I am getting a 500 Internal Server
error. This error is displayed on the console, while I try to look inside Dev Tools to figure out the causes. I can't figure out why this could be the case, could anyone please help?