I have 3 the same lists how to dig in to id in one of the list?I tryed
create_card_on_the_board[0]['content']['id'] but i got Object is not subscriptable error
def create_card_on_the_board_call(self, id_list, card_count, card_name):
global create_card
responses = []
for i in range(card_count):
create_card = self.rest_api_helper.post_call(
self.base_url + '/cards?' + 'key=' + test_config[
'key'] + '&' + 'token=' + test_config[
'token'] + '&' + f'idList={id_list}' + '&' + f'name={card_name}', headers=None)
responses.append(create_card)
return responses
what you have is a list of 3 HTTP responses.
create_card_on_the_board = [resp1,resp2,resp3]
for resp in create_card_on_the_board:
data = resp.json()
# now you have a python dict named 'data' - assuming all responses have the same content you can do:
print(f'id: {data["id"]}')
create_card_on_the_board[0]['content'] is bytes data. You’ll need to convert it into a dict first. E.g.,
myList = dict(create_card_on_the_board[0]['content'])
Related
This question already has answers here:
Return JSON response from Flask view
(15 answers)
Closed 1 year ago.
in the below posted code, featuresArray is an array of features.i would like the below posted webservice to return the 'featuresArray' as stated in the code. when run the App i receive
internal server error
however, when i return for example
feature[0] or specify the index
the webservice displays the value.
so how can i let the web-service return and display the object freaturesArray
python code:
#app.route("/geodata/<string:polygonCoordinates>", methods=['GET'] )
def geodata(polygonCoordinates):
...
...
url = url.replace(" ","%20")
backendResponseAsJSON = readResponseAsJSONForURL(url)
geojsonObjectAsJSON = loadDataAsJSON(backendResponseAsJSON['geojson'][0])
featuresArray = geojsonObjectAsJSON['features']
for feature in featuresArray:
pass#print (feature)
#baseURL = config['EndPoint']['https'] + config['EndPoint']['url'] + config['EndPoint']['api_key'] + config['EndPoint']['start'] + polygonCoordinates + "," + polygonCoordinates + config['EndPoint']['end'] + polygonCoordinates + "," + polygonCoordinates
#print("baseURL: %s"%(baseURL))
return featuresArray
the array or the list must be enclosed inside
str()
just do as follows:
return str(featureArray)
I need a help so basically I am making a function where we give URL as input with parameter and then it will modify the value of parameters and then print the modified URL.
def findingParams(url):
#url = url+'?name=aman&test=aman'
base_url = url.split('?')[0]
parameters = url.split('?')[1]
myparms = {}
myparms1 = []
payload = "modified_value"
if '&' in parameters:
#['name=123', 'test=321']
parameters = parameters.split('&')
for params in parameters:
myparms1.append(params.split('=')[0])
myparms[(params.split('=')[0])] = payload
#['name', '123']
#['test', '321']
print(f'url = {url}\nparams = {myparms}')
#here I want the ouput as modified parameter
else:
#print(params.split('='))
print(base_url)
print(parameters)
myparms1.append(parameters.split('=')[0])
myparms[(parameters.split('=')[0])] = payload
print(f'url = {url}\nparams = {myparms}')
#['name', '123']
#myparms = {'name':'123', 'test':'321'}
for i in myparms1:
print(f'{base_url}?{i}={myparms[i]}')
#base_url+?[params]=[payload]
I wrote this function and this function works fine with URL that have single parameter eg: testme.com/test.php?name=123 and I also have to make it work with multiple parameters but the problem is that I don't know How can I use for loop to append value in URL for example: If I'm using for loop then output is like this
testme.com/test.php?name=modified_Value
testme.com/test.php?test=modified_Value
but I want URL like this
testme.com/test.php?name=modified_value&test=modified_value.
Try using a temp variable to build the url in your loop, then printing at the end, like this:
result = f'{base_url}?'
for i in myparms1:
result = result + f'{i}=myparms1[i]&'
# remove extra & at end after last parameter
result = result[:-1]
print(result)
#!/usr/bin/env python3
def findingParams(url):
if "?" not in url:
print(url)
else:
base_url, parameters = url.split("?")
payload = "modified_value"
if "&" in parameters:
modif = ""
for params in parameters.split("&"):
name, value = params.split("=")
modif += name + "=" + payload + "&"
print(base_url + "?" + modif.strip("&"))
else:
print(url.split("=")[0] + "=" + payload)
findingParams("testme.com/test.php")
# testme.com/test.php
findingParams("testme.com/test.php?name=123")
# testme.com/test.php?name=modified_value
findingParams("testme.com/test.php?name=12345&test=12345")
# testme.com/test.php?name=modified_value&test=modified_value
findingParams("testme.com/test.php?name=12345&test=12345&foo=12345")
# testme.com/test.php?name=modified_value&test=modified_value&foo=modified_value
Like this ?
I do not know how exactly to ask this question, as I can't share API access. If someone could help with the correct way of asking, will appreciate it.
I have a code which works perfectly fine and executes what I need, BUT when I use this API request code inside the DEF function, it returns with nothing or error...
The error is simple that I cannot get the output, or return with 0 values
This is the code:
def sm_main_data():
#DATA PROCESSING - Impression|Engagements|VideoViews
urlMain = "https://api.simplymeasured.com/v1/analytics/" + key.accountId + "/posts/metrics?\
filter=analytics.timeseries_key.gte(" + config.start + ").lte(" + config.end + ")&\
filter=channel.eq(" + config.which_social_media + ")&\
metrics=analytics.engagement_total,analytics.video.views_count,analytics.impressions&\
dimensions=data_source_id,channel,analytics.timeseries_key.by(" + config.per_what + ")"
headers = {'content-type': 'application/json',
'Authorization': 'Bearer ' + key.token}
#Receive data from SM (main data) / modified it and save as JSON file
responseMain = requests.get(urlMain, headers=headers).json()
pprint.pprint(responseMain)
pass
sm_main_data()
I have tried to print variables inside def:
print(key.accountId)
print(config.start)
print(config.end)
print(config.which_social_media)
print(config.per_what)
Which all printed correctly.
Currently I'm lost... and cannot get an even theoretical idea about what could go wrong. Why this code does not work inside def function???
Edit 1.0
Error
{u'errors': [{u'detail': u'` filter` parameter is not supported.,` metrics` parameter is not supported.,` dimensions` parameter is not supported.',
u'status': u'422',
u'title': u'Unprocessable Entity'}]}
Edit 1.1
Code without def
#DATA PROCESSING - Impression|Engagements|VideoViews
urlMain = "https://api.simplymeasured.com/v1/analytics/" + key.accountId + "/posts/metrics?\
filter=analytics.timeseries_key.gte(" + config.start + ").lte(" + config.end + ")&\
filter=channel.eq(" + config.which_social_media + ")&\
metrics=analytics.engagement_total,analytics.video.views_count,analytics.impressions&\
dimensions=data_source_id,channel,analytics.timeseries_key.by(" + config.per_what + ")"
headers = {'content-type': 'application/json',
'Authorization': 'Bearer ' + key.token}
#Receive data from SM (main data) / modified it and save as JSON file
responseMain = requests.get(urlMain, headers=headers).json()
pprint.pprint(responseMain)
The error shows you are trying to send parameters with extra spaces before them to the server:
` filter` parameter is not supported.
` metrics` parameter is not supported.
Those extra spaces before the names are part of the parameter name, because you included those in your string:
def sm_main_data():
# ...
urlMain = "https://api.simplymeasured.com/v1/analytics/" + key.accountId + "/posts/metrics?\
filter=analytics.timeseries_key.gte(" + config.start + ").lte(" + config.end + ")&\
filter=channel.eq(" + config.which_social_media + ")&\
metrics=analytics.engagement_total,analytics.video.views_count,analytics.impressions&\
dimensions=data_source_id,channel,analytics.timeseries_key.by(" + config.per_what + ")"
# ^^^ those lines are indented but the whitespace is part of the string
You would get the same problem if you had indented the urlMain string definition for any other reason, like for a if statement or a try...except statement, not just a function. You'd have to not indent those parts that are inside a string literal.
Rather than use \ continuations in the string, you could use separate string literals to create one long string, or end the string literal with a closing " followed by a + and a " opening quote on the next line:
urlMain = (
"https://api.simplymeasured.com/v1/analytics/" +
key.accountId + "/posts/metrics?" +
"filter=analytics.timeseries_key.gte(" + config.start + ").lte(" + config.end + ")&" +
"filter=channel.eq(" + config.which_social_media + ")&" +
"metrics=analytics.engagement_total,analytics.video.views_count,analytics.impressions&" +
"dimensions=data_source_id,channel,analytics.timeseries_key.by(" + config.per_what + ")"
)
All those + concatenations are not very readable, you should really use string formatting to insert values into a string.
However, you do not need to build a string like that anyway, as requests can do this for you when you give it a dictionary as the params argument. Use lists to pass in multiple values for a given parameter name:
url = "https://api.simplymeasured.com/v1/analytics/{k.accountId}/posts/metrics".format(
k=key)
params = {
'filter': [ # a list for multiple entries: filter=...&filter=...
'analytics.timeseries_key.gte({c.start}).lte({c.end})'.format(c=config),
'channel.eq({c.which_social_media})'.format(c=config),
],
'metrics': (
'analytics.engagement_total,analytics.video.views_count,'
'analytics.impressions'),
'dimensions':
'data_source_id,channel,'
'analytics.timeseries_key.by({c.per_what})'.format(c=config),
}
headers = {'Authorization': 'Bearer {k.token}'.format(k=key)}
responseMain = requests.get(urlMain, params=params, headers=headers).json()
Here I used str.format() to insert values from the config and key objects; note that the placeholders pull out the attributes
Note: I removed the Content-Type header, as that header doesn't apply to a GET request (which doesn't have content, the request body is always empty).
I have below query stored in a variable I got and I need to fetch value of 'resource_status'.
I need 'UPDATE_IN_PROGRESS'
As requested, putting the code here. The variable evntsdata is storing the events list.
try:
evntsdata = str(hc.events.list(stack_name)[0]).split(" ") # this is the variable that is getting the JSON response (or so)
#print(evntsdata[715:733])
#event_handle = evntsdata[715:733]
if event_handle == 'UPDATE_IN_PROGRESS':
loopcontinue = True
while loopcontinue:
evntsdata = str(hc.events.list(stack_name)[0]).split(" ")
#event_handle = evntsdata[715:733]
if (event_handle == 'UPDATE_COMPLETE'):
loopcontinue = False
print(str(timestamp()) + " " + "Stack Update is Completed!" + ' - ' + evntsdata[-3] + ' = ' + evntsdata[-1])
else:
print(str(timestamp()) + " " + "Stack Update in Progress!" + ' - ' + evntsdata[-3] + ' = ' + evntsdata[-1])
time.sleep(10)
else:
print("No updates to perform")
exit(0)
except AttributeError as e:
print(str(timestamp()) + " " + "ERROR: Stack Update Failure")
raise
print(evntsdata) has below result
['<Event', "{'resource_name':", "'Stackstack1',", "'event_time':", "'2017-05-26T12:10:43',", "'links':", "[{'href':", "'x',", "'rel':", "'self'},", "{'href':", "'x',", "'rel':", "'resource'},", "{'href':", "'x',", "'rel':", "'stack'}],", "'logical_resource_id':", "'Stackstack1',", "'resource_status':", "'UPDATE_IN_PROGRESS',", "'resource_status_reason':", "'Stack", 'UPDATE', "started',", "'physical_resource_id':", "'xxx',", "'id':", "'xxx'}>"]
Do not serialize and parse objects when the data is in front of you. This is inefficient and hard to understand and maintain. The solution is quite trivial:
data = hc.events.list(stack_name)[0].to_dict()
event_handle = data['resource_status']
It's not JSON, it's a class that you've printed
class Event(base.Resource):
def __repr__(self):
return "<Event %s>" % self._info
Try poking around the source code to get access to the dictionary self._info, then access your fields according
For example,
event_info = hc.events.list(stack_name)[0]._info
event_handle = event_info['resource_status']
Though, there may be another way like calling to_dict() instead, since the underscore indicates a private variable
Is there a way to pass an HTTP verb (PATCH/POST) to a function and dynamically use that verb for Python requests?
For example, I want this function to take a 'verb' variable which is only called internally and will either = post/patch.
def dnsChange(self, zID, verb):
for record in config.NEW_DNS:
### LINE BELOW IS ALL THAT MATTERS TO THIS QUESTION
json = requests.verb(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
key = record[0] + "record with host " + record[1]
result = json.loads(json.text)
self.apiSuccess(result,key,value)
I realize I cannot requests.'verb' as I have above, it's meant to illustrate the question. Is there a way to do this or something similar? I'd like to avoid an:
if verb == 'post':
json = requests.post(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}
else:
json = requests.patch(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}
Thanks guys!
Just use the requests.request() method. First argument is the HTTP verb that you want to use. requests.get(), requests.post(), etc. are just aliases to request('GET'), request('POST'): see the doc
Your code becomes:
verb = 'POST'
response = requests.request(
verb,
headers=self.auth,
url=self.API + '/zones/' + str(zID) + '/dns_records',
data={"type":record[0], "name":record[1], "content":record[2]}
)
With the request library, the requests.request method can be relied on directly (as Guillaume's answer suggested).
However, when encountering against libraries that don't have a generic method for methods that have similar calling signatures, getattr can be supplied with the name of the desired method as a string with a default value. Maybe like
action = getattr(requests, verb, None)
if action:
action(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
else:
# handle invalid action as the default value was returned
For the default value it can be a proper action, or just leave it out and an exception will be raised; it's up to you how you want to handle it. I left it as None so you can deal with alternative case in the else section.