Cant control api json format , text or video result? - python

CONSUMER_KEY = "*******"
CONSUMER_SECRET = "***"
ACCESS_KEY = "**"
ACCESS_SECRET = ****"
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
requests.get(url, auth=auth)
r = requests.get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=coderFord&count=2',auth=auth)
res=r.json()
def id_al():
for item in res:
b=item['id']
print(b)
req_ya(b)
def req_ya(b):
params = {"ids": b}
ponse = requests.get("https://api.twitter.com/labs/1/tweets/metrics/private", params=params,auth=auth)
ak=ponse.json()
for itema in ak['data']:
for items in res:
k=itema['tweet']
p=itema['video']
data = {"created_at":items['created_at'],"text":items['text'],"tweet_id": itema['tweet_id'], "like_count": k['like_count'],"retweet_count": k['retweet_count'],"quote_count": k['quote_count'],"reply_count": k['reply_count'],"impression_count": k['impression_count'],"view_count":p['view_count']}
data_dict = json.dumps(data, indent = 4, sort_keys = True)
print(json.loads(data_dict))
collection.insert_one(data)
print(id_al())
Error: KeyError: 'video'
If the tweet I send is text, it doesn't send me the video view. And it gives an error.How can I control this
And I can't check because the type part of the tweet doesn't exist.
Response sample like this
https://developer.twitter.com/en/docs/labs/tweet-metrics/quick-start/get-tweets-metrics-private

You can first check there is 'video' in itema.keys() and then perform your logic inside this condition.
Replace this part,
for itema in ak['data']:
for items in res:
k=itema['tweet']
p=itema['video'] # here you are getting error.
with
for itema in ak['data']:
for items in res:
k=itema['tweet']
if 'video' in itema.keys():
p = itema['video']

Related

The request that I send to the Spotify API responds with 404

Here is the code of mine. I censored the CLIENT_SECRET and the CLIENT_ID.
import requests
import json
import base64
CLIENT_ID = "CLIENT_ID"
CLIENT_SECRET = "CLIENT_SECRET"
def get_acces_token(CLIENT_ID: str, CLIENT_SECRET: str) -> str:
authURL = "https://accounts.spotify.com/api/token"
authHeader = {}
authData = {
"grant_type" : "client_credentials"
}
# Base 64
combinated = f"{CLIENT_ID}:{CLIENT_SECRET}"
message = combinated
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_combinated = base64_bytes.decode('ascii')
# request
authHeader['Authorization'] = f"Basic {base64_combinated}"
res = requests.post(authURL,headers = authHeader,data = authData)
ACCCES_TOKEN = res.json()['access_token']
return ACCCES_TOKEN
def get_playlist_tracks(acces_token: str, playlist_id:str) -> dict:
playlist_end_point = f"https://accounts.spotify.com/api/playlists/{playlist_id}"
get_header = {
"Authorization" : f"Bearer {acces_token}"
}
res = requests.get(playlist_end_point,headers=get_header)
return res
token = get_acces_token(CLIENT_ID=CLIENT_ID,CLIENT_SECRET=CLIENT_SECRET)
playlist_id = "3SPj0H71ii0CnhdO6CrhkL?si=c8c41e7c79764265"
tracklist = get_playlist_tracks(token,playlist_id)
print(tracklist)
I don't know why does it respond with 404. The access_token is good. I think that the playlist_end_point should be wrong. Do you have any idea what's wrong in the code?
According to this reference, the right endpoint is https://api.spotify.com/v1/playlists/{playlist_id}/tracks

Shouldn't be accessing this method but get UnboundLocalError: local variable 'response' referenced before assignment

