通过Ajax向Flask发布数据时出现500 Internal Server错误

时间:2018-12-17 17:46:42

标签: python-3.x flask flask-sqlalchemy

我以前曾将此代码发布为其他错误,但此后我遇到了新错误,因此请在新帖子中发布。

我有一个基本的Flask应用程序,该应用程序将用户代理字符串和用户本地时钟时间记录在数据库中。我的模板文件(templates/home.html)如下:

<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>

我的main.py如下:

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)

在这里,我是

a)初始化数据库并为用户创建模型

b)接收home.html内通过ajax请求发布的时钟时间并将其存储在数据库中,同时将其发送到home.html页面进行显示。

该数据库是在Python3解释器上单独创建的。

但是,在服务器上,我遇到了500 Internal Server错误。在我尝试查看开发工具以查明原因时,该错误将显示在控制台上。我不知道为什么会这样,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

首先,jquery中的ajax帖子具有以下结构:

       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
        });

现在要访问烧瓶中发布的JSON,使用get_json()方法非常简单,方法如下:

@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.