Python- handling warning and critical parameters with getopt - amazon-web-services

I'm trying to write a script to alert on certain warning and critical levels. So far it only shows ok no matter the output. It ignores warning and critical. What do I need to change?
./check_sqs -p prefix -q queue -s xxx -a xxx -w 5 -c 10
OK: depth = 33;| Prefix_Queue=33
for o, a in opts:
if o in ('-q', '--queue'):
queue_name = a
if o in ('-a', '--access_key'):
access_key = a
if o in ('-s', '--secret_key'):
secret_key = a
if o in ('-p', '--prefix'):
prefix = a
if o in ('-w', '--warning'):
warning = a
if o in ('-c', '--critical'):
critical = a
if access_key == "_none_":
c = SQSConnection()
else:
c = SQSConnection(access_key, secret_key)
cnt = 0
if queue_name != '':
q = c.get_queue(queue_name)
if q == None:
print "ERROR: Invalid queue name " + queue_name
sys.exit(3)
cnt = q.count()
if cnt >= critical:
print 'Critical: depth =', str(cnt) + ';|', q.id.split('/')[2] + "=" + str(cnt)
sys.exit(2)
if cnt >= warning:
print 'Warning: depth =', str(cnt) + ';|', q.id.split('/')[2] + "=" + str(cnt)
sys.exit(1)
if isinstance(cnt, int) and cnt >= 0:
print 'OK: depth =', str(cnt) + ';|', q.id.split('/')[2] + "=" + str(cnt)
sys.exit(0)
else:
print 'Unknown: depth =', str(cnt) + ';|', q.id.split('/')[2] + "=" + str(cnt)
sys.exit(3)
rs = c.get_all_queues()
resp = ''
for q in rs:
name = q.id.split('/')[2]
if name.startswith(prefix):
cnt = cnt + q.count()
resp = resp + name + "=" + str(q.count()) + " "
print 'OK: depth =', str(cnt) + ';|', resp
sys.exit(0)

Thanks, that was very helpful. Critical and Warning are strings, and that's why the comparison was not working. Changing them into int made the trick.
critical = int(critical)
warning = int(warning)

Related

Python coding questions on bitwise shift and logical operations in packet sniffer

