amazon api not able to find reduced price - amazon-web-services

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

Related

Google Cloud Function HTTP Trigger

I am trying to give arguments to my function by adding URL parameter.
import json
import flask
def location_sort(request):
request_json = request.get_json()
location = json.dumps(request_json)
location = json.loads(location)
reverse_location = {v: k for k, v in location.items()}
x = location.keys()
harf_x = (float(max(x)) + float(min(x))) / 2
y_right = []
y_left = []
sorted_location = []
for i in location:
if float(i) < harf_x:
y_left.append(location[i])
else:
y_right.append(location[i])
y_left.sort()
y_right.sort(reverse=True)
sorted_input = y_left + y_right
for i in sorted_input:
sorted_location.append([reverse_location[i], i])
for i in sorted_location:
i[0],i[1] = float(i[0]),float(i[1])
return sorted_location
def cal_centroid(location):
area = 0 # 면적
centroid_x = 0
centroid_y = 0
temp = 0
for i in range(len(location)):
if i == len(location)-1:
temp = location[i][0]*location[0][1] - location[0][0]*location[i][1]
area += temp*0.5
centroid_x += (location[i][0] + location[0][0]) * temp
centroid_y += (location[i][1] + location[0][1]) * temp
else:
temp = location[i][0]*location[i+1][1] - location[i+1][0]*location[i][1]
area += temp*0.5
centroid_x += (location[i][0] + location[i+1][0]) * temp
centroid_y += (location[i][1] + location[i+1][1]) * temp
centroid_x = round(centroid_x / (6*area), 6)
centroid_y = round(centroid_y / (6*area), 6)
x = [centroid_x, centroid_y]
return json.dumps(x)
def main(request):
request_args = request.args
if request_args and "location" in request_args:
request = request["location"]
request = json.dumps(request)
a = location_sort(request)
return cal_centroid(a)
This is my code for Cloud Function and i run main function. And i tried the URL as
https://<REGION>-<GOOGLE_CLOUD_PROJECT>.cloudfunctions.net/FUNCTION_NAME?location={"37.284213":"127.006481","37.562045":"127.034809","37.528694":"126.907483","37.411124":"127.124356"}
And it returns
Error: could not handle the request
What could be the problem to my code? I am very beginner for GCF and i would be very thankful for your help:)

Group Items together dictionary while loop

I am having trouble storing the ID to keys, like a sub (parent-child) kind of thing. I spent hours on it and could not figure a way to accomplish this. What output I am expecting is at the end of this post. Any help would be great.
import sys
import collections
dict = collections.OrderedDict()
dict["A.1"] = {"parent_child":0}
dict["A.1.1"] = {"parent_child":1}
dict["A.1.1.1"] = {"parent_child":2}
dict["A.1.1.2"] = {"parent_child":2}
dict["A.1.1.3"] = {"parent_child":2}
dict["A.1.2"] = {"parent_child":1}
dict["A.1.2.1"] = {"parent_child":2}
dict["A.1.2.2"] = {"parent_child":2}
dict["A.1.2.2.1"] = {"parent_child":3}
dict["A.1.2.2.2"] = {"parent_child":3}
dict["A.1.2.3"] = {"parent_child":2}
dict["A.1.3"] = {"parent_child":1}
dict["A.1.4"] = {"parent_child":1}
print(dict)
new_dict = {}
p = 0 # previous index
i = 0 # current
n = 1 # next index
current_PC = 0 # current parent_child
next_PC = 0 # next parent_child
previous_id = ""
current_id = ""
next_id = ""
change_current = True
change = True
lst = []
while(True):
if change_current:
current_id = dict.keys()[i]
current_PC = dict.values()[i]["parent_child"]
change_current = False
try:
next_id = dict.keys()[n]
next_PC = dict.values()[n]["parent_child"]
except:
pass # it will go out of index
print("KEY {0}".format(current_id))
if next_PC > current_PC:
if next_PC - current_PC == 1:
lst.append(next_PC)
next_PC += 1
print("next_PC: {0}".format(next_PC))
if next_PC == current_PC:
new_dict[current_id] = lst
lst = []
break
print(new_dict)
Trying to make output looks like this (at in similar way), the new_dict should look like:
new_dict["A.1"] = ["A.1.1", "A.1.2", "A.1.3", "A.1.4"]
new_dict["A.1.1"] = ["A.1.1.1", "A.1.1.2", "A.1.1.3"]
new_dict["A.1.1.1"] = []
new_dict["A.1.1.2"] = []
new_dict["A.1.1.3"] = []
new_dict["A.1.2"] = ["A.1.2.1", "A.1.2.2", "A.1.2.3"]
new_dict["A.1.2.1"] = []
new_dict["A.1.2.2"] = ["A.1.2.2.1", "A.1.2.2.2"]
new_dict["A.1.2.2.1"] = []
new_dict["A.1.2.2.2"] = []
new_dict["A.1.2.3"] = []
new_dict["A.1.3"] = []
new_dict["A.1.4"] = []
This gives you the output you are asking for. Since i did not see a {"parent_child":...} in you desired output i did not proceed with anything else.
options = ["A.1","A.1.1","A.1.1.1","A.1.1.2","A.1.1.3","A.1.2","A.1.2.1","A.1.2.2","A.1.2.2.1","A.1.2.2.2","A.1.2.3","A.1.3","A.1.4"]
new_dict = {}
for i, key in enumerate(options):
new_dict[key] = []
ls = []
for j, opt in enumerate(options):
if (key in opt) and (len(opt)-len(key)==2):
new_dict[key].append(opt)
print(new_dict)
EDIT
Using the comment of #Ranbir Aulakh
options = ["A.1","A.1.1","A.1.1.1","A.1.1.2","A.1.1.3","A.1.2","A.1.2.1","A.1.2.2","A.1.2.2.1","A.1.2.2.2","A.1.2.3","A.1.3","A.1.4"]
new_dict = {}
for i, key in enumerate(options):
new_dict[key] = []
ls = []
for j, opt in enumerate(options):
if (key in opt) and (len(opt.split("."))-len(key.split("."))==1):#(len(opt)-len(key)==2):
new_dict[key].append(opt)
print(new_dict)

