当前位置: 首页 > 知识库问答 >
问题:

通过Ajax将数据发布到Flask时,得到500内部服务器错误[重复]

农弘毅
2023-03-14

我之前发布了一个不同的错误,但我得到了一个新的错误,所以发布在一个新的职位。

我有一个基本的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中接收通过ajax请求发送的时钟时间。html并将其存储在数据库中,同时将其发送到主页。要显示的html页面。

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

但是,在服务器上,我收到一个500内部服务器错误。这个错误显示在控制台上,同时我尝试查看开发工具内部以找出原因。我不明白为什么会这样,有人能帮忙吗?

共有1个答案

长孙昀
2023-03-14

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

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

现在要访问flask中发布的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.
 类似资料:
  • 问题内容: 我正在尝试通过ajax将数据提交到数据库。无需使用ajax,提交文章页面可以正常工作。我添加只是为了查看是否发生了任何事情,但是却出现了此错误: POST http:// localhost / laravel-5 / public / articles / create 500(内部服务器错误) 我的代码有什么问题?是JavaScript还是控制器? 编辑:我正在这 C:\ xamp

  • 问题内容: 我正在尝试为这个工作中的项目学习AJAX。我有一个网站加载病人正在服用的药物。 我递归调用此AJAX函数,以便它将附加一个包含单种药物和7天历史记录的新表。我在使代码在FF和IE中执行时遇到问题。在chrome中效果很好。我有显示xmlhttp.status的警报,这是我得到的: xmlhttp.status == 500(内部服务器错误)。 我注释掉了所有递归,因此将其范围缩小到了这

  • 我想用ajax向laravel中的控制器发送post请求。ajax请求发送两个输入参数,我希望controller在数据库中找到包含第一个参数的列,然后使用第二个输入参数设置name属性。但是我在控制台500中有这个错误消息(内部服务器错误)。 Ajax功能: 路线: 控制器功能: 而且我导入csrf无处不在,因为上次当我做AJAX调用我有这个csrf的问题,下面的代码已经修复了我的问题,但现在不

  • 问题内容: 我有一个将数据发送到控制器的ajax请求,它收集我的下拉菜单的值 错误是 错误的回应是 更新 我的表格 我的ajax请求 我的控制器 它给500内部错误..其笨拙的帮助 问题答案: 您的post方法必须具有属性。删除属性或在视图中添加令牌 并将其传递回ajax函数 请注意,该参数在操作方法中不是必需的

  • 问题内容: 这是我在laravel 5中测试的ajax(请参阅下文) 和触发链接 和我的路线 但是当我在google chrome中运行控制台时,它给了我错误,并且未返回预期的响应“在laravel 5中返回’成功!ajax’;” POST http://juliver.laravel.com/test 500(内部服务器错误) 我的代码有什么问题/问题?我缺少什么? 问题答案: 虽然这个问题存在

  • 问题内容: 大家好,我在laravel和ajax中使用我的评论系统时遇到问题。实际上,它仅适用于php,但我遇到了ajax问题。 这是错误消息: 状态码:500内部服务器错误。并且错误显示:1/3 SQLSTATE [23000]:违反完整性约束:1048列’post_id’不能为null。 我正在编辑模态中的注释,我可以创建一个新注释,但是问题是使用ajax编辑它。 JS代码: 这是HTML: