AttributeError:' NoneType'对象没有属性' commit'

时间:2016-01-06 11:46:17

标签: python python-3.x attributeerror weather-api

我正在使用JetBrains PYCharm来创建一个Python脚本,它连接到外部API来整理天气数据,原谅我对任何事物的无知,我知道之前已经问过类似的问题,请耐心等待我本周第一次。

它导入' PostcodeToLatLong ' - 顾名思义,这是将标准英​​国邮政编码转换为一对Latitude&经度值。

当我尝试在PYCharm中运行代码时,我在PYCharm的调试窗口中得到以下错误/输出,我可以看到它与数据库连接/断开功能有关但是不明白为什么我得到这个消息 - 任何想法?:

Exception ignored in: <bound method AA_ForecastIOWeather.__del__ of <__main__.AA_ForecastIOWeather object at 0x01CFB250>>
Traceback (most recent call last):
File "C:/www-service/forecast-io.py", line 18, in __del__
File "C:/www-service/forecast-io.py", line 24, in disconnect_database
AttributeError: 'NoneType' object has no attribute 'commit'

下面的Python代码: -

#!/usr/bin/python
import mysql.connector
import time
import logging
from PostCodeToLatLong import PostCodeToLatLong

API_KEY = 'fa9690c7e2927c7e9696d7xxxxxxxxxxx'

class AA_ForecastIOWeather(object):

    def __init__(self, codepoint_dir = '.'):
        self._db = None
        self.log = self._init_logging()
        self._forecastIO = API_KEY
        self.p2ll = PostCodeToLatLong(codepoint_dir)

    def __del__(self):
        self.disconnect_database()

    def connect_database():
        mysql.connector.connect(user='root', password='admin', host='localhost', port=3306, database='mydbname')

    def disconnect_database(self):
        self._db.commit()
        self._db.close()

    def _init_logging(self):
        log = logging.getLogger('AA_ForecastIOWeather')
        log.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s-%(name)s(%(lineno)d)-%(levelname)s:%(message)s')
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        log.addHandler(handler)
        return log



w = AA_ForecastIOWeather(codepoint_dir = '/registration/lib/codepoint')

1 个答案:

答案 0 :(得分:1)

设置self._db

变化:

def connect_database():
    mysql.connector.connect(user='root', password='admin', host='localhost', port=3306, database='mydbname')

成:

def connect_database(self):
    self._db = mysql.connector.connect(user='root', password='admin', host='localhost', port=3306, database='mydbname')

当然,您需要致电connect_database()。如果没有在其他任何地方完成,这将是一个好地方:

def __init__(self, codepoint_dir = '.'):
    self._db = connect_database()