I have the following function to get the twitter followers and write them to a MySQL database. My problem is my error handling doesn't handle the StopIteration case very well. When I execute the code it does write the details to the database in line with the API restrictions but at the end it generates the error below so no further code is executed. How can I improve my error handling so the exception is handled correctly ?
StopIteration: The above exception was the direct cause of the following exception: RuntimeError
def limit_handled(cursor):
while True:
try:
yield cursor.next()
except tweepy.RateLimitError:
time.sleep(15 * 60)
def writeFollowersToDB(TwitterAPI,DBConnection,SocialHandle ="Microsoft",DatabaseTable="twitter"):
AboutMe = TwitterAPI.get_user(SocialHandle)
#print(AboutMe)
DBCursor=mydb.cursor()
#Create the SQL INSERT
SQLInsert="INSERT INTO "+ DatabaseTable + " (SourceHandle,SourceHandleFollowersCount,SourceHandleFollowingCount, Action,DestinationHandle,DestinationHandleFollowersCount,DestinationPublishedLocation,DestinationWeb,CrawlDate) VALUES (%s, %s, %s,%s,%s,%s,%s,%s,%s) ;"
print(SQLInsert)
for follows in limit_handled(tweepy.Cursor(TwitterAPI.followers,id=SocialHandle).items()):
today = date.today()
try:
if not follows.url:
expandedURL =""
else:
#print(follows.url)
expandedURL = follows.entities["url"]["urls"][0]["expanded_url"]
#print(follows.screen_name, AboutMe.followers_count,AboutMe.friends_count,"from ", follows.location,"with ", " followers "," and provided this expanded URL: ",expandedURL )
CrawlDate = today.strftime("%Y-%m-%d")
#Insert into table
SQLValues =(AboutMe.screen_name,AboutMe.followers_count,AboutMe.friends_count,"isFollowedBy",follows.screen_name,follows.followers_count,follows.location,expandedURL,CrawlDate)
DBCursor.execute(SQLInsert,SQLValues)
DBConnection.commit()
print(AboutMe.screen_name,follows.screen_name,follows.followers_count)
except StopIteration:
DBConnection.close()
break
except:
print(e.reason)
DBConnection.close()
break
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-2-d095a0b00b72> in limit_handled(cursor)
3 try:
----> 4 yield cursor.next()
5 except tweepy.RateLimitError:
C:\Path\site-packages\tweepy\cursor.py in next(self)
194 # Reached end of current page, get the next page...
--> 195 self.current_page = self.page_iterator.next()
196 self.page_index = -1
C:\Path\site-packages\tweepy\cursor.py in next(self)
69 if self.next_cursor == 0 or (self.limit and self.num_tweets == self.limit):
---> 70 raise StopIteration
71 data, cursors = self.method(cursor=self.next_cursor,