I am trying to fetch ec2 information via python program , but i am not able to get value for public ip address..which printing as None though it has public ip attached to it (i can see from console)
What I tried:
inst_id = []
for reserv in res_inst['Reservations']:
instance = reserv['Instances']
for inst in instance:
ip_addr = inst['PrivateIpAddress']
#print(inst)
if (ip == ip_addr):
inst_id = inst['InstanceId']
inst_type = inst['InstanceType']
image_id = inst['ImageId']
vpc_id = inst['VpcId']
key_name = inst['KeyName']
#pub_ip = inst[u'PublicIpAddress']
pub_ip = inst.get(u'PublicIpAddress')
print(inst_type)
print(inst_id)
print(key_name)
print(vpc_id)
print(pub_ip)
print(image_id)
az = inst['Placement']['AvailabilityZone']
print(az)
for s1 in inst['SecurityGroups']:
sg_name = s1['GroupName']
print(sg_name)
In above code, these syntaxes are not working for public ip..its says key error
pub_ip = inst[u'PublicIpAddress']
pub_ip = inst['PublicIpAddress']
The below syntax works, but giving None as value
pub_ip = inst.get(u'PublicIpAddress')
Output: I am getting all values except print(pub_ip) which is printing as None.
I am sure when i printing whole json string of inst in above code, i see public ip value present in that json dictionary, however, when printing its saying None.
Can any one suggest what wrong thing i am doing here ...
Blockquote
Hi asp,
Please try this...
response= ec2_client.describe_instances()
for reservation in response['Reservations']:
for instance in reservation['Instances']:
print(instance)
Hope it helps..
#r0ck
Im working on a small project of retrieving information about books from the Google Books API using Python 3. For this i make a call to the API, read out the variables and store those in a list. For a search like "linkedin" this works perfectly. However when i enter "Google", it reads the second title from the JSON input. How can this happen?
Please find my code below (Google_Results is the class I use to initialize the variables):
import requests
def Book_Search(search_term):
parms = {"q": search_term, "maxResults": 3}
r = requests.get(url="https://www.googleapis.com/books/v1/volumes", params=parms)
print(r.url)
results = r.json()
i = 0
for result in results["items"]:
try:
isbn13 = str(result["volumeInfo"]["industryIdentifiers"][0]["identifier"])
isbn10 = str(result["volumeInfo"]["industryIdentifiers"][1]["identifier"])
title = str(result["volumeInfo"]["title"])
author = str(result["volumeInfo"]["authors"])[2:-2]
publisher = str(result["volumeInfo"]["publisher"])
published_date = str(result["volumeInfo"]["publishedDate"])
description = str(result["volumeInfo"]["description"])
pages = str(result["volumeInfo"]["pageCount"])
genre = str(result["volumeInfo"]["categories"])[2:-2]
language = str(result["volumeInfo"]["language"])
image_link = str(result["volumeInfo"]["imageLinks"]["thumbnail"])
dict = Google_Results(isbn13, isbn10, title, author, publisher, published_date, description, pages, genre,
language, image_link)
gr.append(dict)
print(gr[i].title)
i += 1
except:
pass
return
gr = []
Book_Search("Linkedin")
I am a beginner to Python, so any help would be appreciated!
It does so because there is no publisher entry in volumeInfo of the first entry, thus it raises a KeyError and your except captures it. If you're going to work with fuzzy data you have to account for the fact that it will not always have the expected structure. For simple cases you can rely on dict.get() and its default argument to return a 'valid' default entry if an entry is missing.
Also, there are a few conceptual problems with your function - it relies on a global gr which is bad design, it shadows the built-in dict type and it captures all exceptions guaranteeing that you cannot exit your code even with a SIGINT... I'd suggest you to convert it to something a bit more sane:
def book_search(search_term, max_results=3):
results = [] # a list to store the results
parms = {"q": search_term, "maxResults": max_results}
r = requests.get(url="https://www.googleapis.com/books/v1/volumes", params=parms)
try: # just in case the server doesn't return valid JSON
for result in r.json().get("items", []):
if "volumeInfo" not in result: # invalid entry - missing volumeInfo
continue
result_dict = {} # a dictionary to store our discovered fields
result = result["volumeInfo"] # all the data we're interested is in volumeInfo
isbns = result.get("industryIdentifiers", None) # capture ISBNs
if isinstance(isbns, list) and isbns:
for i, t in enumerate(("isbn10", "isbn13")):
if len(isbns) > i and isinstance(isbns[i], dict):
result_dict[t] = isbns[i].get("identifier", None)
result_dict["title"] = result.get("title", None)
authors = result.get("authors", None) # capture authors
if isinstance(authors, list) and len(authors) > 2: # you're slicing from 2
result_dict["author"] = str(authors[2:-2])
result_dict["publisher"] = result.get("publisher", None)
result_dict["published_date"] = result.get("publishedDate", None)
result_dict["description"] = result.get("description", None)
result_dict["pages"] = result.get("pageCount", None)
genres = result.get("authors", None) # capture genres
if isinstance(genres, list) and len(genres) > 2: # since you're slicing from 2
result_dict["genre"] = str(genres[2:-2])
result_dict["language"] = result.get("language", None)
result_dict["image_link"] = result.get("imageLinks", {}).get("thumbnail", None)
# make sure Google_Results accepts keyword arguments like title, author...
# and make them optional as they might not be in the returned result
gr = Google_Results(**result_dict)
results.append(gr) # add it to the results list
except ValueError:
return None # invalid response returned, you may raise an error instead
return results # return the results
Then you can easily retrieve as much info as possible for a term:
gr = book_search("Google")
And it will be far more tolerant of data omissions, provided that your Google_Results type makes most of the entries optional.
Following #Coldspeed's recommendation it became clear that missing information in the JSON file caused the exception to run. Since I only had a "pass" statement there it skipped the entire result. Therefore I will have to adapt the "Try and Except" statements so errors do get handled properly.
Thanks for the help guys!
I'm trying to sign some data using CKM_SHA256_RSA_PKCS mechanism... I'm having trouble with the lowlevel-API, as there is virtually no documentation and almost no examples. I'm attempting to do something almost identical to Sign/verify PyKCS11 library
I can't seem to properly convert the code using the lowlevel(awful) API.
Here's some short snippets of my attempt.
a = CPKCS11Lib()
info = CK_INFO()
m = PyKCS11.LowLevel.CK_MECHANISM()
signature = ckbytelist()
m.mechanism = PyKCS11.LowLevel.CKM_SHA256_RSA_PKCS
key = PyKCS11.LowLevel.CK_OBJECT_HANDLE()
slotInfo = CK_SLOT_INFO()
lib='/opt/PTK/lib/libcryptoki.so'
session = CK_SESSION_HANDLE()
sessionInfo = CK_SESSION_INFO()
tokenInfo = CK_TOKEN_INFO()
slotList = ckintlist()
objects = ckobjlist()
binaryData = "XYZ"
sha256 = hashlib.sha256()
sha256.update(str(bytearray(binaryData)))
digest = sha256.digest()
binaryData2 = '\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20' + digest
signMechanism = PyKCS11.Mechanism(PyKCS11.LowLevel.CKM_SHA256_RSA_PKCS, None)
signedData = str(a.C_Sign(CKA_PRIVATE, binaryData2, signMechanism))
print(signedData)
Getting this traceback for signedData
def C_Sign(self, *args): return _LowLevel.CPKCS11Lib_C_Sign(self, *args)
TypeError: in method 'CPKCS11Lib_C_Sign', argument 2 of type 'CK_SESSION_HANDLE'
I have a SOAP web service that I am posting a request to with Python, but I am not sure how to format the return.
UPDATE: Return is an 'instance' being returned by SUDS
I have been able to return just one record of the 40, which is included below:
print len(xmloutput)
print len(xmloutput[1].ODI_Outage)
print xmloutput[1].ODI_Outage[6]
This is the return that I am getting:
2
40
(ODI_Outage){
metersAffected = 28
ERT =
(ert_time){
ert = "2013-07-19T20:50:00Z"
}
Incident =
(incident){
Location =
(location){
mainAddress =
(mailaddress){
townDetail =
(towninfo){
code = "L7L6W3"
name = "BURLINGTON"
stateOrProvince = "ONTARIO"
}
}
PositionPoints =
(coordinates){
xPosition = -79.7833492971
yPosition = 43.3923166879
}
}
}
}
How do I take this return and create either XML or JSON for all of the ODI_Outage objects? Just not sure what to do.
To check the type of the return use: print type(your_return_variable)
In SUDS when i call a method on the server and receive it's response, i access the return values/attributes using . notation (attribute access). Is there a way for me to have the response stored in a python object - after all the WSDL/SUDS has an idea of the structure of the server-data-type.
eg:
SOAP Type: ClientInfo
(reply){
Transaction =
(Transaction){
Reference1 = "1"
Reference2 = "2"
Reference3 = "3"
Reference4 = "4"
Reference5 = "5"
}
Notifications = ""
HasErrors = False
Countries =
(ArrayOfCountry){
Country[] =
(Country){
Code = "AD"
Name = "Andorra"
IsoCode = "020"
StateRequired = False
PostCodeRequired = False
PostCodeRegex = None
InternationalCallingNumber = "376"
},
Can i dump this into a python data-type/object by using the wsdl info?
The suds object is a python object, you're just looking at the print representation. Suds has many hooks where you can digest its results.
https://fedorahosted.org/suds/wiki/Documentation