Loop List Python for Variable - python

Im trying to loop through a list and insert the 'extensionid' into the URL
extensionid = ['1234','12356']
url = '/restapi/v1.0/account/~/extension/'+extensionid+'/presence'
params = {
'dndStatus': "TakeAllCalls",
}
resp = platform.get(url, params,)
print ((resp.text()))
But I get the error
url = '/restapi/v1.0/account/~/extension/'+extensionid+'/presence'
TypeError: can only concatenate str (not "list") to str [Finished in
1.121s
What am I doing wrong?
Thanks!

You probably need.
extensionid = ['1234','12356']
url = '/restapi/v1.0/account/~/extension/{}/presence'
params = {
'dndStatus': "TakeAllCalls",
}
for id in extensionid: #iterate each id
resp = platform.get(url.format(id), params) #form URL and query.
print ((resp.text()))

extensionid is a list of strings.
So, you cannot concatenate a list with a string as error is telling you.
To access a specific item of the list you have to use an index.
For example:
extensionid[0] // it contains 1234
extensionid[1] // it contains 12356
So, your url can be written like this:
url = '/restapi/v1.0/account/~/extension/'+extensionid[0]+'/presence'
In this case it will be evaluated by python as:
url = '/restapi/v1.0/account/~/extension/1234/presence'
Please consider this simple documentation about lists:
https://www.programiz.com/python-programming/list
To iterate the elements of a list you can use:
for element in extensionid:
url='/restapi/v1.0/account/~/extension/'+ element +'/presence'
print(url)

Related

How can I iterate the entries of an API?

I have this api : https://api.publicapis.org/entries
And I wat to iterate key entries of it. I tried as it follows :
r = requests.get('https://api.publicapis.org/entries')
entries = [] #initializing the vector entries
for i in entries: #iterating it
return(i.text) #trying to print the entries
Then I received the following error :
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
How can I solve this problem ?
For that particular API endpoint, you should be fine with
resp = requests.get('https://api.publicapis.org/entries')
resp.raise_for_status() # raise exception on HTTP errors
entries = resp.json()["entries"] # parse JSON, dig out the entries list
# ... do something with entries.
You can use json.loads to parse response text.
Let me add the full code.
import requests
import json
r = requests.get('https://api.publicapis.org/entries')
entries = json.loads(r.text)['entries'] #initializing the vector entries
for i in entries: #iterating it
API = i['API']
Description = i['Description']

Python: request to add a variable in url

Since I am using a for loop to request a URL which changed with a constant number, how can I parsed the variable in?
total_page = 4
for y in range (total_page):
variable = 20*y+1
base_url = 'https://abcd.com/r='
url = ''.join([base_url, variable])
finviz1 = requests.get(url)
However, an error occurred
url = ''.join([base_url, variable])
TypeError: sequence item 1: expected string or Unicode, int found
How to eliminate the error?
It expects all elements of the array to be a string, whereas you are passing variable as an integer. Convert it into a string before passing it, like this:
url = ''.join([base_url, str(variable)])

Getting error using gender.py

am trying to tell gender by first name.
I been using this code from:
[https://github.com/block8437/gender.py/blob/master/gender.py][1]
import requests, json
def getGenders(names):
url = ""
cnt = 0
if not isinstance(names,list):
names = [names,]
for name in names:
if url == "":
url = "name[0]=" + name
else:
cnt += 1
url = url + "&name[" + str(cnt) + "]=" + name
req = requests.get("https://api.genderize.io?" + url)
results = json.loads(req.text)
retrn = []
for result in results:
if result["gender"] is not None:
retrn.append((result["gender"], result["probability"], result["count"]))
else:
retrn.append((u'None',u'0.0',0.0))
return retrn
Everything was working for 2 days, I have not change anything in the code. I been passing different names in it on and off for 2 days. Suddenly I got this error:
string indices must be integers
on this line:
if result["gender"] is not None:
First, I want to know why this would suddenly happen? Second, How can I fix it?
Iterating through a dictionary iterates through the keys in a dictionary.
results = {"name":"peter","gender":"male","probability":"0.99","count":796}
[result for result in results] # ['count', 'gender', 'name', 'probability']
Iterating through a list iterates through the items of a list.
results = [{"name":"peter","gender":"male","probability":"0.99","count":796}]
[result for result in results] # [{'count': 796, 'gender': 'male', 'name': 'peter', 'probability': '0.99'}]
According to the API description at https://genderize.io/, there are two response formats: a json object for a single name lookup (which json.loads would return as a dictionary), and a list of objects for multiple lookups (which json.loads would return as a list of dictionaries). See the response for
https://api.genderize.io/?name=peter
compared to
https://api.genderize.io/?name[0]=peter
It seems like your error is the result of getting a response in the first format when you are expecting the second. Why might this have changed? Thats a question for the API you are using. It looks to me like your request should always be in the multi-name request format but I can't speak for how they are actually responding.
As for fixing this, you could check the type and wrap naked dictionaries in a list:
retrn = []
if not isinstance(results, list):
results =[results]
for result in results:
if result["gender"] is not None:
retrn.append((result["gender"], result["probability"], result["count"]))
else:
retrn.append((u'None',u'0.0',0.0))

Getting Keyerror when parsing JSON in Python

I have just made a program to parse some data from an api. The api gives data back with a JSON format. When I try to parse it it gives me a key error
url = json.loads(r.text)["url"]
KeyError: 'url'
This is the part of the code
url = json.loads(r.text)["url"]
I am trying to get the data in the plain field. Here is the output from the API:
{"updates":[{"id":"a6aa-8bd","description":"Bug fixes and enhancemets","version":"8.1.30","type":"firmware","url":"https://con-man.company.com/api/v1/file-732e844b","updated":"2017-07-25"}]}
You cannot access url since it is inside update (list), therefore you need to Pass index and then key :
One liner:
>>> url = json.loads(r.text)['updates'][0]['url']
'https://con-man.company.com/api/v1/file-732e844b'
Explicit
>>> jobj = json.loads(r.text)
>>> url = jobj['updates'][0]['url']
'https://con-man.company.com/api/v1/file-732e844b'
try this,
url = json.loads(r.text)["updates"][0]["url"]
{
"updates": [
{
"id":"a6aa-8bd",
"description":"Bug fixes and enhancemets",
"version":"8.1.30",
"type":"firmware",
"url":"https://con-man.company.com/api/v1/file-732e844b",
"updated":"2017-07-25"
}
]
}
Try to visualize of your dict, it has only one key "update" in that key value it has another list and into that list, you has another dict
so if in your case
_dict = json.loads(r.text) # read file and load dict
_list = _dict['updates'] # read list inside dict
_dict_1 = _list[0] # read list first value and load dict
url = _dict_1['url'] # read 'url' key from dict
I used this and works now for me.
json_object = json.loads(response.content.decode("utf-8"))['list'][0]['localPercentDynamicObjectsUsed']

how to convert instance of class "filter" to str directly

url = 'https://www.shanbay.com/read/article/97936/'
temp = filter(str.isdigit,url) #slect numbers
Instead of using for...in expression, can I convert temp to str directly?
filters are lazy in Python 3, you'll need to feed them to a function that will consume them and force them to produce their elements.
url = 'https://www.shanbay.com/read/article/97936/'
temp = filter(str.isdigit,url) # filter object
If you feed this to another function that consumes it, you can get back the elements. If you need a string, just join it:
nums = "".join(temp)
"".join will get all the elements from the filter instance and join them on the empty string "" producing 97936; use that in an int call if you require an int result.
filter returns an iterator, so you'd have to join its elements.
url = 'https://www.shanbay.com/read/article/97936/'
temp = "".join(filter(str.isdigit,url))
How about re.findall()?
import re
url = 'https://www.shanbay.com/read/article/97936/'
temp = re.findall('[0-9]+', url)

Categories

Resources