getting value of request response object python - python

I am using python requests to validate mailgun email addresses.
def validateemail(emailaddress):
return requests.get(
"https://api.mailgun.net/v3/address/validate",
auth=("api", EMAILPUBLICVALIDATIONKEY ),
params={'address': emailaddress}
)
validation = validateemail(email)
validationtext = validation.json
validationtext contains the following response:
["{"address": "sdfhdd#assfuck.com", "did_you_mean": …: false, "is_role_address": false, "is_valid": tr", "ue, "mailbox_verification": "unknown", "parts": {"…: "assfuck.com", "local_part": "sdfhdd"}, "reason", "": null}"]
0: "{"address": "sdfhdd#assfuck.com", "did_you_mean": null, "is_disposable_address": false, "is_role_address": false, "is_valid": tr"
1: "ue, "mailbox_verification": "unknown", "parts": {"display_name": null, "domain": "assfuck.com", "local_part": "sdfhdd"}, "reason"
2: "": null}"
in array position 0 there is a is_validproperty. I want to see if its true or not and do some action.
everything I have tried keeps giving me errors
print(validationtext[0].is_valid)
TypeError: 'instancemethod' object has no attribute '__getitem__'
what gives?

validation.json is a function, not an attribute. If you want to get the result, you have to call the function by putting parentheses on the end, as in validationtext = validation.json().

You didn't call the validate.json function correctly. You're missing the parenthesis: validate.json()
Just a minor oversight on your end! Happens to the best of us.

Related

AttributeError 'bytes' object has no attribute 'get'

I'm managing an api and I would like to understand why I have the error "AttributeError 'bytes' object has no attribute 'get'"
import requests
from requests.auth import HTTPBasicAuth
incidents = []
limit = 100
offset = 0
got_all_events = False
while not got_all_events:
alerts = requests.get(f'***', auth=HTTPBasicAuth('***', '***'))
print(alerts)
for alert in alerts:
incident = {
'name': alert.get('hostname'),
'rawJSON': json.dumps(alert),
}
incidents.append(incident)
if len(alerts) == limit:
offset += limit
else:
got_all_events = True
print(incident)
The error is regarding this code line
'name': alert.get('hostname'),
From my api my array is defined like that:
{
"totalSize": 0,
"data": [
{
"hostname": "string",
"domain": "string",
"tags": "string",
"os": {},
}
],
"size": 0
}
Your dictionary has the hostname key nested in a subdictionary as part of a list, so the get is unable to find it.
The only valid targets for the get on alert are totalsize, data, and size.
You could run a get on alert with key data to return a list, then run another get on position 0 of that list with key hostname to get what you want.
A more straightforward approach would just be:
'name': alert["data"][0]["hostname"]
alerts is a requests.Response object, not something decoded from JSON. You have to extract the body first. The iterator for a Response yields a sequence of bytes values, which is where the bytes value you think should be a dict comes from.
response = requests.get(f'***', auth=HTTPBasicAuth('***', '***'))
alerts = response.json()
for alert in alerts:
incident = {
'name': alert.get('hostname'),
'rawJSON': json.dumps(alert),
}
incidents.append(incident)
Thanks for your help.
Now it is working like that:
r=alerts.json()
for alert in r['data']:
incident = {
'hostName': alert["hostname"],
}
incidents.append(incident)
print(json.dumps(incidents, indent=1))

Parse data from multiple numbers in a list or slice - TypeError: list indices must be integers or slices, not str

