Python tweepy writing to sqlite3 db

本秂侑毒 提交于 2021-02-05 11:16:07

问题


My script below (taken from various resources online) isn't writing to the database. I do not get any errors, and if I comment out the database lines then it outputs to the console without issue.

The database exists, it has 2 fields, its writeable by me.... Any ideas please?

Updated code below

#!/usr/bin/env python

import sys
import tweepy
from textwrap import TextWrapper
import sqlite3

CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''


auth1 = tweepy.auth.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
auth1.set_access_token(ACCESS_KEY,ACCESS_SECRET)
api = tweepy.API(auth1)
conn = sqlite3.connect('twitter.db')
cur = conn.cursor()

class StreamListener(tweepy.StreamListener):
    status_wrapper = TextWrapper(width=60, initial_indent='    ', subsequent_indent='    ')



    def on_status(self, status):
        try:
            cur.execute('INSERT INTO tweets (text, date) VALUES (?, ?)' ,(status.text,))
            print self.status_wrapper.fill(status.text)
            print '\n %s  %s  via %s\n' % (status.author.screen_name, status.created_at, status.source)
            conn.commit()   
        except Exception, e:
            print >> sys.stderr, 'Encountered Exception:', e

    def on_error(self, status_code):
            print >> sys.stderr, 'Encountered error with status code:', status_code
            return True # Don't kill the stream

    def on_timeout(self):
            print >> sys.stderr, 'Timeout...'
            return True # Don't kill the stream


streamer = tweepy.Stream(auth1, StreamListener(), timeout=None)
setTerms = ['news','hello']
streamer.filter(setTerms)

回答1:


First, fix your indentation. You are not getting any errors, because you're explicitly silencing them! with

except Exception, e:
    # Catch any unicode errors while printing to console
    # and just ignore them to avoid breaking application.
    pass

This catches any exception that occurs in the try: except: block. Reading the Python Tutorial is a good start to learn more about exceptions.




回答2:


Do you want to do this:

cur = conn.cursor()
cursor.execute('INSERT INTO tweets (text, date) VALUES (?, NOW())' ,(status.text))

Or this:

cur = conn.cursor()
cur.execute('INSERT INTO tweets (text, date) VALUES (?, NOW())' ,(status.text))

In the First case cursor is undeclared.

Also, as lqc pointed out, you silence all errors. Don't catch any exceptions to see what's going on or change it to something more specific (like UnicodeError).



来源:https://stackoverflow.com/questions/11432187/python-tweepy-writing-to-sqlite3-db

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!