A Twitter client

In this example, we will connect to the Twitter API, which uses the OAuth protocol. You'll need to provide a credentials file with the keys you have taken down from the Twitter app configuration. This is the format of credentials.txt file, where we use a new line for each key or token:

  • CONSUMER_KEY
  • CONSUMER_SECRET
  • OAUTH_TOKEN
  • OAUTH_TOKEN_SECRET

You can find the following code in the twitter_connect.py file:

!/usr/bin/python3

import requests, requests_oauthlib, sys

def init_auth(file):
(CONSUMER_KEY,CONSUMER_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET) = open(file, 'r').read().splitlines()
auth_obj = requests_oauthlib.OAuth1(CONSUMER_KEY, CONSUMER_SECRET,OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
if verify_credentials(auth_obj):
print('Validated credentials OK')
return auth_obj
else:
print('Credentials validation failed')
sys.exit(1)

def verify_credentials(auth_obj):
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
response = requests.get(url, auth=auth_obj)
return response.status_code == 200

if __name__ == '__main__':
auth_obj = init_auth('credentials.txt')

In the previous script, we create the OAuth1 authentication instance, auth_obj, in the init_auth() function by using our access credentials. We pass this to Requests whenever we need to make an HTTP Request, and through it, Requests handles the authentication. You can see an example of this in the verify_credentials() function.

In the verify_credentials() function, we test whether Twitter recognizes our credentials. The URL that we're using here is an endpoint that Twitter provides for testing whether our credentials are valid. It returns an HTTP 200 status code if they are valid or a 401 status code if not.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset