【问题标题】:AttributeError: 'NoneType' object has no attribute 'commit' [closed]AttributeError:“NoneType”对象没有属性“提交”[关闭]
【发布时间】:2016-01-06 11:46:17
【问题描述】:

我正在使用 JetBrains PYCharm 创建一个 Python 脚本,该脚本连接到外部 API 以整理天气数据,请原谅我对任何事情的无知,我知道以前有人问过类似的问题,请多多包涵,我只接触了 Python本周第一次。

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

当我尝试在 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')

【问题讨论】:

  • 您从未真正从最初的 self._db 更新 None...

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


【解决方案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()

【讨论】:

  • 我没有将 self 添加到函数中...谢谢
猜你喜欢
  • 2015-09-24
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 2022-10-24
  • 2019-02-24
  • 2019-01-01
  • 2021-12-26
  • 2019-07-23
相关资源
最近更新 更多