import socket
import sys
import struct
import re
#get data
def receiveData(s):
data=''
try:
data=s.recvfrom(65565)
except timeout:
data = ''
except:
print "An error occurred"
sys.exc_info()
return data[0]
#get Type Of Service - 8bits
def getTOS(data):
precedence = {0:'Routine',1:'Priority', 2:'Immediate', 3:'Flash', 4:'Flash Override', 5:'CRITIC/ECP', 6:'Internetwork control', 7:'Network Control'}
delay = {0:'Normal Delay', 1:'Low Delay'}
throughput = {0:'Normal Throughput', 1:'High Throughput'}
reliability = {0:'Normal Reliability', 1:'High Reliability'}
monetary = {0:'Normal Cost', 1:'Minimize monetary cost'}
D = data & 0x10
D >>= 4
T = data & 0x8
T >>= 3
R = data & 0x4
R >>= 2
M = data & 0x2
M >>=1
tabs = "\n\t\t\t"
TOS = precedence [data >> 5]+ tabs + delay[D] + tabs + throughput[T] + tabs + reliability[R] + tabs + monetary[M]
return TOS
def getFlags(data):
flagR = {0:'Cleared to 0'}
flagDF = {0:'Fragment if necessary', 1:'Do not Fragment'}
flagMF = {0:'This is the last Fragment', 1:'More fragments to follow this fragment'}
R = data & 0x8000
R >>= 15
DF = data & 0x4000
DF >>= 14
MF = data & 0x2000
MF >>= 13
tabs = '\n\t\t\t'
flags = flagR[R] + tabs + flagDF[DF] + tabs + flagMF[MF]
return flags
def getProtocol(protocolNr):
protocolFile = open('/root/Desktop/protocol.txt', 'r')
protocolData = protocolFile.read()
protocol = re.findall(r'\n' + str(protocolNr) + ' (?:.)+\n', protocolData)
if protocol:
protocol = protocol[0]
protocol = protocol.replace('\n', '')
protocol = protocol.replace(str(protocolNr), '')
protocol = protocol.lstrip()
return protocol
else:
return "No such protocol found"
s=socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
data = receiveData(s)
unpackedData = struct.unpack('!BBHHHBBH4s4s', data[:20])
version_IHL = unpackedData[0]
version = version_IHL >> 4
IHL = version_IHL & 0xF
TOS = unpackedData[1]
totalLength = unpackedData[2]
ID = unpackedData[3]
flags = unpackedData[4]
fragmentOffset = unpackedData[4] & 0x1FFF
TTL = unpackedData[5]
protocolNr = unpackedData[6]
checksum = unpackedData[7]
sourceAddress = socket.inet_ntoa(unpackedData[8])
destinationAddress = socket.inet_ntoa(unpackedData[9])
print " An IP packed with the size %i was captured :" %totalLength
print " Raw Data :" +data
print "\nParsed Data"
print " Version:\t\t" +str(version)
print " Header Length:\t\t" + str(IHL*4) + "bytes"
print " Type of Service:\t" + getTOS(TOS)
print " ID:\t\t\t" + str(hex(ID)) + " (" + str(ID) + ")"
print " Flags:\t\t\t" + getFlags(flags)
print " Fragment Offset:" + str(fragmentOffset)
print " TTL:\t\t\t" + str(TTL)
print " Protocol:\t\t\t" +getProtocol(protocolNr)
print " Checksum:\t\t\t" +str(checksum)
print " Source:\t\t\t" +sourceAddress
print " Destination:\t\t\t" +destinationAddress
print " Payload:\n" + data[20:]
Below I have extracted some code sections from above and kindly spend some time to answer the following.
(1)
D = data & 0x10
D >>= 4
T = data & 0x8
T >>= 3
R = data & 0x4
R >>= 2
M = data & 0x2
M >>=1
tabs = "\n\t\t\t"
TOS = precedence [data >> 5]+ ......
in the above section could you please explain on what basis D=data & 0x10 is used and right shifted 4 times and also why is precedence shifted 5 times to the right. My question is more like why 0x10 was specifically used to AND with data and then right shifted 4 times to get the Delay bit. I am seeking clarification on all other bits like T, R, M in the above section and the flag bits in the below section too.
(2)
R = data & 0x8000
R >>= 15
DF = data & 0x4000
DF >>= 14
MF = data & 0x2000
MF >>= 13
In the above segment please explain on what basis is used R = data & 0x8000 and shift it 15 times to the right
(3)
fragmentOffset = unpackedData[4] & 0x1FFF
In the above line of code why specifically 0x1FFF was used to AND with unpackedData[4]
Credits to the source code goes to Ana Balica
https://www.youtube.com/watch?v=ghokDuCDcMY
import socket
import sys
import struct
import re
def receiveData(s):
data =''
try:
data , addr =s.recvfrom(655365)
except timout:
data =''
except:
print "An error hapend"
sys.exc_info()
return data
#get Type Of Service - 8bits
def getTOS(data):
precedence = {0:'Routine',1:'Priority', 2:'Immediate', 3:'Flash', 4:'Flash Override', 5:'CRITIC/ECP', 6:'Internetwork control', 7:'Network Control'}
delay = {0:'Normal Delay', 1:'Low Delay'}
throughput = {0:'Normal Throughput', 1:'High Throughput'}
reliability = {0:'Normal Reliability', 1:'High Reliability'}
monetary = {0:'Normal Cost', 1:'Minimize monetary cost'}
D = data & 0x10
D >>= 4
T = data & 0x8
T >>= 3
R = data & 0x4
R >>= 2
M = data & 0x2
M >>=1
tabs = "\n\t\t\t"
TOS = precedence [data >> 5]+ tabs + delay[D] + tabs + throughput[T] + tabs + reliability[R] + tabs + monetary[M]
return TOS
def getFlags(data):
flagR = {0:'Cleared to 0'}
flagDF = {0:'Fragment if necessary', 1:'Do not Fragment'}
flagMF = {0:'This is the last Fragment', 1:'More fragments to follow this fragment'}
R = data & 0x8000
R >>= 15
DF = data & 0x4000
DF >>= 14
MF = data & 0x2000
MF >>= 13
tabs = '\n\t\t\t'
flags = flagR[R] + tabs + flagDF[DF] + tabs + flagMF[MF]
return flags
def getProtocol(protocolNr):
protocolFile = open('protocol.txt', 'r')
protocolData = protocolFile.read()
protocol = re.findall(r'\n' + str(protocolNr) + ' (?:.)+\n', protocolData)
if protocol:
protocol = protocol[0]
protocol = protocol.replace('\n', '')
protocol = protocol.replace(str(protocolNr), '')
protocol = protocol.lstrip()
return protocol
else:
return "No such protocol found"
def showdata(unpackedData):
version_IHL = unpackedData[0]
version = version_IHL >> 4
IHL = version_IHL & 0xF
TOS = unpackedData[1]
totalLength = unpackedData[2]
ID = unpackedData[3]
flags = unpackedData[4]
fragmentOffset = unpackedData[4] & 0x1FFF
TTL = unpackedData[5]
protocolNr = unpackedData[6]
checksum = unpackedData[7]
sourceAddress = socket.inet_ntoa(unpackedData[8])
destinationAddress = socket.inet_ntoa(unpackedData[9])
print " An IP packed with the size %i was captured :" %totalLength
print " Raw Data :" +data
print "\nParsed Data"
print " Version:\t\t" +str(version)
print " Header Length:\t\t" + str(IHL*4) + "bytes"
print " Type of Service:\t" + getTOS(TOS)
print " ID:\t\t\t" + str(hex(ID)) + " (" + str(ID) + ")"
print " Flags:\t\t\t" + getFlags(flags)
print " Fragment Offset:" + str(fragmentOffset)
print " TTL:\t\t\t" + str(TTL)
print " Protocol:\t\t\t" +getProtocol(protocolNr)
print " Checksum:\t\t\t" +str(checksum)
print " Source:\t\t\t" +sourceAddress
print " Destination:\t\t\t" +destinationAddress
print " Payload:\n" + data[20:]
# the public network interface
HOST = socket.gethostbyname(socket.gethostname())
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
for i in range(100):
# receive a package
#print s.recvfrom(65565)
data=receiveData(s)
datastr = str(data)
if len(datastr) >19 :
unpackedData = struct.unpack('!BBHHHBBH4s4s',datastr[:20])
#print unpackedData
showdata(unpackedData)
else:
print data
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
import socket
import sys
import struct
import re
def receiveData(s):
data =''
try:
data , addr =s.recvfrom(655365)
except timout:
data =''
except:
print "An error hapend"
sys.exc_info()
return data
#get Type Of Service - 8bits
def getTOS(data):
precedence = {0:'Routine',1:'Priority', 2:'Immediate', 3:'Flash', 4:'Flash Override', 5:'CRITIC/ECP', 6:'Internetwork control', 7:'Network Control'}
delay = {0:'Normal Delay', 1:'Low Delay'}
throughput = {0:'Normal Throughput', 1:'High Throughput'}
reliability = {0:'Normal Reliability', 1:'High Reliability'}
monetary = {0:'Normal Cost', 1:'Minimize monetary cost'}
D = data & 0x10
D >>= 4
T = data & 0x8
T >>= 3
R = data & 0x4
R >>= 2
M = data & 0x2
M >>=1
tabs = "\n\t\t\t"
TOS = precedence [data >> 5]+ tabs + delay[D] + tabs + throughput[T] + tabs + reliability[R] + tabs + monetary[M]
return TOS
def getFlags(data):
flagR = {0:'Cleared to 0'}
flagDF = {0:'Fragment if necessary', 1:'Do not Fragment'}
flagMF = {0:'This is the last Fragment', 1:'More fragments to follow this fragment'}
R = data & 0x8000
R >>= 15
DF = data & 0x4000
DF >>= 14
MF = data & 0x2000
MF >>= 13
tabs = '\n\t\t\t'
flags = flagR[R] + tabs + flagDF[DF] + tabs + flagMF[MF]
return flags
def getProtocol(protocolNr):
protocolFile = open('protocol.txt', 'r')
protocolData = protocolFile.read()
protocol = re.findall(r'\n' + str(protocolNr) + ' (?:.)+\n', protocolData)
if protocol:
protocol = protocol[0]
protocol = protocol.replace('\n', '')
protocol = protocol.replace(str(protocolNr), '')
protocol = protocol.lstrip()
return protocol
else:
return "No such protocol found"
def showdata(unpackedData):
version_IHL = unpackedData[0]
version = version_IHL >> 4
IHL = version_IHL & 0xF
TOS = unpackedData[1]
totalLength = unpackedData[2]
ID = unpackedData[3]
flags = unpackedData[4]
fragmentOffset = unpackedData[4] & 0x1FFF
TTL = unpackedData[5]
protocolNr = unpackedData[6]
checksum = unpackedData[7]
sourceAddress = socket.inet_ntoa(unpackedData[8])
destinationAddress = socket.inet_ntoa(unpackedData[9])
print " An IP packed with the size %i was captured :" %totalLength
print " Raw Data :" +data
print "\nParsed Data"
print " Version:\t\t" +str(version)
print " Header Length:\t\t" + str(IHL*4) + "bytes"
print " Type of Service:\t" + getTOS(TOS)
print " ID:\t\t\t" + str(hex(ID)) + " (" + str(ID) + ")"
print " Flags:\t\t\t" + getFlags(flags)
print " Fragment Offset:" + str(fragmentOffset)
print " TTL:\t\t\t" + str(TTL)
print " Protocol:\t\t\t" +getProtocol(protocolNr)
print " Checksum:\t\t\t" +str(checksum)
print " Source:\t\t\t" +sourceAddress
print " Destination:\t\t\t" +destinationAddress
print " Payload:\n" + data[20:]
# the public network interface
HOST = socket.gethostbyname(socket.gethostname())
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
for i in range(100):
# receive a package
#print s.recvfrom(65565)
data=receiveData(s)
datastr = str(data)
if len(datastr) >19 :
unpackedData = struct.unpack('!BBHHHBBH4s4s',datastr[:20])
#print unpackedData
showdata(unpackedData)
else:
print data
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)

