Python flask 休息 api

标签 python mysql rest api flask-restful

我想在我的项目中添加一个 rest api,因此我需要一个选择性的 mysql 语句 bt 我总是回来

{ “错误”:“(1054,你\“'where子句'中的未知列'无'\”)”

代码有什么问题?我需要如何在 mysql select 语法中正确转义 id??

#!/usr/bin/python

from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
from flask.ext.mysql import MySQL



mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'pi'
app.config['MYSQL_DATABASE_PASSWORD'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_DB'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'


mysql.init_app(app)

api = Api(app)

class test(Resource):
    def post(self):
        try:
        # Parse the arguments

        parser = reqparse.RequestParser()
        parser.add_argument('ID', type=str, help='Id of Item')
        args = parser.parse_args()

        id = str(args['ID'])
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM `PowerSystem` WHERE ID=$(id)")



        data = cursor.fetchall()

        items_list=[];
        for item in data:
            i = {
                'ID':str(item[0]),
                'Timestamp':str(item[1]),
                'batteryVoltage':str(item[2]),
                'batteryCurrent':str(item[3]),
                'solarVoltage':str(item[4]),
                'solarCurrent':str(item[5]),
                'loadVoltage':str(item[6]),
                'loadCurrent':str(item[7]),
                'batteryPower':str(item[8]),
                'solarPower':str(item[9]),
                'loadPower':str(item[10]),
                'batteryCharge':str(item[11])
            }
            items_list.append(i)

        return {'StatusCode':'200$(_id)','Items':items_list}

    except Exception as e:
        return {'error': str(e)}
    api.add_resource(test, '/test')


    if __name__ == '__main__':
     app.run(debug=True,host='0.0.0.0')

   app.run(debug=True,host='0.0.0.0')

最佳答案

执行语句不正确,模式应该是cursor.execute( <select statement string>, <tuple>) , 将您的语句更改为:

cursor.execute("SELECT * FROM `PowerSystem` WHERE ID=%s",(id,))

关于Python flask 休息 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44428455/

相关文章:

python - 按键对列表进行排序并在不重新计算的情况下取出值

python - Pandas RegEx 提取子字符串上的第一个匹配项,传递的项目数错误

mysql - 错误 1059 : Identifier Name Too Long on Foreign Key Constraints from Existing Table

python - 在 Python 中,如何替换字符串中的所有非 UTF-8 字符?

java - QueryParam 跳过符号后的所有内容

rest - 在使用HATEOAS时找到 Restful 资源?

python - 将不在模型中的字段添加到 Django REST 框架中的序列化程序

python - 如何使用 strip() 从句子中删除\n 字符

php - 每个月单独的预订日期范围

python : Automate the user input data(Multiple sequential inputs)?