2016-01-06 161 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