IndexError: Python list index out of range

I have an empty list, (r) and declared first element as r[0] = a
import time, urllib.request,random
def getDictionary():
word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_site)
txt = response.read()
return txt.splitlines()
def getWordsList(listOfWords, sample):
word = ""
randWords = []
for i in range(0,sample):
while(len(word) <=2):
word = random.choice(listOfWords).decode('utf-8')
randWords.append(word)
word = ""
return randWords
start = True
noOfWords = 25
words = getDictionary()
wordsList = getWordsList(words, noOfWords)
start = True
print ("\nINSTRUCTIONS\nWhen the coundown gets to zero, type the word in lowercase letters!\n That's the only rule!")
name = input("What is your name? ")
name = name.split(" ")
input("Press enter when ready...")
while start == True:
print("Game will start in: ")
print ("3 seconds")
time.sleep(1)
print ("2 seconds")
time.sleep(1)
print ("1 seconds")
time.sleep(1)
times = []
k = list()
r = list()
for i in range(25):
startTime = time.time()
userWord = input(str(i+1) + ". " + wordsList[i].capitalize() + " " )
k.append(wordsList[i].capitalize())
if (userWord.lower() == wordsList[i].lower()):
endTime = time.time()
times.append(endTime - startTime)
r[i] = str(endTime - startTime)
else:
times.append("Wrong Word")
r[i] = ("Wrong Word")
Above is where I am having a problem.
for i in range(25):
startTime = time.time()
print (str(i+1) + ". " + str(k[i]) + ": " + str(times[i]) )
a = 0
for i in range(25):
a = a+i
for i in range(25):
if r[i] == "Wrong Word":
r = r.pop(i)
b = (a/len(r))
c = round(b, 2)
print (c)
start = False
here is my error:
r[i] = "Wrong Word"
IndexError: list assignment index out of range
The pop() method removes an element from the list and returnes it (see an example). What I think is happening is that at some point the condition of the if statment resolves to true. Next, after calling r.pop(i) r is replaced by its i-th element. It's probpably a string so calling its (i+1)-th element later can result in Index out of range error.
In other words, something like this is happening:
r = ["a", "foo", "bar", "baz"]
for i in range(4):
if r[i] == "a": # for i=0 this gives "a" == "a"
r = r.pop(i) # later,this results in r = "a"
next loop iteration with i = 1 will result in "a"[1] which will result in Index out of range.
All in all instead of:
for i in range(25):
if r[i] == "Wrong Word":
r = r.pop(i)
you could just write:
r = [item for item in r if item != "Wrong word"]
which would be also more pythonic solution.