The problem
I am trying to get a list of statuses of all support tickets from freshdesk.
So far I have been able to request.get all the tickets but it comes out with too much information. So I am trying to only pull the "status" from the json data.
Here is what happens if I want to print just 1 ticket's information:
ticketresponse = requests.get(freshdeskticketsurl, auth = (freshdeskapi, freshdeskpassword))
ticket_json = ticketresponse.json()
ticket_str = json.dumps(ticket_json[0], indent=2)
print(ticket_str)
Response:
{
"cc_emails": [],
"fwd_emails": [],
"reply_cc_emails": [],
"ticket_cc_emails": [],
"fr_escalated": false,
"spam": false,
"email_config_id": null,
"group_id": 43000110950,
"priority": 1,
"requester_id": taking that out of this example,
"responder_id": taking that out of this example,
"source": 3,
"company_id": taking that out of this example,
"status": 5,
"subject": "Receptiontv-min - can't use slide show in powerpoint",
"association_type": null,
"support_email": null,
"to_emails": null,
"product_id": null,
"id": taking that out of this example,
"type": "Trouble Ticket",
"due_by": "2021-03-09T19:21:09Z",
"fr_due_by": "2022-02-25T19:21:09Z",
"is_escalated": false,
"custom_fields": {},
"created_at": "2021-03-02T19:21:09Z",
"updated_at": "2021-03-02T19:21:16Z",
"associated_tickets_count": null,
"tags": []
}
I ONLY want the "status" section. I can do that with only 1 ticket by doing this:
ticketresponse = requests.get(freshdeskticketsurl, auth = (freshdeskapi, freshdeskpassword))
ticket_json = ticketresponse.json()
ticket_str = json.dumps(ticket_json[0]['status'], indent=2)
print(ticket_str)
Response:
5
However, where I am having trouble is trying to print out the status for all the tickets at once. I can print out all the tickets at once by using ticket_str = json.dumps(ticket_json, indent=2) print(ticket_str)
However if I try any of the following lines of code to try and get all the status, it gives me the same error:
ticket_str = json.dumps(ticket_json['status'], indent=2)
Response
TypeError: list indices must be integers or slices, not str
ticketslice = slice(0,20) ticket_str = json.dumps(ticket_json[ticketslice]['status'], indent=2)
Response
TypeError: list indices must be integers or slices, not str
If anyone has any ideas or has a different approach to the idea let me know.
Thank you for your time,
If you want all the statuses you need to loop on the response array, something like that:
for i in range(len(ticket_json)):
ticket_str = json.dumps(ticket_json[i], indent=2)
print(ticket_str['status'])

How to submit post data via urllib2 in python 2.4?

I am trying to submit a POST request with data in json format to create a user using the Crowd API.
Here is the code snippet:
url = 'http://crowdserver/crowd/rest/usermanagement/1/user'
payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample#user.cool"}'
req = urllib2.Request(url, payload)
req.add_header('Content-type','application/json')
req.add_header("Accept", "application/json")
res = urllib2.urlopen(req)
output = resp.read()
print output
print resp.code
I get the following output:
Bad Request
Error code returned is 400
I thought this might perhaps be an encoding issue so replaced payload with:
payload = json.dumps({"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample#user.cool"})
Which returns:
NameError: name 'true' is not defined
So it looks like "active": true is not in an acceptable format.
If I add double quotes such as "active":"true" I get a TypeError; TypeError: not a valid non-string sequence or mapping object
Update
So the type error was indeed solved by setting the active attribute value to True but it turns out the 400 error was returned due to invalid user data, for example missing password or the user already exists read as the user already exists - I find it odd that the error for invalid input and an existing user share the same error code.
In this line:
payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "sample#user.cool"}'
Change ..., "active": true, ... to ..., "active": True, ...
Python's True/False are case-sensitive.

Invalid boolean value using python requests

I am using python requests for posting data in dpd api. If I post the data:
{
"job_id": null,
"collectionOnDelivery": false,
"invoice": null,
"collectionDate": "2012-05-01T09:00:00",
"consolidate": null,
"consignment": []
}
using requests, I am getting the response 200, with error as
{"errorCode":"1008","errorType":"Validation","errorMessage":"Invalid boolean value","obj":"collectionOnDelivery"}
I modified the value of collectionOnDelivery as 0 and tried, but got the same error message. Can anyone help in this?
I guess "null" and "false" aren't a variable or a type you created. In python it is "None" instead of "null", also you need to capitalize first letter of "false" So try this:
{
"job_id": None,
"collectionOnDelivery": False,
"invoice": None,
"collectionDate": "2012-05-01T09:00:00",
"consolidate": None,
"consignment": []
}

How to fix a TypeError in django related to parsing JSON?

