使用Tweepy和MySQL的未引发的异常 [英] Unraised exception using Tweepy and MySQL

查看:84
本文介绍了使用Tweepy和MySQL的未引发的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Tweepy将推文存储在MySQL数据库中.该代码可以正常工作,但只有一次尝试执行SQL命令以将数据插入数据库时​​,该代码才能正常工作.代码如下:

I am trying to use Tweepy to store tweets in a MySQL DB. The code works fine, with the exception of once I try to execute the SQL command to insert the data into the database. Code is as follows:

#MySQL connection attempt
try:
    cnx = mysql.connector.connect(**config)
    cursor = cnx.cursor()
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    else:
        print(err)

class StdOutListener(StreamListener):
    def on_data(self, data):
        tweet = json.loads(data) #loads JSON data into list for python
        #Parameters for SQL insert
        try:
            user_id = tweet['user']['id']
        except IndexError:
            print("Critical error: User ID not found")
            return
        try:
            username = tweet['user']['screen_name']
        except IndexError:
            print("Critical error: Username not found")
            return
        try:
            avatar = tweet['user']['profile_image_url']
        except IndexError:
            return
        try:
            tweet_id = tweet['id']
        except IndexError:
            print("Critical error: Tweet ID not found")
            return
        try:
            content = tweet['text']
        except IndexError:
            print("Critical error: Tweet Content not found")
            return
        try:
            #converts Twitter's date format into MySQL DATETIME
            posted = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))
        except IndexError:
            print("Critical error: created_at not found")
            return

        #MySQL insert query
        try:
            cursor.execute("INSERT INTO tweets (user_id, username, avatar, tweet_id, content, posted) VALUES (%%s, %%s, %%s, %%s, %%s, %%s)",(user_id, username, avatar, tweet_id, content, posted))
        except RuntimeError:
            print("Runtime error")
        print("TEST")
        cnx.commit()
        return True

    def on_error(self, status):
        print(status)




if __name__ == '__main__':
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    stream = Stream(auth, l)
    print("Starting Twitter Stream")
    stream.filter(track=['bob'], languages=["en"])

然后,在运行时出现以下错误:

Then, when running I get the following error:

Traceback (most recent call last):
  File "C:/Users/Wilson/PycharmProjects/Avalon/Twitter.py", line 95, in <module>
    stream.filter(track=['*', '**', '***', '****'], languages=["en"])
  File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 428, in filter
    self._start(async)
  File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 346, in _start
    self._run()
  File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 286, in _run
    raise
RuntimeError: No active exception to reraise

我已将其隔离到执行MySQL查询的行中.

I have isolated it to the line that executes the MySQL query.

推荐答案

通过在

By checking tweepy/streaming.py at https://github.com/tweepy/tweepy/blob/master/tweepy/streaming.py it seems there is a bug in tweepy in the way exceptions are handled, spefically

    if exception:
        # call a handler first so that the exception can be logged.
        self.listener.on_exception(exception)
        raise

raise应该为raise exception

这篇关于使用Tweepy和MySQL的未引发的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