import json import pprint import urllib.parse #python_sangz consumerKey = 'nononon' consumerSecretKey = 'nononon' accessToken = 'nononon' accessTokenSecret = 'nononon' consumer = oauth2.Consumer(consumerKey, consumerSecretKey) token = oauth2.Token(accessToken, accessTokenSecret) cliente = oauth2.Client(consumer, token) #query = input("novo tweet: ") #queryCodificada = urllib.parse.quote(query, safe='') req = cliente.request( 'https://api.twitter.com/1.1/search/tweets.json?q=bolsonaro') decodeBytes = req[1].decode() jsonLoad = json.loads(decodeBytes) contador = len(jsonLoad['statuses']) for i in jsonLoad['statuses']:
def handleAuthenticationRequest(cls, request): assert oauth is not None if 'oauth_verifier' in request.GET: social = 'twitter' consumer_key = liboauth.conf.CONSUMER_KEY_TWITTER.get() consumer_secret = liboauth.conf.CONSUMER_SECRET_TWITTER.get() access_token_uri = liboauth.conf.ACCESS_TOKEN_URL_TWITTER.get() consumer = oauth.Consumer(consumer_key, consumer_secret) token = oauth.Token( request.session['request_token']['oauth_token'], request.session['request_token']['oauth_token_secret']) client = oauth.Client(consumer, token) oauth_verifier = request.GET['oauth_verifier'] resp, content = client.request(access_token_uri + oauth_verifier, "GET") if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) access_token = dict(cgi.parse_qsl(content)) access_token['screen_name'] = ''.join( [x for x in access_token['screen_name'] if x.isalnum()]) else: parser = httplib2.Http() login_failed_url = '/' if 'error' in request.GET or 'code' not in request.GET: return "" redirect_uri = get_redirect_uri(request) code = request.GET['code'] grant_type = 'authorization_code' state_split = request.GET['state'].split(',') nexturl = state_split[1] if len(state_split) > 1 else '/' social = state_split[0] if social == 'google': consumer_key = liboauth.conf.CONSUMER_KEY_GOOGLE.get() consumer_secret = liboauth.conf.CONSUMER_SECRET_GOOGLE.get() access_token_uri = liboauth.conf.ACCESS_TOKEN_URL_GOOGLE.get() authentication_token_uri = liboauth.conf.AUTHORIZE_URL_GOOGLE.get( ) elif social == 'facebook': consumer_key = liboauth.conf.CONSUMER_KEY_FACEBOOK.get() consumer_secret = liboauth.conf.CONSUMER_SECRET_FACEBOOK.get() access_token_uri = liboauth.conf.ACCESS_TOKEN_URL_FACEBOOK.get( ) authentication_token_uri = liboauth.conf.AUTHORIZE_URL_FACEBOOK.get( ) elif social == 'linkedin': consumer_key = liboauth.conf.CONSUMER_KEY_LINKEDIN.get() consumer_secret = liboauth.conf.CONSUMER_SECRET_LINKEDIN.get() access_token_uri = liboauth.conf.ACCESS_TOKEN_URL_LINKEDIN.get( ) authentication_token_uri = liboauth.conf.AUTHORIZE_URL_LINKEDIN.get( ) params = lib_urlencode({ 'code': code, 'redirect_uri': redirect_uri, 'client_id': consumer_key, 'client_secret': consumer_secret, 'grant_type': grant_type }) headers = {'content-type': 'application/x-www-form-urlencoded'} resp, cont = parser.request(access_token_uri, method='POST', body=params, headers=headers) if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) #google if social == 'google': access_tok = (json.loads(cont))['access_token'] auth_token_uri = authentication_token_uri + access_tok resp, content = parser.request(auth_token_uri, "GET") if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) username = (json.loads(content))["email"] access_token = dict(screen_name=map_username(username), oauth_token_secret=access_tok) whitelisted_domains = liboauth.conf.WHITELISTED_DOMAINS_GOOGLE.get( ) if whitelisted_domains: if username.split('@')[1] not in whitelisted_domains: access_token = "" #facebook elif social == 'facebook': access_tok = (dict(cgi.parse_qsl(cont)))['access_token'] auth_token_uri = authentication_token_uri + access_tok resp, content = parser.request(auth_token_uri, "GET") if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) username = (json.loads(content))["email"] access_token = dict(screen_name=map_username(username), oauth_token_secret=access_tok) #linkedin elif social == 'linkedin': access_tok = (json.loads(cont))['access_token'] auth_token_uri = authentication_token_uri + access_tok resp, content = parser.request(auth_token_uri, "GET") if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) username = (json.loads(content))['emailAddress'] access_token = dict(screen_name=map_username(username), oauth_token_secret=access_tok) return access_token, nexturl
import json import Crypto import oauth2 as oauth import requests import dateutil.parser from ebdjango.settings import JIRA_URL, JIRA_OAUTH_TOKEN, JIRA_OAUTH_TOKEN_SECRET, JIRA_EMAIL, JIRA_API_TOKEN from forecast.helperMethods.oauth.jira_oauth_script import SignatureMethod_RSA_SHA1, create_oauth_client client = create_oauth_client( 'OauthKey', 'dont_care', SignatureMethod_RSA_SHA1(), oauth.Token( JIRA_OAUTH_TOKEN, JIRA_OAUTH_TOKEN_SECRET)) if str(JIRA_EMAIL).find('@') == -1 else None def fetch_filters_and_update_form(form): initial_wip = fetch_wip_filter(form) initial_throughput = fetch_throughput_filter(form) form.save() return initial_wip, initial_throughput def fetch_wip_filter(form): # Sets form's wip_l_b / wip_u_b to positive values (>=0) or to -1 if form.wip_filter: resp_code, response_content = \ make_single_get_req(f"{JIRA_URL}/rest/api/2/search?jql={form.wip_filter}&maxResults=1&fields=None", client) if resp_code == 200:
consumer = oauth.Consumer(CONSUMER_KEY, CONSUMER_SECRET) client = oauth.Client(consumer) 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)) url = "%s?oauth_token=%s" % (AUTH_URL, request_token['oauth_token']) web.open_new_tab(url) oauth_verifier = raw_input('What is the PIN? ') token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) resp, content = client.request(ACCESS_TOKEN_URL, "POST") access_token = dict(urlparse.parse_qsl(content)) print "Access Token:" print "access token = %s" % access_token['oauth_token'] print "access secret = %s" % access_token['oauth_token_secret'] print print "You may now access protected resources using the access tokens above." print toStore = access_token['oauth_token'] + "\n", access_token['oauth_token_secret'] + "\n" authKey = access_token['oauth_token']
def authenticated( request, template='im/third_party_check_local.html', extra_context=None ): if extra_context is None: extra_context = {} consumer = oauth.Consumer(settings.LINKEDIN_TOKEN, settings.LINKEDIN_SECRET) client = oauth.Client(consumer) if request.GET.get('denied'): return HttpResponseRedirect(reverse('edit_profile')) if not 'request_token' in request.session: messages.error(request, 'linkedin handshake failed') return HttpResponseRedirect(reverse('edit_profile')) token = oauth.Token(request.session['request_token']['oauth_token'], request.session['request_token']['oauth_token_secret']) token.set_verifier(request.GET.get('oauth_verifier')) client = oauth.Client(consumer, token) resp, content = client.request(access_token_url, "POST") if resp['status'] != '200': try: del request.session['request_token'] except: pass messages.error(request, 'Invalid linkedin token response') return HttpResponseRedirect(reverse('edit_profile')) access_token = dict(cgi.parse_qsl(content)) token = oauth.Token(access_token['oauth_token'], access_token['oauth_token_secret']) client = oauth.Client(consumer, token) _url = ("http://api.linkedin.com/v1/people/~:(id,first-name,last-name," "industry,email-address)?format=json") resp, content = client.request(_url, "GET") if resp['status'] != '200': try: del request.session['request_token'] except: pass messages.error(request, 'Invalid linkedin profile response') return HttpResponseRedirect(reverse('edit_profile')) profile_data = json.loads(content) userid = profile_data['id'] username = profile_data.get('emailAddress', None) realname = profile_data.get('firstName', '') + ' ' + profile_data.get( 'lastName', '') provider_info = profile_data affiliation = 'LinkedIn.com' user_info = {'affiliation': affiliation, 'realname': realname} try: return handle_third_party_login(request, 'linkedin', userid, provider_info, affiliation, user_info=user_info) except AstakosUser.DoesNotExist, e: third_party_key = get_pending_key(request) return handle_third_party_signup(request, userid, 'linkedin', third_party_key, provider_info, user_info, template, extra_context)
def auth2(): user = UserKeys().user2() consumer = oauth2.Consumer(key=user["CONSUMER_KEY"], secret=user["CONSUMER_SECRET"]) access_token = oauth2.Token(key=user["ACCESS_KEY"], secret=user["ACCESS_SECRET"]) client = oauth2.Client(consumer, access_token) return client
consumer_key = "a" consumer_secret = "b" access_token = "c" access_token_Secret = "d" import oauth2 import json import urllib.parse consumer = oauth2.Consumer(consumer_key, consumer_secret) token = oauth2.Token(access_token, access_token_Secret) cliente = oauth2.Client(consumer, token) query = input("Novo tweet: ") query_codificada = urllib.parse.quote(query, safe="") requisicao = cliente.request( "https://api.twitter.com/1.1/statuses/update.json?status=" + query_codificada, method="POST") decodificar = requisicao[1].decode() objeto = json.loads(decodificar) print(objeto)
def get_credentials(): return dict( consumer = oauth.Consumer(settings.CONSUMER_KEY, settings.CONSUMER_SECRET), token = oauth.Token(settings.TOKEN_KEY, settings.TOKEN_SECRET) )
def oauth2_request(consumer_key, consumer_secret, access_token, access_secret): consumer = oauth2.Consumer(key=consumer_key, secret=consumer_secret) token = oauth2.Token(key=access_token, secret=access_secret) client = oauth2.Client(consumer, token) return client
import urllib2 import json import time url1 = "https://api.twitter.com/1.1/search/tweets.json" params = { "oauth_version": "1.0", "oauth_nonce": oauth2.generate_nonce(), "oauth_timestamp": int(time.time()) } consumer=oauth2.Consumer(key=" sHxIIacqOzagP0sOWvexVuIEF", secret="MYJ28HJDIF8amIww93CSYPflHJiFgjE1emGLWWCDiBKcvmmj1C") token=oauth2.Token(key=" 159854868-umOhzzDEEODyhLgpxbq3iDjH0vLnPSsCyxJ1arcJ", secret="aT7U4TNzFlrIn7Bd8bLZVkBZsYTa13kWcFWVTNiwLncLy") params["oauth_consumer_key"] = consumer.key # VARIABLE AUTHENCATION PARAMETERS params["oauth_token"] = token.key params["q"] = "Jaipur" req = oauth2.Request(method="GET", url=url1, parameters=params) signature_method = oauth2.SignatureMethod_HMAC_SHA1() req.sign_request(signature_method, consumer, token) url = req.to_url() response = urllib2.Request(url) data = json.load(urllib2.urlopen(response)) filename = params["q"]
def oauth_req( url, key, secret, http_method="GET", post_body="", http_headers=None ): consumer = oauth.Consumer( key=ConsumerKey , secret=ConsumerSecret ) token = oauth.Token( key=key, secret=secret ) client = oauth.Client( consumer, token ) (resp,content) = client.request( url, method=http_method, body=post_body, headers=http_headers ) return content
def login_with_token(self, oauth_token, oauth_token_secret): """ When you want to access a user's data using their existing token """ self.token = oauth.Token(oauth_token, oauth_token_secret) self.http = oauth.Client(self.consumer, self.token)
def build_oauth_client(): consumer = oauth.Consumer(consumer_key, consumer_secret) token = oauth.Token(xauth_token, xauth_token_secret) client = oauth.Client(consumer, token) client.set_signature_method = oauth.SignatureMethod_HMAC_SHA1() return client
# below, specifying the additional parameter oauth_callback=<your callback URL>. webbrowser.open("%s?oauth_token=%s" % (AUTHORIZE_URL, request_token['oauth_token'])) # Since we didn't specify a callback, the user must now enter the PIN displayed in # their browser. If you had specified a callback URL, it would have been called with # oauth_token and oauth_verifier parameters, used below in obtaining an access token. oauth_verifier = raw_input('What is the PIN? ') # Step 3: Once the consumer has redirected the user back to the oauth_callback # URL you can request the access token the user has approved. You use the # request token to sign this request. After this is done you throw away the # request token and use the access token returned. You should store this # access token somewhere safe, like a database, for future use. token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) client.ca_certs = certifi.where() resp, content = client.request(ACCESS_TOKEN_URL, "GET") access_token = dict(urlparse.parse_qsl(content)) print "resp from client.request() to ACCESS_TOKEN_URL" print resp print "Access Token:" print " - oauth_token = %s" % access_token['oauth_token'] print " - oauth_token_secret = %s" % access_token['oauth_token_secret'] print print "You may now access protected resources using the access tokens above." print
import time import urllib2 import json url1 = "https://api.twitter.com/1.1/search/tweets.json" params = { "oauth_version": "1.0", "oauth_nonce": oauth2.generate_nonce(), "oauth_timestamp": int(time.time()) } consumer = oauth2.Consumer( key="mjd9CMYbS3Wg7b1yb9YooDVw8", secret="rmcoIiPMJ02oAFReZpAcJJUOxyT578CSNYKAFlMm2Q6vhvxAZr") token = oauth2.Token(key="997359327752085505-cYQzTueD4DrAU79S31qU78em3GWhkAU", secret="Y8IEEOIKYH62bWtQVL9jJuLUyOc48dgvk6Jxx4uor2mbf") params["oauth_consumer_key"] = consumer.key params["oauth_token"] = token.key params["q"] = "jaipur" req = oauth2.Request(method="GET", url=url1, parameters=params) signature_method = oauth2.SignatureMethod_HMAC_SHA1() req.sign_request(signature_method, consumer, token) url = req.to_url() response = urllib2.Request(url) data = json.load(urllib2.urlopen(response)) filename = params["q"] f = open(filename + "_File.txt", "w")
import oauth2 as oauth import urllib2 as urllib # See Assginment 6 instructions or README for how to get these credentials access_token_key = '268629777-NpoDxGVYuugKo5O2BL4j4MWRx63dZLk2pstdd2rh' access_token_secret = 'Bi6fE1gJ6TB8SrcjkfuKUg7AxqozDkaI34WGbvd5U' consumer_key = 'ilVcoxluRMEHAWqpqq7tIA' consumer_secret = 'Orpt32cfpFosYTnDfluEbsAmiubjA1WJc3F7plFiU' _debug = 0 oauth_token = oauth.Token( key='268629777-NpoDxGVYuugKo5O2BL4j4MWRx63dZLk2pstdd2rh', secret='Bi6fE1gJ6TB8SrcjkfuKUg7AxqozDkaI34WGbvd5U') oauth_consumer = oauth.Consumer( key='ilVcoxluRMEHAWqpqq7tIA', secret='Orpt32cfpFosYTnDfluEbsAmiubjA1WJc3F7plFiU') signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() http_method = "GET" http_handler = urllib.HTTPHandler(debuglevel=_debug) https_handler = urllib.HTTPSHandler(debuglevel=_debug) ''' Construct, sign, and open a twitter request using the hard-coded credentials above. '''
def get_oauth_token_and_secret(self, api_key, api_secret, token_expiration): # set trello environment variables os.environ['TRELLO_API_KEY'] = api_key os.environ['TRELLO_API_SECRET'] = api_secret os.environ['TRELLO_EXPIRATION'] = token_expiration # Script to obtain an OAuth token from Trello. # # Must have TRELLO_API_KEY and TRELLO_API_SECRET set in your environment # To set the token's expiration, set TRELLO_EXPIRATION as a string in your # environment settings (eg. 'never'), otherwise it will default to 30 days. # # More info on token scope here: # https://trello.com/docs/gettingstarted/#getting-a-token-from-a-user request_token_url = 'https://trello.com/1/OAuthGetRequestToken' authorize_url = 'https://trello.com/1/OAuthAuthorizeToken' access_token_url = 'https://trello.com/1/OAuthGetAccessToken' expiration = os.environ.get('TRELLO_EXPIRATION', None) scope = os.environ.get('TRELLO_SCOPE', 'read,write') trello_key = os.environ['TRELLO_API_KEY'] trello_secret = os.environ['TRELLO_API_SECRET'] consumer = oauth.Consumer(trello_key, trello_secret) client = oauth.Client(consumer) # Step 1: Get a request token. This is a temporary token that is used for # having the user authorize an access token and to sign the request to obtain # said access 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)) print "Request Token:" print " - oauth_token = %s" % request_token['oauth_token'] print " - oauth_token_secret = %s" % request_token['oauth_token_secret'] print # Step 2: Redirect to the provider. Since this is a CLI script we do not # redirect. In a web application you would redirect the user to the URL # below. print "Go to the following link in your browser:" print "{authorize_url}?oauth_token={oauth_token}&scope={scope}&expiration={expiration}".format( authorize_url=authorize_url, oauth_token=request_token['oauth_token'], expiration=expiration, scope=scope, ) # After the user has granted access to you, the consumer, the provider will # redirect you to whatever URL you have told them to redirect to. You can # usually define this in the oauth_callback argument as well. accepted = 'n' while accepted.lower() == 'n': accepted = raw_input('Have you authorized me? (y/n) ') oauth_verifier = raw_input('What is the PIN? ') # Step 3: Once the consumer has redirected the user back to the oauth_callback # URL you can request the access token the user has approved. You use the # request token to sign this request. After this is done you throw away the # request token and use the access token returned. You should store this # access token somewhere safe, like a database, for future use. token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) resp, content = client.request(access_token_url, "POST") access_token = dict(urlparse.parse_qsl(content)) print "Access Token:" print " - oauth_token = %s" % access_token['oauth_token'] print " - oauth_token_secret = %s" % access_token['oauth_token_secret'] print print "You may now access protected resources using the access tokens above." print # remove trello environment variables del os.environ['TRELLO_API_KEY'] del os.environ['TRELLO_API_SECRET'] return access_token
print "Go to the following link in your browser:" print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token']) # After the user has granted access to you, the consumer, the provider will # redirect you to whatever URL you have told them to redirect to. You can # usually define this in the oauth_callback argument as well. accepted = 'n' while accepted.lower() == 'n': accepted = raw_input('Have you authorized me? (y/n) ') oauth_verifier = raw_input('What is the PIN? ') # Step 3: Once the consumer has redirected the user back to the oauth_callback # URL you can request the access token the user has approved. You use the # request token to sign this request. After this is done you throw away the # request token and use the access token returned. You should store this # access token somewhere safe, like a database, for future use. token = oauth.Token(request_token['oauth_token'],request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) resp, content = client.request(access_token_url, "POST") access_token = dict(urlparse.parse_qsl(content)) print "Access Token:" print access_token.keys() # Save the output of the script which gives the access token print access_token.values() print "You may now access protected resources using the access tokens above."
def main(): parser = setup_optparse() (options, args) = parser.parse_args() config = ConfigParser.ConfigParser() config.read("config.cfg") if options.subdomain: subdomain = options.subdomain else: subdomain = config.get("DEFAULTS", "network") if options.email: email = options.email else: email = config.get("DEFAULTS", "email") config_header = "%s:%s" % (subdomain, email) try: consumer_key = config.get(subdomain, "consumer_key") consumer_secret = config.get(subdomain, "consumer_secret") except ConfigParser.NoSectionError: try: print "Unable to find a key for this network, using the default" consumer_key = config.get("DEFAULTS", "consumer_key") consumer_secret = config.get("DEFAULTS", "consumer_secret") except ConfigParser.NoOptionError: print "No consumer key found, unable to continue" return consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) try: access_key = config.get(config_header, "access_key") access_secret = config.get(config_header, "access_secret") token = oauth.Token(key=access_key, secret=access_secret) except ConfigParser.NoSectionError: print "Couldn't find a token, going without it" token = None host = "external.ningapis.com" client = ningapi.Client(host, subdomain, consumer, token) try: resource_name = args.pop(0) except IndexError: # TODO: Output list of available resources print "Missing resource name" return try: action_name = args.pop(0) except IndexError: # TODO: Output list of available options print "Missing action name" return resource = service_directory.get(resource_name, None) if not resource: print "Invalid resource name: %s" % resource_name return action = getattr(resource, action_name, None) if not action: print "Invalid action for %s: %s" % (action_name, resource_name) return try: action(client, options, args) except ningapi.NingError, e: print "Ning Error: %s" % str(e)
def wrap_oauth(cls, *args, **kwargs): # First argument must be request object request = args[0] # Get the project keyword argumet project = kwargs.get('project', None) # Get the project credentials project_credentials = OAuthCredentials.get_credentials(project) if not project_credentials: msg = { 'response': "invalid_request", 'detail': "project, {0}, has no OAuth credentials".format(project) } return Response(msg, 500) parameters = OAuthCredentials.get_parameters(request.QUERY_PARAMS) oauth_body_hash = parameters.get('oauth_body_hash', None) oauth_signature = parameters.get('oauth_signature', None) oauth_consumer_key = parameters.get('oauth_consumer_key', None) oauth_token = parameters.get('oauth_token', None) if not oauth_body_hash or not oauth_signature or not oauth_consumer_key: msg = { 'response': "invalid_request", 'detail': "Required oauth parameters not provided in the uri" } return Response(msg, 500) if oauth_consumer_key != project_credentials['consumer_key']: msg = { 'response': "access_denied", 'detail': "oauth_consumer_key does not match project, {0}, credentials". format(project) } return Response(msg, 403) uri = '{0}://{1}{2}'.format(settings.TREEHERDER_REQUEST_PROTOCOL, request.get_host(), request.path) #Construct the OAuth request based on the django request object req_obj = oauth.Request( method=request.method, url=uri, parameters=parameters, body=json.dumps(request.DATA), ) server = oauth.Server() token = oauth.Token(key='', secret='') #Get the consumer object cons_obj = oauth.Consumer(oauth_consumer_key, project_credentials['consumer_secret']) #Set the signature method server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1()) try: #verify oauth django request and consumer object match server.verify_request(req_obj, cons_obj, token) except oauth.Error: msg = { 'response': "invalid_client", 'detail': "Client authentication failed for project, {0}".format(project) } return Response(msg, 403) return func(request, *args, **kwargs)
# consumer_key=twitter_credentials.CONSUMER_KEY # consumer_secret=twitter_credentials.CONSUMER_SECRET # access_token=twitter_credentials.ACCESS_TOKEN # access_token_secret=twitter_credentials.ACCESS_TOKEN_SECRET # with open('api_keys.json') as f: # keys = json.load(f) # auth = tweepy.OAuthHandler(consumer_key,consumer_secret) # auth.set_access_token(access_token, access_token_secret) # api = tweepy.API(auth) consumer = oauth.Consumer(key=twitter_credentials.CONSUMER_KEY, secret=twitter_credentials.CONSUMER_SECRET) access_token = oauth.Token(key=twitter_credentials.ACCESS_TOKEN, secret=twitter_credentials.ACCESS_TOKEN_SECRET) client = oauth.Client(consumer, access_token) user = user.lower() output_file = '{}.json'.format(user) output_file_short = '{}_short.json'.format(user) compression = zipfile.ZIP_DEFLATED with open('updated_ids.json') as f: ids = json.load(f) print('total ids: {}'.format(len(ids))) all_data = [] start = 0 end = 100
def callback(): # Accept the callback params, get the token and call the API to # display the logged-in user's name and handle oauth_token = request.args.get('oauth_token') oauth_verifier = request.args.get('oauth_verifier') oauth_denied = request.args.get('denied') # if the OAuth request was denied, delete our local token # and show an error message if oauth_denied: if oauth_denied in oauth_store: del oauth_store[oauth_denied] return render_template('error.html', error_message="the OAuth request was denied by this user") if not oauth_token or not oauth_verifier: return render_template('error.html', error_message="callback param(s) missing") # unless oauth_token is still stored locally, return error if oauth_token not in oauth_store: return render_template('error.html', error_message="oauth_token not found locally") oauth_token_secret = oauth_store[oauth_token] # if we got this far, we have both callback params and we have # found this token locally consumer = oauth.Consumer( app.config['APP_CONSUMER_KEY'], app.config['APP_CONSUMER_SECRET']) token = oauth.Token(oauth_token, oauth_token_secret) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) resp, content = client.request(access_token_url, "POST") access_token = dict(urllib.parse.parse_qsl(content)) screen_name = access_token[b'screen_name'].decode('utf-8') user_id = access_token[b'user_id'].decode('utf-8') # These are the tokens you would store long term, someplace safe real_oauth_token = access_token[b'oauth_token'].decode('utf-8') real_oauth_token_secret = access_token[b'oauth_token_secret'].decode( 'utf-8') # Call api.twitter.com/1.1/users/show.json?user_id={user_id} real_token = oauth.Token(real_oauth_token, real_oauth_token_secret) real_client = oauth.Client(consumer, real_token) real_resp, real_content = real_client.request( show_user_url + '?user_id=' + user_id, "GET") if real_resp['status'] != '200': error_message = "Invalid response from Twitter API GET users/show: {status}".format( status=real_resp['status']) return render_template('error.html', error_message=error_message) response = json.loads(real_content.decode('utf-8')) friends_count = response['friends_count'] statuses_count = response['statuses_count'] followers_count = response['followers_count'] name = response['name'] # don't keep this token and secret in memory any longer return render_template('callback-success.html', screen_name=screen_name, user_id=user_id, name=name, friends_count=real_oauth_token, statuses_count=real_oauth_token_secret, followers_count=followers_count, access_token_url=access_token_url)
def get_client(self, oauth_token=None, oauth_verifier=None): token = oauth.Token(oauth_token['oauth_token'], oauth_token['oauth_token_secret']) if oauth_verifier: token.set_verifier(oauth_verifier) return oauth.Client(self.consumer, token=token)
# shelves_data = gr_client.Shelf.list(user_id) shelves = shelves_data['user_shelf'] for shelf in shelves: shelf_name = shelf['name'] if shelf_name == 'to-read': break shelf_id = shelf['id']['#text'] print(shelf_name) print(shelf['book_count']['#text']) print(shelf_id) consumer = oauth.Consumer(key=GOODREADS_KEY, secret=GOODREADS_SECRET) token = oauth.Token(GOODREADS_KEY, GOODREADS_SECRET) oauth_client = oauth.Client(consumer, token) page = 1 shelf_books_url = f'http://www.goodreads.com/review/list/{shelf_id}.xml' # headers = {'content-type': 'application/x-www-form-urlencoded'} query = { "v": 2, "key": GOODREADS_KEY, "shelf": "read", "per_page": 200, "page": page, } params = urlencode(query)
def conexao(self, consumer_access, consumer_secret, token_access, token_secret): self.consumer = oauth2.Consumer(consumer_access, consumer_secret) self.token = oauth2.Token(token_access, token_secret) self.twitter_client = oauth2.Client(self.consumer, self.token)
def authorization(): """ Authorize `turses` to use a Twitter account. Return a dictionary with `oauth_token` and `oauth_token_secret` if succesfull, `None` otherwise. """ # This function is borrowed from python-twitter developers # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. print 'base_url:{0}'.format(BASE_URL) REQUEST_TOKEN_URL = BASE_URL + '/oauth/request_token' ACCESS_TOKEN_URL = BASE_URL + '/oauth/access_token' AUTHORIZATION_URL = BASE_URL + '/oauth/authorize' consumer_key = TWITTER_CONSUMER_KEY consumer_secret = TWITTER_CONSUMER_SECRET oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) oauth_client = oauth.Client(oauth_consumer) print encode(_('Requesting temp token from Twitter')) resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': response = str(resp['status']) message = _('Invalid respond, requesting temp token: %s') % response print encode(message) return request_token = dict(parse_qsl(content)) print message = _('Please visit the following page to retrieve needed pin code' 'to obtain an Authentication Token:') print encode(message) print print '%s?oauth_token=%s' % (AUTHORIZATION_URL, request_token['oauth_token']) print pincode = raw_input('Pin code? ') token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(pincode) print '' print encode(_('Generating and signing request for an access token')) print '' oauth_client = oauth.Client(oauth_consumer, token) resp, content = oauth_client.request(ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % pincode) access_token = dict(parse_qsl(content)) if resp['status'] == '200': return access_token else: print 'response:{0}'.format(resp['status']) print encode(_('Request for access token failed: %s')) % resp['status'] return None
import oauth2 as oauth import urllib2 as urllib import json # See assignment1.html instructions or README for how to get these credentials api_key = "KqC6fs59CKrijQdhamLzfD6F7" api_secret = "mbWi4JEws2XLoMbjtJpPGoh8Ifc4rwNQdG8UainxXdtRCPTsIL" access_token_key = "447648646-yVsW7zqrv2w4qe0TDofiGXKGF68g4jcpuMfNUrg3" access_token_secret = "sEaKXx0umFLL3srbkpzvADwAGuAV9d9p6hXk4LMBJ5DLy" _debug = 0 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 = "GET" http_handler = urllib.HTTPHandler(debuglevel=_debug) https_handler = urllib.HTTPSHandler(debuglevel=_debug) ''' Construct, sign, and open a twitter request using the hard-coded credentials above. ''' def twitterreq(url, method, parameters): req = oauth.Request.from_consumer_and_token(oauth_consumer, token=oauth_token,
#dados do Facebook API ****Token de usuário expira do app não userToken = 'EAACyRYKnAbcBAIkQgV9VXFmWWwZB6l2a184KE2kLKjXljUoWZCt8vT4MKyAtuxuWCZBp5tj6ERw5gZBHFnGILvUycFm9GWW30Xt1Snx1Xx6ps4Vf90huCyGcZAeF3ZCmMS2NpvdslEvbeCdpW8M4v1GYpjc8u0S0Y26eOlNJZBGd34jDUMAefAraqQeYsUAahIZD' appToken = '196011614470583|K3JP_CGRCg7prLyt0K3ik6z8C_Q' idApp = '196011614470583' chaveApp = '80e069e408c8010253d193a20ffac2e8' consumer_key = '8Cb5GIPaNeqe0e89ih1Rv3BRX' consumer_secret = 'hyAHcf5TUhgzbThoCWQCKaSsTdgs0TMkriUzFZ1hdjOBnax7dl' token_key = '932641261193977856-8OhVGO563z9Wc6XeqV2Cu1pVa4pXbhO' token_secret = 'psQpIJoeZeocYhv2M6YAvceuaOUDlbjyYa4pvMdzqmgPK' consumer = oauth2.Consumer(consumer_key, consumer_secret) token = oauth2.Token(token_key, token_secret) cliente = oauth2.Client(consumer, token) query = input("Pesquisa: ") query_codificada = urllib.parse.quote(query, safe='') requisicao = cliente.request(' ' + query_codificada + '&lang=pt') decodificar = requisicao[1].decode() objeto = json.loads(decodificar) twittes = objeto['statuses'] #Fornece os Twittes dos últimos 7 dias com operadores padrão for twit in twittes: print(twit['user']['screen_name']) pprint(twit['text'])
def __init__(self): self.consumer = oauth2.Consumer('key', 'secret') self.request_token = oauth2.Token('requestkey', 'requestsecret') self.access_token = oauth2.Token('accesskey', 'accesssecret') self.nonce = 'nonce' self.verifier = VERIFIER
def conexao(self, consumer_key, consumer_key_secret, access_token, access_token_secret): self.consumer = oauth2.Consumer(consumer_key, consumer_key_secret) self.token = oauth2.Token(access_token, access_token_secret) self.cliente = oauth2.Client(self.consumer, self.token)