2016-01-06 127 views
-2

我正在使用JetBrains PYCharm创建连接到外部API的Python脚本来整理天气数据,原谅我对任何事情的无知,我知道类似的问题已经被问到之前,请耐心等待本周我第一次只碰到Python。AttributeError:'NoneType'对象没有属性'commit'

它输入'邮政编码到延长线' - 顾名思义,这是将标准英​​国邮政编码转换为一对纬度经度值。

当我尝试运行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') 
+5

你从来没有真正从最初'None' ... – jonrsharpe

+0

'self._db =更新'self._db' None' –

回答

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() 
+0

我没有增加自我的功能...谢谢 – Zabs