I get a TypeError displaying in the browser when I run the code below. The error comes at the last line and says 'NoneType' object is not subscriptable (I am trying to get all the urls for all the items). However it is odd because in the command line, all the urls in the feed get printed. Any ideas on why the items are getting printed in the command line but showing an error in the browser? How do I fix this?
#reddit parse
try:
f = urllib.urlopen("http://www.reddit.com/r/videos/top/.json");
except Exception:
print("ERROR: malformed JSON response from reddit.com")
reddit_posts = json.loads(f.read().decode("utf-8"))["data"]["children"]
reddit_feed=[]
for post in reddit_posts:
if "oembed" in post['data']['media']:
print post["data"]["media"]["oembed"]["url"]
reddit_feed.append(post["data"]["media"]["oembed"]["url"])
print reddit_feed
edit
if post["data"]["media"]["oembed"]["url"]:
print post["data"]["media"]["oembed"]["url"]
There are posts in the returned json with media=null so post['data']['media'] will not have oembed field (and hence, url field):
{
"kind" : "t3",
"data" : {
"downs" : 24050,
"link_flair_text" : null,
"media" : null,
"url" : "http://youtu.be/aNJgX3qH148?t=4m20s",
"link_flair_css_class" : null,
"id" : "rymif",
"edited" : false,
"num_reports" : null,
"created_utc" : 1333847562,
"banned_by" : null,
"name" : "t3_rymif",
"subreddit" : "videos",
"title" : "An awesome young man",
"author_flair_text" : null,
"is_self" : false,
"author" : "Lostinfrustration",
"media_embed" : {},
"permalink" : "/r/videos/comments/rymif/an_awesome_young_man/",
"author_flair_css_class" : null,
"selftext" : "",
"domain" : "youtu.be",
"num_comments" : 2260,
"likes" : null,
"clicked" : false,
"thumbnail" : "http://a.thumbs.redditmedia.com/xUDtCtRFDRAP5gQr.jpg",
"saved" : false,
"ups" : 32312,
"subreddit_id" : "t5_2qh1e",
"approved_by" : null,
"score" : 8262,
"selftext_html" : null,
"created" : 1333847562,
"hidden" : false,
"over_18" : false
}
},
It also seems to be that your exception message doesn't really fit: there are many kinds of exceptions that can be thrown when urlopen blows up, such as IOError. It does not check on whether the returned format is valid JSON as your error message imply.
Now, to mitigate the problem, you need to check if "oembed" in post['data']['media'], and only if it does can you call post['data']['media']['oembed']['url'], notice that I am making the assumption that all oembed blob has url (mainly because you need an URL to embed a media on reddit).
**UPDATE:
Namely, something like this should fix your problem:
for post in reddit_posts:
if isinstance(post['data']['media'], dict) \
and "oembed" in post['data']['media'] \
and isinstance(post['data']['media']['oembed'], dict) \
and 'url' in post['data']['media']['oembed']:
print post["data"]["media"]["oembed"]["url"]
reddit_feed.append(post["data"]["media"]["oembed"]["url"])
print reddit_feed
The reason you have that error is because for some post, post["data"]["media"] is None and so you are basically calling None["oembed"] here. And hence the error: 'NoneType' object is not subscriptable. I've also realized that post['data']['media']['oembed'] may not be a dict and hence you will also need to verify if it is a dict and if url is in it.
Update 2:
It looks like data won't exist sometimes either, so the fix:
import json
import urllib
try:
f = urllib.urlopen("http://www.reddit.com/r/videos/top/.json")
except Exception:
print("ERROR: malformed JSON response from reddit.com")
reddit_posts = json.loads(f.read().decode("utf-8"))
if isinstance(reddit_posts, dict) and "data" in reddit_posts \
and isinstance(reddit_posts['data'], dict) \
and 'children' in reddit_posts['data']:
reddit_posts = reddit_posts["data"]["children"]
reddit_feed = []
for post in reddit_posts:
if isinstance(post['data']['media'], dict) \
and "oembed" in post['data']['media'] \
and isinstance(post['data']['media']['oembed'], dict) \
and 'url' in post['data']['media']['oembed']:
print post["data"]["media"]["oembed"]["url"]
reddit_feed.append(post["data"]["media"]["oembed"]["url"])
print reddit_feed

Categories