代码之家  ›  专栏  ›  技术社区  ›  cagta

如何使用此python脚本避免硬编码sql表达式?

  •  -1
  • cagta  · 技术社区  · 7 年前

    简言之,我从树莓pi上的NRF24传感器中获取一些数据,然后将它们写入数据库。根据Codacy的说法,我需要避免硬编码的sql表达式,但我不知道我的脚本出了什么问题。你能帮我一下吗?

    import time
    from datetime import datetime
    import sys
    from struct import unpack
    from RF24 import RF24
    import psycopg2
    
    irq_gpio_pin = None
    con = None
    
    radio = RF24(22, 0)
    
    def get_data_from_node():
        if radio.available():
            while radio.available():
                length = 10
                receive_payload = radio.read(length)
                values = unpack('hhhhh',receive_payload)
                print "Node Number: "+str(values[0])+"\nLight: "+str(values[1])+" Humidity: "+str(values[2])+" Temperature: "+str(values[3])+" MQ6: "+str(values[4])
                #TIMESTAMPT = "(%s)",(datetime.now(),)
                LOG="INSERT INTO LOGS (HUMIDITY,TEMPERATURE,PRESSURE,AIR_QUALITY,READING_TIME,LOG_TIME,BASE_STATION_ID) VALUES("+str(values[1])+","+str(values[2])+","+str(values[3])+","+str(values[4])+",('%s'),('%s'),1);" % (datetime.now(),datetime.now(),)
                write_to_db(LOG)
    
    def write_to_db(LOG):
        try:
            con = psycopg2.connect(database='dname', user='uname', password='pass')
            con.cursor().execute(LOG)
            con.commit()
        except psycopg2.DatabaseError, e:
            print 'Error %s' % e
            sys.exit(1)
    
    pipes = ["0Node", "1Node"]
    radio.begin()
    radio.setRetries(15,15)
    radio.printDetails()
    
    radio.openWritingPipe(pipes[1])
    radio.openReadingPipe(1,pipes[0])
    radio.startListening()
    
    while 1:
        get_data_from_node()
        time.sleep(0.1)
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   rcriii    7 年前

    基于psycopg文档( http://initd.org/psycopg/docs/usage.html ),光标。execute()可以接受2个参数,SQL语句和一系列将被插入的值。通过这种方式构造insert语句,psycopg可以将python值正确转换为DB格式,并提供针对SQL注入攻击的保护:

    ...
    log="INSERT INTO LOGS (HUMIDITY,TEMPERATURE,PRESSURE,AIR_QUALITY,READING_TIME,LOG_TIME,BASE_STATION_ID) VALUES (%s, %s, %s, %s, %s, %s, %s);"
    vals = values[:4] + [datetime.now(),datetime.now(), 1]
    write_to_db(log, vals)
    ...
    def write_to_db(LOG, vals):
    try:
        con = psycopg2.connect(database='dname', user='uname', password='pass')
        con.cursor().execute(LOG, vals)
        con.commit()
    ...