2

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?

QPTR
  • 1,620
  • 7
  • 26
  • 47
  • 1
    Also, in `user = User(user_agent=user-agent_received, clock=clock_received)` you've made a mistake `user-agent_received` should be `user_agent_received`. – Rahul Bharadwaj Dec 17 '18 at 17:56

1 Answers1

3

Firstly, ajax post in jquery has this structure:

       var clock={
          "key":value //say
       };



        $.ajax({
            url: 'home',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(clock),
            contentType:"application/json; charset=UTF-8"
        })
        .done(function(data) {
            // do stuff here
        })
        .fail(function(err) {
            // do stuff here
        })
        .always(function(info) {
            // do stuff here
        });

Now to access a posted JSON in flask, it's extremely simple use of get_json() method as:

@app.route("/home", methods=["GET", "POST"])
def home():

    if request.method == "POST":

        user_agent_received = request.get_json()
        # user_agent_received is now a regular 
        # python dictionary with same structure 
        # as input json sent from jQuery on client.
Rahul Bharadwaj
  • 2,555
  • 2
  • 18
  • 29
  • Thank you so much for the answer! It works now! I have a question, are the attributes `dataType` and `data` always necessary? – QPTR Dec 17 '18 at 18:40
  • 1
    jQuery does make an intelligent guess when you provide data, but for POST it's always better to be sure of the data type you are sending. – Rahul Bharadwaj Dec 17 '18 at 21:51
  • 1
    Late addition: `data` is necessary. `dataType` can be guessed but don't let that happen. – Rahul Bharadwaj Dec 18 '18 at 02:21