Learning Python Network Programming

(Sean Pound) #1
Chapter 3

This is because Twitter applies rate limits to its API, which means that our
application is only allowed to make a certain number of requests to an endpoint in
a given amount of time. The limits are listed in the Twitter documentation and they
vary according to the authentication route (as discussed later) and endpoint. We are
using statuses/mentions_timeline.json, so our limit is 15 requests for every 15
minutes. If we exceed this, then Twitter will respond with a 429 Too many requests
status code. This will force us to wait till the next 15 minute window starts before it
lets us get any useful data back.


Rate limits are a common feature of web APIs, so it's useful to have ways of testing
efficiently when using them. One approach to testing with data from rate-limited
APIs is to download some data once and then store it locally. After this, load it from
the file instead of pulling it from the API. Download some test data by using the
Python interpreter, as shown here:





from twitter_worldclock import *








auth_obj = init_auth()





Credentials validated OK





mentions = get_mentions(1, auth_obj)








json.dump(mentions, open('test_mentions.json', 'w'))





You'll need to be in the same folder as twitter_worldclock.py when you run
this. This creates a file called test_mentions.json, which contains our JSONized
mentions. Here, the json.dump() function writes the supplied data into a file rather
than returning it as a string.


Instead of calling the API, we can use this data by modifying our program's main
section to look like the following:


if __name__ == '__main__':
mentions = json.load(open('test_mentions.json'))
for tweet in mentions:
process_tweet(tweet)

Sending a reply


The final function that we need to perform is sending a tweet in response to a
mention. For this, we use the statuses/update.json endpoint. If you've not
registered your mobile number with your app account, then this won't work. So, just
leave your program as it is. If you have registered your mobile number, then add this
function under process_tweets():


def post_reply(reply_to_id, text, auth_obj):
params = {
Free download pdf