Flask- MySQL:如何处理有效载荷以插入到数据库?

问题描述:

我试图插入一个有效载荷到数据库,我有这样的代码:Flask- MySQL:如何处理有效载荷以插入到数据库?

@app.route('/login', methods=['POST']) 
def login(): 
    if request.method == 'POST': 
     data = request.get_json() 
     credentials = jsonify(data) 
    cur = mysql.connection.cursor() 
    cur.execute('''INSERT INTO User (username, fb_id, auth_token, date_joined) 
       VALUES (%(username)s, %(fb_id)s, %(auth_token)s, %(date_joined)s''', 
        credentials) 
    return "ok" 

这是我想测试出对邮差样品JSON:

{ 
    "username": "edjones", 
    "fb_id": "aklsjdla123", 
    "auth_token": "alksdjaks", 
    "date_joined": 12309201910 
} 

这是我得到的邮差错误:

args = tuple(map(db.literal, args)) 
TypeError: argument 2 to map() must support iteration 

什么是用c直接处理有效载荷的方式?

+0

你是否在你的python文件中意外创建了map函数。 ?还请包括全面的回溯,有助于快速解决问题。 –

+0

请在调试问题中包含完整的追溯。在这种情况下,异常的字符串repr几乎是无用的。例如,您不清楚代码中的哪一行会引发。 –

Request.get_json()返回解析 JSON体,和jsonify()串行数据JSON和把它包装在响应。游标的​​方法需要参数序列或映射图作为第二个参数,但是您将它传递给Response。挂断电话,以jsonify()

@app.route('/login', methods=['POST']) 
def login(): 
    credentials = request.get_json() 
    cur = mysql.connection.cursor() 
    cur.execute('''INSERT INTO User (username, fb_id, auth_token, date_joined) 
       VALUES (%(username)s, %(fb_id)s, %(auth_token)s, %(date_joined)s''', 
       credentials) 
    return "ok" 

既然你已经限制了公认的方法在route()装饰到邮政,如果后卫应该是多余的。