I'm writing a code that uses Twitter API to get users' statuses, number of followers etc. I need to write a script that opens browser and asks users to sign in and let me get the authentication from them.
from requests_oauthlib import OAuth1Session
import requests
from requests_oauthlib import OAuth1
from urlparse import parse_qs
client_key = "keykeykeykey"
client_secret = "keykeykeykeykey"
request_token_url = 'https://api.twitter.com/oauth/request_token'
oauth = OAuth1Session(client_key, client_secret=client_secret)
fetch_response = oauth.fetch_request_token(request_token_url)
#print(fetch_response)
resource_owner_key = fetch_response.get('oauth_token')
resource_owner_secret = fetch_response.get('oauth_token_secret')
oauth = OAuth1(client_key, client_secret=client_secret)
r = requests.post(url=request_token_url, auth=oauth)
#print(r.content)
credentials = parse_qs(r.content)
resource_owner_key = credentials.get('oauth_token')[0]
resource_owner_secret = credentials.get('oauth_token_secret')[0]
base_authorization_url = 'https://api.twitter.com/oauth/authorize'
authorization_url = oauth.authorization_url(base_authorization_url)
print 'Please go here and authorize,', authorization_url
redirect_response = raw_input('Paste the full redirect URL here: ')
oauth_response = oauth.parse_authorization_response(redirect_response)
#print(oauth_response)
verifier = oauth_response.get('oauth_verifier')
authorize_url = base_authorization_url + '?oauth_token='
authorize_url = authorize_url + resource_owner_key
print 'Please go here and authorize,', authorize_url
verifier = raw_input('Please input the verifier')
I have found this kind of example from internet but it gives an error like :
AttributeError: 'OAuth1' object has no attribute 'authorization_url'
I have checked the session info and actually there is authorization_url here:
https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py
It looks like you use the oauth variable as an OauthSession object and a Oauth1 object.
oauth = OAuth1Session(client_key, client_secret=client_secret)
oauth = OAuth1(client_key, client_secret=client_secret)
It should work if you use it as a session object
Related
I am trying to access protected Tweets from Twitter handles using Tweepy and Twitter API v2. To do this I know I have to use 3-legged OAuth. I have done it and successfully generated an access token and access token secret. But with those access keys I am not able to see the protected Tweets of my own protected account when I am authorizing with the same account.
Does anyone know what I am doing wrong here?
This is a login.py file with the authorization function
#!/usr/bin/env python
import tweepy
def authrize():
CONSUMER_KEY = "XXXXXXXXXXXxx"
CONSUMER_SECRET = "XXXXXXXXXXXXXXXXx"
BEARER_TOKEN = "XXXXXXXXXXXXXXXX"
auth = tweepy.OAuth1UserHandler(CONSUMER_KEY, CONSUMER_SECRET,callback="oob")
print(auth.get_authorization_url())
verifier = input("Input PIN: ")
ACCESS_TOKEN, ACCESS_TOKEN_SECRET = auth.get_access_token(verifier)
print(ACCESS_TOKEN,"******",ACCESS_TOKEN_SECRET)
return (CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
and my tweepy code app.py is as follows
import tweepy
import login
def get_client(CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET):
client = tweepy.Client(bearer_token=BEARER_TOKEN,
consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET,
access_token=ACCESS_TOKEN,
access_token_secret=ACCESS_TOKEN_SECRET, wait_on_rate_limit=True)
return client
def get_user_id(username):
user = client.get_user(username=username)
return user.data.id
def pagination(user_id):
responses = tweepy.Paginator(client.get_users_tweets, user_id,
exclude='replies,retweets',
max_results=100,
expansions='referenced_tweets.id',
tweet_fields=['created_at', 'public_metrics', 'entities'])
return responses
def get_original_tweets(user_id):
tweet_list = []
responses = pagination(user_id)
for response in responses:
if response.data ==None:
continue
else:
for tweets in response.data:
tweet_list.append([tweets.text,
tweets['public_metrics']['like_count'],
tweets['public_metrics']['retweet_count'],
tweets['created_at'].date()])
return tweet_list
def user_details(username):
user = {}
user_response = client.get_user(username=username, user_fields=['public_metrics', 'description', 'url'])
user_metrics = user_response.data['public_metrics']
user['description'] = user_response.data['description']
user['followers'] = user_metrics['followers_count']
user['following'] = user_metrics['following_count']
return user
keys = login.authrize()
client = get_client(*keys)
username = input("Username:")
userid = get_user_id(username)
print(user_details(username))
print(get_original_tweets(userid))
By default, Client.get_users_tweets uses your bearer token rather than OAuth 1.0a User Context to authenticate. You need to set the user_auth parameter to True.
So I have an object, which is credentials from an OAuth2 authorization for a web service. I want to save the users credentials so I can continue to use them in the future. I'm using Django.
The object is: <oauth2client.client.OAuth2Credentials object at 0x104b47310>
I'm not sure how I can stringify the credentials and then build the credentials object back from a string.
Sample code as requested:
#!/usr/bin/python
import httplib2
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
# Copy your credentials from the console
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
# Check https://developers.google.com/webmaster-tools/search-console-api-original/v3/ for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http)
# Retrieve list of properties in account
site_list = webmasters_service.sites().list().execute()
# Filter for verified websites
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
if s['permissionLevel'] != 'siteUnverifiedUser'
and s['siteUrl'][:4] == 'http']
# Printing the URLs of all websites you are verified for.
for site_url in verified_sites_urls:
print site_url
# Retrieve list of sitemaps submitted
sitemaps = webmasters_service.sitemaps().list(siteUrl=site_url).execute()
if 'sitemap' in sitemaps:
sitemap_urls = [s['path'] for s in sitemaps['sitemap']]
print " " + "\n ".join(sitemap_urls)
You can use pickle module to serialize and de-serialize python objects. Here is untested code:
import pickle
# Store OAuth2Credentials to a file
with open(FILENAME, 'wb') as credentials_file:
pickle.dump(credentials, credentials_file)
# Read OAuth2Credentials from file
with open(FILENAME, 'rb') as credentials_file:
credentials = pickle.load(credentials_file)
I'm trying to get an oauth request token from the etrade api (sandbox) in Python with this thing:
import requests
from oauthlib.oauth1 import Client
consumer_key = 'foo' # actual key used
consumer_secret = 'bar' # actual secret used
request_url = 'https://etwssandbox.etrade.com/oauth/sandbox/request_token'
client = Client(consumer_key, client_secret = consumer_secret)
uri, headers, body = client.sign(request_url)
add_params = ', realm="", oauth_token= "", oauth_callback="oob"'
headers['Authorization'] += add_params
r = requests.get(url = uri, headers = headers)
print(r.text) # abbreviated resp: " . . . .auth_problem=consumer_key_rejected,oauth_problem_advice=The oauth_consumer_key foo can be used only in SANDBOX environment . . .
The header generated is:
{'Authorization': 'OAuth oauth_nonce="99985873301258063061424248905", oauth_timestamp="1424248905", oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="foo", oauth_signature="A7ZY91UyZz6NfSGmMA5YWGnVM%2FQ%3D", realm="", oauth_token= "", oauth_callback="oob"'}
I have also tried the url: 'https://etwssandbox.etrade.com/oauth/sandbox/rest/request_token'
And I have tried the header without the add_params (it seems to need the blank oauth_token?)
Note: Confusingly, the response periodically comes back: "Http/1.1 400 Bad Request" with exactly the same url/header.
Any idea what I'm doing wrong?
A helpful person at etrade clarified for the doc-challenged that all oauth api requests (whether you are working in the sandbox or not) need to be sent to the main api url: 'https://etws.etrade.com/oauth/{api}'.
It is only after authenticating a session that the sandbox urls should be used: 'https://etwssandbox.etrade.com/{non-oauth-module}/sandbox/rest/{api}'.
In case others are having problems authenticating a session with etrade in python3, this works in the sandbox at least:
from rauth import OAuth1Service
import webbrowser
def getSession():
# Create a session
# Use actual consumer secret and key in place of 'foo' and 'bar'
service = OAuth1Service(
name = 'etrade',
consumer_key = 'foo',
consumer_secret = 'bar',
request_token_url = 'https://etws.etrade.com/oauth/request_token',
access_token_url = 'https://etws.etrade.com/oauth/access_token',
authorize_url = 'https://us.etrade.com/e/t/etws/authorize?key={}&token={}',
base_url = 'https://etws.etrade.com')
# Get request token and secret
oauth_token, oauth_token_secret = service.get_request_token(params =
{'oauth_callback': 'oob',
'format': 'json'})
auth_url = service.authorize_url.format(consumer_key, oauth_token)
# Get verifier (direct input in console, still working on callback)
webbrowser.open(auth_url)
verifier = input('Please input the verifier: ')
return service.get_auth_session(oauth_token, oauth_token_secret, params = {'oauth_verifier': verifier})
# Create a session
session = getSession()
# After authenticating a session, use sandbox urls
url = 'https://etwssandbox.etrade.com/accounts/sandbox/rest/accountlist.json'
resp = session.get(url, params = {'format': 'json'})
print(resp)
Thanks #ethann - this actually still works as of 6/17/2020 with changed urls.
from rauth import OAuth1Service
import webbrowser
service = OAuth1Service(
name = 'etrade',
consumer_key = 'foo',
consumer_secret = 'bar',
request_token_url = 'https://apisb.etrade.com/oauth/request_token',
access_token_url = 'https://apisb.etrade.com/oauth/access_token',
authorize_url = 'https://us.etrade.com/e/t/etws/authorize?key={}&token={}',
base_url = 'https://apisb.etrade.com')
oauth_token, oauth_token_secret = service.get_request_token(params =
{'oauth_callback': 'oob',
'format': 'json'})
auth_url = service.authorize_url.format('foo again', oauth_token)
webbrowser.open(auth_url)
verifier = input('Please input the verifier: ')
session = service.get_auth_session(oauth_token, oauth_token_secret, params = {'oauth_verifier': verifier})
url = 'https://apisb.etrade.com/v1/accounts/list'
resp = session.get(url, params = {'format': 'json'})
print(resp.text)
I am trying to follow some companies registered on LinkedIn through python code and as per LinkedIn API documentation I need to use oauth2 - POST method to follow a company.
My queries are below:
How to specify a particular company name via python code to follow a company?
Can someone advise the python code for this?
My code is below:
oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=api_key, secret=api_secret)
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
http_method = "POST"
http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)
def linkedinreq(url, method, parameters):
req = oauth.Request.from_consumer_and_token(oauth_consumer,
token=oauth_token,
http_method=http_method,
http_url=url,
parameters=parameters)
req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)
req.to_postdata()
def fetchsamples():
url = "https://api.linkedin.com/v1/people/~/following/companies"
parameters = []
response = linkedinreq(url, "POST", parameters)
fetchsamples()
The python modules python-linkedin and python-linkedin-v2 are outdated. Thus, I suggest you to use the requests_oauthlib module instead.
from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import linkedin_compliance_fix
# In case the `redirect_url` does not implement https
import os
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
# Credentials you get from registering a new application
client_id = '<the client id you get from linkedin>'
client_secret = '<the client secret you get from linkedin>'
redirect_url = '<authorized redirect URL from LinkedIn config>'
# OAuth endpoints given in the LinkedIn API documentation (check for updates)
authorization_base_url = 'https://www.linkedin.com/oauth/v2/authorization'
token_url = 'https://www.linkedin.com/oauth/v2/accessToken'
# Authorized Redirect URL (from LinkedIn config)
linkedin = OAuth2Session(client_id, redirect_uri=redirect_url)
linkedin = linkedin_compliance_fix(linkedin)
# Redirect user to LinkedIn for authorization
authorization_url, state = linkedin.authorization_url(authorization_base_url)
print('Please go here and authorize,', authorization_url)
# Get the authorization verifier code from the callback url
redirect_response = input('Paste the full redirect URL here:')
# Fetch the access token
linkedin.fetch_token(token_url, client_secret=client_secret,
authorization_response=redirect_response)
# Fetch a protected resource, i.e. user profile
r = linkedin.get('https://api.linkedin.com/v1/people/~')
print(r.content)
Instead of reinventing the wheel, use python-linkedin wrapper.
Example code to search for the companies:
from linkedin import linkedin
CONSUMER_KEY = 'your key'
CONSUMER_SECRET = 'your secret'
USER_TOKEN = 'your token'
USER_SECRET = 'your user secret'
RETURN_URL = ''
# Instantiate the developer authentication class
authentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
USER_TOKEN, USER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Pass it in to the app...
application = linkedin.LinkedInApplication(authentication)
print application.search_company(selectors=[{'companies': ['name', 'universal-name', 'website-url']}],
params={'keywords': 'apple microsoft'})
To follow the company, use follow_company() method, see more information and examples here:
COMPANY_ID = 1035 # this you would get from the `search_company()`
application.follow_company(COMPANY_ID)
I am trying to setup this Twitter authorization without having the user to enter the pin in our screen but I am having trouble getting the correct setup I am always directed to enter the PIN. trying to use and follow this package https://github.com/simplegeo/python-oauth2
Here is my current code
env = Environment(loader = PackageLoader('buzzient','tmpl'))
template = env.get_template('authtwitter.html')
tmpldict = {}
#SETUP TWITTER AUTHORIZATION OBJECT
consumer_key = '######################'
consumer_secret = '##############################'
request_token_url = 'http://twitter.com/oauth/request_token'
access_token_url = 'http://twitter.com/oauth/access_token'
authorize_url = 'http://twitter.com/oauth/authenticate'
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
#get request token
resp, content = client.request(request_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid Response %s." %resp['status'])
request_token = dict(urlparse.parse_qsl(content))
tmpldict['twitauthurl'] = "%s?oauth_token=%s" % ( authorize_url, request_token['oauth_token'] )
qargs=buzzientlib.urlparse_qs(self.request.url,True,False)
t = template.render(tmpldict)
self.response_body = str(t)
The template just includes a link to twitauthurl
Switched packages to Tweepy and followed this example
http://packages.python.org/tweepy/html/auth_tutorial.html