使用Flask Rest API将数据从JSON插入MySQL时出错

时间:2019-06-06 05:49:07

标签: python mysql

我有一个JSON数据,我想将其插入我的MySQL数据库中。

我已经获取了一个JSON对象并将其加载到字典中,然后创建了一个类,并且在该类内部定义了一种方法来将该数据插入到我的MySQL数据库中

from flask_mysqldb import MySQL
from flask_restful import Resource,Api
import json

app=Flask(__name__)

app.config['MYSQL_HOST']='localhost'
app.config['MYSQL_USER']='root'
app.config['MYSQL_PASSWORD']=''
app.config['MYSQL_DB']='test'

mysql=MySQL(app)
api=Api(app)
person = '{"product_id": 2, "user_id": 901, "rating":5}'
person_dict = json.loads(person)

class SetData(Resource):
    def post(self):
        product_id=person_dict['product_id']
        user_id=person_dict['user_id']
        rating=person_dict['rating']
        cur=mysql.connection.cursor()
        cur.execute("Insert INTO star_rating(product_id,user_id,range) values(%d,%d,%d)",(product_id,user_id,rating))
        mysql.connection.commit()
        return 'Record Inserted Successfully'

api.add_resource(SetData,'/')

if __name__=='__main__':
    app.run(debug=True)
            ```

It was expected that data should be inserted in my MySQL Database but its giving error: 
Error is browser is : 
    "message": "The method is not allowed for the requested URL."
When I checked the command prompt, there were few listed errors :
File "C:\Users\adeep\Desktop\restapi\lib\site-packages\MySQLdb\cursors.py", line 201, in execute
    query = query % args
TypeError: %d format: a number is required, not bytes

During handling of the above exception, another exception occurred:
MySQLdb._exceptions.ProgrammingError: %d format: a number is required, not bytes

1 个答案:

答案 0 :(得分:0)

我认为您需要将变量和mysql语句中的设置变量都转换为字符串

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>

<h1>Test</h1>
<a href="vscode://file/path/to/my/file.md">open file.md in vscode</a> 

</body>
</html>