what is this error? need more than 1 value to unpack

I am getting the error need more than 1 value to unpack i am using defaultDict to make my list to dictionary.
def getTabsCols(request):
proj_name = request.GET.get('projname')
cursor = connection.cursor()
proj_details = TProjects.objects.get(
attr_project_name=proj_name, attr_project_type='Structure', attr_is_active=1)
pid = proj_details.project_id
query = 'call SP_Get_TABCOL_NAMES('+str(pid)+')'
cursor.execute(query)
proj_details = TProjects.objects.get(
attr_project_name=proj_name, attr_project_type='Structure', attr_is_active=1)
pid = proj_details.project_id
query = 'call SP_Get_TABCOL_NAMES('+str(pid)+')'
cursor.execute(query)
result = cursor.fetchall()
tab_list = []
tab_col_list = []
prd = {}
res = []
for row in result:
tabs = collections.OrderedDict()
schema_name = row[1]
table_name = row[3]
tab = (schema_name + '.' + table_name).encode('utf8')
tabs[tab] = row[5].encode('utf8')
tab_list.append(tabs)
d = collections.defaultdict(set)
for k, v in tab_list:
d1[k].append(v)
d = dict((k, tuple(v)) for k, v in d1.iteritems())
return HttpResponse(d, content_type="text/html")

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.

(Python) Shelve + try: how to search for a key and set it if it doesn't exists without repeating code?

To store the user work folders permanently, I'm using shelve. And to know if the user has the folders configured I'm using a similar code 3 times:
pastaUsuario = os.getenv('HOMEDRIVE') + os.getenv('HOMEPATH')
pastaPrincipal = pastaUsuario + '\\rev'
pastaConfig = pastaPrincipal + '\\config'
config = shelve.open(pastaConfig + '\\config.db')
try:
pastaIsometricosSpooler = config['pastaIsometricosSpooler']
except Exception:
config['pastaIsometricoSpooler'] = raw_input('Digite o caminho da pasta de extração do Spooler: ')
pastaIsometricosSpooler = config['pastaIsometricosSpooler']
finally:
config.close()
config = shelve.open(pastaConfig + '\\config.db')
try:
ultimoIso = config['ultimoIso']
except Exception:
config['ultimoIso'] = raw_input('Digite o tag do isométrico a ser revisado: ')
ultimoIso = config['ultimoIso']
finally:
config.close()
config = shelve.open(pastaConfig + '\\config.db')
try:
ultimaRev = config['ultimaRev']
except Exception:
config['ultimaRev'] = raw_input('Digite a nova revisão: ')
ultimaRev = config['ultimaRev']
finally:
config.close()
How to avoid repeating the almost identical code?
I tried to use the "for" statement with a list:
config = shelve.open(pastaConfig + '\\config.db')
for x in ['pastaIsometricosSpooler', 'ultimoIso', 'ultimaRev']:
try:
x = config[x]
except Exception:
config[x] = raw_input()
x = config[x]
finally:
config.close()
But the variable set doesn't work because of quotes (eg.: 'ultimaRev' = config['ultimaRev'])
Sorry for my bad english!
This is probably best done by using a function rather than trying to make the same code work in a loop. Adapting what you have:
def getconfig( x, prompt ):
try:
theconf= config[x]
except Exception:
config[x] = raw_input( prompt )
theconf= config[x]
return theconf
Then you can use it three times:
config = shelve.open(pastaConfig + '\\config.db')
ultimaRev = getconfig( 'ultimaRev', 'Digite a nova revisão: ')
ultimoIso = getconfig( 'ultimoIso', 'Digite o tag do' )
pastaIsometricosSpooler = getconfig('pastaIsometricosSpooler', 'Digite o caminho da' )
config.close()