I am getting an error on this line
File "/Users/j/udacity/item_catalog/item-catalog-1490/application.py", line 171, in fbconnect
response.headers['Content-Type'] = 'application/json'
UnboundLocalError: local variable 'response' referenced before assignment
But I don't understand why it's even going to that method because the two states seem to be equal
***************state C155X84FWY0WLD2V5VS2UZDDWXN72F1O
************* login C155X84FWY0WLD2V5VS2UZDDWXN72F1O
But inside that method I have a print for state not equal and it doesn't print that out. In the browser I am getting a 500 error.
#app.route('/fbconnect', methods=['POST'])
def fbconnect():
print "***************state" ,request.args.get('state')
print "*************login session state", login_session['state']
if request.args.get('state') != login_session['state']:
print "*********************state not equal"
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
I'm posting the full content below
#app.route('/fbconnect', methods=['POST'])
def fbconnect():
#state = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32))
#login_session['state'] = state
print "***************state" ,request.args.get('state')
print "*************login session state", login_session['state']
if request.args.get('state') != login_session['state']:
print "*********************state not equal"
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
access_token = request.data
app_id = json.loads(open('fb_client_secrets.json', 'r').read())['web']['app_id']
app_secret = json.loads(open('fb_client_secrets.json', 'r').read())['web']['app_secret']
url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%s&client_secret=%s&fb_exchange_token=%s' % (app_id, app_secret, access_token)
h = httplib2.Http()
result = h.request(url, 'GET')[1]
# Use token to get user info from API
userinfo_url = "https://graph.facebook.com/v2.4/me"
token = result.split("&")[0]
url = 'https://graph.facebook.com/v2.4/me?%s&fields=name,id,email' % token
h = httplib2.Http()
result = h.request(url, 'GET')[1]
data = json.loads(result)
login_session['provider'] = 'facebook'
login_session['username'] = data["name"]
login_session['email'] = data["email"]
login_session['facebook_id'] = data["id"]
# The token must be stored in the login_session in order to properly logout, let's strip out the information before the equals sign in our token
stored_token = token.split("=")[1]
login_session['access_token'] = stored_token
# Get user picture
url = 'https://graph.facebook.com/v2.4/me/picture?%s&redirect=0&height=200&width=200' % token
h = httplib2.Http()
result = h.request(url, 'GET')[1]
data = json.loads(result)
login_session['picture'] = data["data"]["url"]
# see if user exists
user_id = getUserID(login_session['email'])
print "user_id", user_id
if not user_id:
user_id = createUser(login_session)
login_session['user_id'] = user_id
output = ''
output += '<h1>Welcome, '
output += login_session['username']
output += '!</h1>'
output += '<img src="'
output += login_session['picture']
output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
flash("Now logged in as %s" % login_session['username'])
#session['name']=login_session['username']
#print session['']
return output

Meeting room calendars missing - Office 365 API

I am trying to get the list of all calendars for a user. This user has delegate permissions to view the calendar of all the meeting rooms (resources). If I log into the user's account and I am able to see the meeting room calendars in the "Other Calendars" section. I also created my own calendar called "Test" in the "Other Calendars" section.
When I get all the calendar groups first and then iterate through the calendar group list and get the calendars, the list for "Other Calendars" only has "Test" calendar.
Not sure why this is the case. The user is a global administrator as well.
def get_access_info_from_authcode(auth_code, redirect_uri):
post_data = { 'grant_type': 'authorization_code',
'code': auth_code,
'redirect_uri': redirect_uri,
'scope': ' '.join(str(i) for i in scopes),
'client_id': client_registration.client_id(),
'client_secret': client_registration.client_secret()
}
r = requests.post(access_token_url, data = post_data, verify = verifySSL)
try:
return r.json()
except:
return 'Error retrieving token: {0} - {1}'.format(r.status_code, r.text)
def get_access_token_from_refresh_token(refresh_token, resource_id):
post_data = { 'grant_type' : 'refresh_token',
'client_id' : client_registration.client_id(),
'client_secret' : client_registration.client_secret(),
'refresh_token' : refresh_token,
'resource' : resource_id }
r = requests.post(access_token_url, data = post_data, verify = verifySSL)
# Return the token as a JSON object
return r.json()
def get_calendars_from_calendar_groups(calendar_endpoint, token, calendar_groups):
results = []
for group_id in calendar_groups:
get_calendars = '{0}/me/calendargroups/{1}/calendars'.format(calendar_endpoint, group_id)
r = make_api_call('GET', get_calendars, token)
if (r.status_code == requests.codes.unauthorized):
logger.debug('Response Headers: {0}'.format(r.headers))
logger.debug('Response: {0}'.format(r.json()))
results.append(None)
results.append(r.json())
return results
def get_calendars(calendar_endpoint, token, parameters=None):
if (not parameters is None):
logger.debug(' parameters: {0}'.format(parameters))
get_calendars = '{0}/me/calendars'.format(calendar_endpoint)
if (not parameters is None):
get_calendars = '{0}{1}'.format(get_calendars, parameters)
r = make_api_call('GET', get_calendars, token)
if(r.status_code == requests.codes.unauthorized):
logger.debug('Unauthorized request. Leaving get_calendars.')
return None
return r.json()
Logic + Code:
Step 1) Get the authorization URL:
authority = "https://login.microsoftonline.com/common"
authorize_url = '{0}{1}'.format(authority, '/oauth2/authorize?client_id={0}&redirect_uri={1}&response_type=code&state={2}&prompt=consent')
Step 2) Opening the URL takes us to https://login.microsoftonline.com/common where I login as the user:
Step 3) This redirects back to my localhost then the following:
discovery_result = exchoauth.get_access_info_from_authcode(auth_code, Office365.redirect_uri)
refresh_token = discovery_result['refresh_token']
client_id = client_registration.client_id()
client_secret = client_registration.client_secret()
access_token_json = exchoauth.get_access_token_from_refresh_token(refresh_token, Office365.resource_id)
access_token = access_token_json['access_token']
calendar_groups_json = exchoauth.get_calendar_groups(Office365.api_endpoint, access_token)
cal_groups = {}
if calendar_groups_json is not None:
for entry in calendar_groups_json['value']:
cal_group_id = entry['Id']
cal_group_name = entry['Name']
cal_groups[cal_group_id] = cal_group_name
calendars_json_list = exchoauth.get_calendars_from_calendar_groups(Office365.api_endpoint,
access_token, cal_groups)
for calendars_json in calendars_json_list:
if calendars_json is not None:
for ent in calendars_json['value']:
cal_id = ent['Id']
cal_name = ent['Name']
calendar_ids[cal_id] = cal_name
Let me know if you need any other information
The delegate-token which request with the Auth code grant flow only able to get the calendars of sign-in user.
If you want to the get the events from the specific room, you can use the app-only token request with client credential flow.
Here is an helpful link for your reference.

