简体   繁体   中英

Python MySQL Insert error must be str, not AttributeError

I have a Python function that pulls a JSON file, then reads this and pulls certain key pairs for inserting into a database.

def update_vuln_sets():
    try:
        logging.info('Getting latest vulnerability sets from Vulners API...')
        response = requests.get('https://vulners.com/api/v3/search/stats/')
        response.encoding = 'windows-1252'
        vuln_set = json.loads(response.text)
        vuln_type = vuln_set['data']['type_results']
    except Exception as e:
        logging.error(e)
    try:
        logging.info('Processing JSON response')
                for k in vuln_type:
        vuln_bulletinfamily = vuln_set['data']['type_results'][k]['bulletinFamily']
        vuln_name = vuln_set['data']['type_results'][k]['displayName']
        vuln_count = vuln_set['data']['type_results'][k]['count']
        try:
            logging.info('Connecting to the database...')
            con = MySQLdb.connect('5.57.62.97', 'vuln_backend', 'aHv5Gz50cNgR', 'vuln_backend')
            logging.info('Database connected!')
        except FileNotFoundError as fnf:
            logging.error(fnf)
        except MySQLdb.Error as e:
            logging.error(e)
        try:
            logging.info('Inserting vulnerability type ' + k + ' into DB')
            with con:
                cur = con.cursor()
                con.row_factory = MySQLdb.row
                cur.execute("INSERT OR IGNORE INTO vuln_sets (vulntype, displayname, bulletinfamily, vulncount)"
                            " values (?,?,?,?)", (k, vuln_name, vuln_bulletinfamily, vuln_count))
                con.commit()
            logging.info('Vulnerability type ' + k + ' inserted successfully!')
            except Exception as e:
                logging.error('Vulnerability type ' + k + 'not inserted! - Error: ' + e)
        logging.info('Vulnerability sets successfully updated!')
    except Exception as e:
        logging.error(e)

Checking through my logging it is getting held up at the Inserting Record stage but it just gives an error of root ERROR must be str, not AttributeError

You're logging e which is not a str it is an AttributeError . Based on the bit of a stack trace you shared, it looks like 'logging.error() takes a str` argument.

You could either change logging.error() to accept an Exception instead of a string, or you could call take a string portion of the error to log it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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