Syntax error for else and elif (Can't determine if structure issue)

I'm very new to python and I've been working on a basic calculator within python for the last few hours (rhetorical I know, given what python has built in, but it's part of my learning process), I've run into an error I can't seem to fix, generally I'm able to get my scripts on their feet and running with the assistance of a couple of Google searches but this one has me stumped. I'm getting a syntax error where I have an else, and while at first I was pretty sure it was a structure issue, rewriting the script didn't fix anything, vague I know, so here's the script (I've marked the spot with a comment) :
def Calculator():
tempnums = [] #stores nums only
tempfuncs = [] #stores funcs only
tmpfuncs = {} #stores funcs only
times = lambda multiply: tempnums[0]*tempnums[1]
div = lambda divide: tempnums[0]%tempnums[1]
plus = lambda add: tempnums[0]+tempnums[1]
minus = lambda subtract:tempnums[0]-tempnums[1]
done = 0
varnum = 0
xtimes = 0
divtimes = 0
plustimes = 0
mintimes = 0
while done == 0: #USER INPUT PROCESS
varnum = varnum + 1
tempint = input() #nums
exec("num%d = tempint" % (varnum))
function = raw_input() #functions
if function != "=":
if function == 'x':
if x not in tmpfuncs:
xtimes = xtimes + 1
tmpfuncs[x] = times
else:
xtimes = xtimes + 1
exec("tmpfuncs[x%d] = times" % (xtimes)
else: #ERROR COMES HERE
if function == '//':
if dv not in tmpfuncs:
divtimes = divtimes + 1
tmpfuncs[dv] = div
else:
divtimes = divtimes + 1
exec("tmpfuncs[dv%d] = div" % (divtimes)
if function == '+':
if pls not in tmpfuncs:
plustimes = plustimes + 1
tmpfuncs[pls] = plus
else:
plustimes = plustimes + 1
exec("tmpfuncs[pls%d] = plus" % (plustimes)
if function == '-':
if mn not in tmpfuncs:
mintimes = mintimes + 1
tmpfuncs[mn] = minus
else:
mintimes = mintimes + 1
exec("tmpfuncs[mn%d] = minus" % (mintimes)
else: #user has selected to calculate input
done = 1
for i in range(1, varnum + 1):
exec("tempnums.append(num%d)" % (i)) #adding nums to a list with dynamic var names
print tmpfuncs
#next we'll make it so that tempnums[0] is the changing result as we use tempnums 0 and 1 to calculate the answer, deleting one as we go until there is only zero
Calculator()
Calculator()
I'm hoping this is legible as I'm posting from mobile (as a matter of fact I'm writing this from mobile as well).
The line above the else is missing a closing parens:
exec("tmpfuncs[x%d] = times" % (xtimes)
should be
exec("tmpfuncs[x%d] = times" % (xtimes))
The same error occurs in many other of your exec lines. Also, I suggest you consider restructuring your code so you do not need to use exec at all.

Python: Trying to speed up a program that is running very slow

So, this program parses an e-mail address and a plain-text password from a text file. Then, it runs them through a few encryption routines and appends the encrypted text onto the end of the e-amil address:password entry in a new file.
import io
from Crypto.Cipher import AES
import base64
import struct
def str_to_a32(b):
if len(b) % 4:
b += '\0' * (4 - len(b) % 4)
return struct.unpack('>%dI' % (len(b) / 4), b)
def a32_to_str(a):
return struct.pack('>%dI' % len(a), *a)
def aes_cbc_encrypt(data, key):
encryptor = AES.new(key, AES.MODE_CBC, '\0' * 16)
return encryptor.encrypt(data)
def aes_cbc_encrypt_a32(data, key):
return str_to_a32(aes_cbc_encrypt(a32_to_str(data), a32_to_str(key)))
def base64urlencode(data):
data = base64.b64encode(data)
for search, replace in (('+', '-'), ('/', '_'), ('=', '')):
data = data.replace(search, replace)
return data
def a32_to_base64(a):
return base64urlencode(a32_to_str(a))
def stringhash(s, aeskey):
s32 = str_to_a32(s)
h32 = [0, 0, 0, 0]
for i in xrange(len(s32)):
h32[i % 4] ^= s32[i]
for _ in xrange(0x4000):
h32 = aes_cbc_encrypt_a32(h32, aeskey)
return a32_to_base64((h32[0], h32[2]))
def prepare_key(a):
pkey = [0x93C467E3, 0x7DB0C7A4, 0xD1BE3F81, 0x0152CB56]
for _ in xrange(0x10000):
for j in xrange(0, len(a), 4):
key = [0, 0, 0, 0]
for i in xrange(4):
if i + j < len(a):
key[i] = a[i + j]
pkey = aes_cbc_encrypt_a32(pkey, key)
return pkey
with io.open('user_list.txt', 'r') as file:
with io.open('user_list_enc.txt', 'a') as enc_file:
for line in file:
email_split, pass_split = line.replace('\n', '').split(":")
password_aes = prepare_key(str_to_a32(pass_split))
uh = stringhash(email_split.lower(), password_aes)
enc_file.write(email_split + ":" + pass_split + ":" + uh + "\n")
print email_split + ":" + pass_split + ":" + uh + "\n"

amazon api not able to find reduced price

I am using below code snippet to get the red reduced price from amazon but simehow I am always getting the old price and not the reduced red one.
enter code here`def getSignedUrlAmazon(searchvalue):
params = {'ResponseGroup':'Medium',
'AssociateTag':'',
'Operation':'ItemSearch',
'SearchIndex':'All',
'Keywords':searchvalue}
action = 'GET'`enter code here`
server = "webservices.amazon.in"
path = "/onca/xml"
params['Version'] = '2011-08-01'
params['AWSAccessKeyId'] = AWS_ACCESS_KEY_ID
params['Service'] = 'AWSECommerceService'
params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# Now sort by keys and make the param string
key_values = [(urllib.quote(k), urllib.quote(v)) for k,v in params.items()]
key_values.sort()
# Combine key value pairs into a string.
paramstring = '&'.join(['%s=%s' % (k, v) for k, v in key_values])
urlstring = "http://" + server + path + "?" + \
('&'.join(['%s=%s' % (k, v) for k, v in key_values]))
# Add the method and path (always the same, how RESTy!) and get it ready to sign
hmac.update(action + "\n" + server + "\n" + path + "\n" + paramstring)
# Sign it up and make the url string
urlstring = urlstring + "&Signature="+\
urllib.quote(base64.encodestring(hmac.digest()).strip())
return urlstring
forgot the price grabbing part:
def getDataAmazon(searchvalue,PRICE, lock):
try:
searchvalue = removeStopWord(searchvalue)
url = getSignedUrlAmazon(searchvalue)
data = etree.parse(url)
root = objectify.fromstring(etree.tostring(data, pretty_print=True))
gd=[]
gd1=[]
counter = 0
if hasattr(root, 'Items') and hasattr(root.Items, 'Item'):
for item in root.Items.Item:
cd={}
priceCheckFlag = False
try :
if hasattr(item.ItemAttributes, 'EAN'):
cd['EAN'] = str(item.ItemAttributes.EAN)
elif hasattr(item, 'ASIN'):
cd['ASIN'] = str(item.ASIN)
cd['productName'] = str(item.ItemAttributes.Title)
if hasattr(item, 'SmallImage'):
cd['imgLink'] = str(item.SmallImage.URL)
elif hasattr(item, 'MediumImage'):
cd['imgLink'] = str(item.MediumImage.URL)
cd['numstar'] = "0"
cd['productdiv'] = '1'
cd['sellername'] = 'Amazon'
if hasattr(item, 'DetailPageURL'):
cd['visitstore'] = str(item.DetailPageURL)
if hasattr(item.ItemAttributes, 'ListPrice') and hasattr(item.ItemAttributes.ListPrice, 'Amount'):
cd['price'] = item.ItemAttributes.ListPrice.Amount/100.0
elif hasattr(item, 'OfferSummary') and hasattr(item.OfferSummary, 'LowestNewPrice'):
cd['price'] = item.OfferSummary.LowestNewPrice.Amount/100.0