Suds Python Array Response

Using Python 2.7 and SUDS. How would I print just URL from these arrays/objects? I'd like to be able to pick any of the arrays/objects (such as URL) and just print an entire list of them instead of/or in addition to the response already being given from the server.
Here is my request:
from suds.client import Client
import logging
# Specify Login Information
developer_key = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
password = 'xxxxxxxx'
account_guid = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx'
sku = ['A30938', 'B84727']
# Specify URLs
wsdl_url = 'https://api.channeladvisor.com/ChannelAdvisorAPI/v6/InventoryService.asmx?WSDL'
service_url = 'https://api.channeladvisor.com/ChannelAdvisorAPI/v6/InventoryService.asmx'
# Initialize client.
client = Client(wsdl_url, location = service_url)
# Pass login information
login = client.factory.create('APICredentials')
login.DeveloperKey = developer_key
login.Password = password
client.set_options(soapheaders=login)
# Initiate request
for i in sku:
result = client.service.GetInventoryItemImageList(account_guid, i)
# Print the result to the screen.
print result
And here is the results:
(APIResultOfArrayOfImageInfoResponse){
Status = "Success"
MessageCode = 0
ResultData =
(ArrayOfImageInfoResponse){
ImageInfoResponse[] =
(ImageInfoResponse){
PlacementName = "ITEMIMAGEURL1"
FolderName = None
Url = "d3t71aa9ase5oz.cloudfront.net/12801479/images/bear_white.jpg"
},
(ImageInfoResponse){
PlacementName = "ITEMIMAGEURL2"
FolderName = None
Url = "d3t71aa9ase5oz.cloudfront.net/12801479/images/bear_black.jpg"
},
}
}
(APIResultOfArrayOfImageInfoResponse){
Status = "Success"
MessageCode = 0
ResultData =
(ArrayOfImageInfoResponse){
ImageInfoResponse[] =
(ImageInfoResponse){
PlacementName = "ITEMIMAGEURL1"
FolderName = None
Url = "http://d3t71aa9ase5oz.cloudfront.net/12801479/images/m89851.jpg"
},
}
}
Just iterate through the items and get the attribute you want. Something like:
for item in response:
for data in item.ResultData:
print data.Url

instapaper and oauth - 403 "Not logged in" error

I am trying to use the instapaper API, but I keep getting a 403 error for my requests. Here's the code:
consumer_key='...'
consumer_secret='...'
access_token_url = 'https://www.instapaper.com/api/1/oauth/access_token'
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
client.add_credentials('...','...')
params = {}
params["x_auth_username"] = '..'
params["x_auth_password"] = '...'
params["x_auth_mode"] = 'client_auth'
client.set_signature_method = oauth.SignatureMethod_HMAC_SHA1()
resp, token = client.request(access_token_url, method="POST",body=urllib.urlencode(params))
result = simplejson.load(urllib.urlopen('https://www.instapaper.com/api/1/bookmarks/list?' + token))
Any ideas?
You're right about the signature method.
But my main problem was that I wasn't handling the token appropriately. Here's the working code:
consumer = oauth.Consumer('key', 'secret')
client = oauth.Client(consumer)
# Get access token
resp, content = client.request('https://www.instapaper.com/api/1/oauth/access_token', "POST", urllib.urlencode({
'x_auth_mode': 'client_auth',
'x_auth_username': 'uname',
'x_auth_password': 'pass'
}))
token = dict(urlparse.parse_qsl(content))
token = oauth.Token(token['oauth_token'], token['oauth_token_secret'])
http = oauth.Client(consumer, token)
# Get starred items
response, data = http.request('https://www.instapaper.com/api/1/bookmarks/list', method='POST', body=urllib.urlencode({
'folder_id': 'starred',
'limit': '100'
}))
res = simplejson.loads(data)
First, make sure oauth2 is the library you're using. It's the most well-maintained python oauth module.
Second, this looks suspect:
client.set_signature_method = oauth.SignatureMethod_HMAC_SHA1()
You're replacing the set_signature_method function. It should be:
client.set_signature_method(oauth.SignatureMethod_HMAC_SHA1())
You should follow the example here: https://github.com/simplegeo/python-oauth2/blob/master/example/client.py

Categories

Resources