简体   繁体   English

Python烧瓶休息api

[英]Python flask rest api

i like to add a rest api to my project and therefore I need a selective mysql statement bt I always get back 我想在我的项目中添加一个rest api,因此我需要一个有选择性的mysql语句,我总是回来

{ "error": "(1054, u\\"Unknown column 'None' in 'where clause'\\")" } {“error”:“(1054,u \\”'where子句'\\'中的未知列'无')“}

Whats wrong with the code? 代码有什么问题? how do i need to escape id correctly in the mysql select syntax?? 我如何才能在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')

这是正确而安全的方法:

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

execute语句不正确,模式应该像cursor.execute( <select statement string>, <tuple>) ,将你的语句改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM