I am using JetBrains PYCharm for creating a Python script that is connecting to an external API to collate weather data, forgive my ignorance of anything , I know similar questions have been asked before, please bear with me I only touched Python for the first time this week.
It imports 'PostcodeToLatLong' - as the name suggests this is to convert a standard UK postcode to a pair of Latitude & Longitude values.
When I attempt to run the code in PYCharm I get the following error/output in the debug window in PYCharm, I can see its related to the Database Connect/Disconnect functions but do not understand why i'm getting this message - any ideas?:
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 Code Below :-
#!/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')
Setup self._db
:
Change:
def connect_database():
mysql.connector.connect(user='root', password='admin', host='localhost', port=3306, database='mydbname')
into:
def connect_database(self):
self._db = mysql.connector.connect(user='root', password='admin', host='localhost', port=3306, database='mydbname')
Of course, you need to call connect_database()
. If not done anywhere else, this would be a good place:
def __init__(self, codepoint_dir = '.'):
self._db = connect_database()