Related
I am new to Tkinter, and am having an issue when submitting the code. I had an error before involving the reset button, but that has since been fixed, but now the code does not submit, giving the error that is in the title
Here is the code in its entirety https://pastecord.com/ujoxixyhob.dpr
I dont think this will help too much, so here I have isolated it to this one part:
def Submit():
name = entry_name.get()
residency = ''
if rbtnValue.get() == 'intl':
residency = 'intl'
if rbtnValue.get() == 'dom':
residency = 'dom'
program = comboProgramming.get()
courses = ''
if cbtnProgramming.get() == 'COMP100':
courses += '(COMP100)'
if cbtnWebDesign.get() == 'COMP213':
courses += '\n(COMP213)'
if cbtnSoftEng.get() == 'COMP120':
courses += '\n(COMP120)'
result = name + '\n' + program + '\n' + residency + '\n' + courses
messagebox.showinfo(title='Information', message=result)
This is where the error says it is. I am hoping to find out the error. Thank you
I am using Zapier to catch a webhook and use that info for an API post. The action code runs perfectly fine with "4111111111111111" in place of Ccnum in doSale. But when I use the input_data variable and place it in doSale it errors.
Zapier Input Variable:
Zapier Error:
Python code:
import pycurl
import urllib
import urlparse
import StringIO
class gwapi():
def __init__(self):
self.login= dict()
self.order = dict()
self.billing = dict()
self.shipping = dict()
self.responses = dict()
def setLogin(self,username,password):
self.login['password'] = password
self.login['username'] = username
def setOrder(self, orderid, orderdescription, tax, shipping, ponumber,ipadress):
self.order['orderid'] = orderid;
self.order['orderdescription'] = orderdescription
self.order['shipping'] = '{0:.2f}'.format(float(shipping))
self.order['ipaddress'] = ipadress
self.order['tax'] = '{0:.2f}'.format(float(tax))
self.order['ponumber'] = ponumber
def setBilling(self,
firstname,
lastname,
company,
address1,
address2,
city,
state,
zip,
country,
phone,
fax,
email,
website):
self.billing['firstname'] = firstname
self.billing['lastname'] = lastname
self.billing['company'] = company
self.billing['address1'] = address1
self.billing['address2'] = address2
self.billing['city'] = city
self.billing['state'] = state
self.billing['zip'] = zip
self.billing['country'] = country
self.billing['phone'] = phone
self.billing['fax'] = fax
self.billing['email'] = email
self.billing['website'] = website
def setShipping(self,firstname,
lastname,
company,
address1,
address2,
city,
state,
zipcode,
country,
email):
self.shipping['firstname'] = firstname
self.shipping['lastname'] = lastname
self.shipping['company'] = company
self.shipping['address1'] = address1
self.shipping['address2'] = address2
self.shipping['city'] = city
self.shipping['state'] = state
self.shipping['zip'] = zipcode
self.shipping['country'] = country
self.shipping['email'] = email
def doSale(self,amount, ccnumber, ccexp, cvv=''):
query = ""
# Login Information
query = query + "username=" + urllib.quote(self.login['username']) + "&"
query += "password=" + urllib.quote(self.login['password']) + "&"
# Sales Information
query += "ccnumber=" + urllib.quote(ccnumber) + "&"
query += "ccexp=" + urllib.quote(ccexp) + "&"
query += "amount=" + urllib.quote('{0:.2f}'.format(float(amount))) + "&"
if (cvv!=''):
query += "cvv=" + urllib.quote(cvv) + "&"
# Order Information
for key,value in self.order.iteritems():
query += key +"=" + urllib.quote(str(value)) + "&"
# Billing Information
for key,value in self.billing.iteritems():
query += key +"=" + urllib.quote(str(value)) + "&"
# Shipping Information
for key,value in self.shipping.iteritems():
query += key +"=" + urllib.quote(str(value)) + "&"
query += "type=sale"
return self.doPost(query)
def doPost(self,query):
responseIO = StringIO.StringIO()
curlObj = pycurl.Curl()
curlObj.setopt(pycurl.POST,1)
curlObj.setopt(pycurl.CONNECTTIMEOUT,30)
curlObj.setopt(pycurl.TIMEOUT,30)
curlObj.setopt(pycurl.HEADER,0)
curlObj.setopt(pycurl.SSL_VERIFYPEER,0)
curlObj.setopt(pycurl.WRITEFUNCTION,responseIO.write);
curlObj.setopt(pycurl.URL,"https://secure.merchantonegateway.com/api/transact.php")
curlObj.setopt(pycurl.POSTFIELDS,query)
curlObj.perform()
data = responseIO.getvalue()
temp = urlparse.parse_qs(data)
for key,value in temp.iteritems():
self.responses[key] = value[0]
return self.responses['response']
# NOTE: your username and password should replace the ones below
Ccnum = input_data['Ccnum'] #this variable I would like to use in
#the gw.doSale below
gw = gwapi()
gw.setLogin("demo", "password");
gw.setBilling("John","Smith","Acme, Inc.","123 Main St","Suite 200", "Beverly Hills",
"CA","90210","US","555-555-5555","555-555-5556","support#example.com",
"www.example.com")
r = gw.doSale("5.00",Ccnum,"1212",'999')
print gw.responses['response']
if (int(gw.responses['response']) == 1) :
print "Approved"
elif (int(gw.responses['response']) == 2) :
print "Declined"
elif (int(gw.responses['response']) == 3) :
print "Error"
Towards the end is where the problems are. How can I pass the variables from Zapier into the python code?
David here, from the Zapier Platform team. A few things.
First, I think your issue is the one described here. Namely, I believe input_data's values are unicode. So you'll want to call str(input_data['Ccnum']) instead.
Alternatively, if you want to use Requests, it's also supported and is a lot less finicky.
All that said, I would be remiss if I didn't mention that everything in Zapier code steps gets logged in plain text internally. For that reason, I'd strongly recommend against putting credit card numbers, your password for this service, and any other sensitive data through a Code step. A private server that you control is a much safer option.
Let me know if you've got any other questions!
I've this in urls.py. I'm using paginator. If I get some UsuarioName it responses me the UsuarioName profile and page = 1. But I could see following pages. I've followed Django paginator doc.
url(r'^(?P<UsuarioName>.+)/$', "actividades.views.ShowUserPage"),
url(r'^(?P<UsuarioName>.+)/?(?P<page>.+)/?$', "actividades.views.ShowUserPage"),
views.py, If I write def.. (... UsuarioName, page), is wrong, because there's no parameter for the first url entry.
def ShowUserPage(request, UsuarioName, page):
UsuarioModel = UserProfile.objects.get(user__username=UsuarioName)
UserPage = '<div class="userpage">'
UserPage += '<strong>' + UsuarioModel.titulo + '</strong><br>'
UserPage += UsuarioModel.user.get_username() + "<br>"
UserPage += UsuarioModel.descripcion + "<br>"
UserPage += '</div>'
UserPage += '<strong>Actividades de usuario</strong>'
UserActList = UserActivities.objects.filter(user=UsuarioModel).values('actividad','fecha_alta')
paginator = Paginator(UserActList, 2)
page = 1
try:
ActPage = paginator.page(page)
except PageNotAnInteger:
ActPage = paginator.page(1)
except EmptyPage:
ActPage = paginator.page(1)
#print ActPage.object_list[0]['actividad']
for ActividadActual in ActPage:
UserAct = Actividad.objects.get(id_evento=ActividadActual['actividad'])
UserPage += '<div class="activity">'
UserPage += '<strong>Actividad: ' + UserAct.titulo + '</strong><br>'
UserPage += 'Fecha actividad: ' + UserAct.fecha.strftime("%d-%m-%y") + '<br>'
UserPage += 'Fecha alta: ' + ActividadActual['fecha_alta'].strftime("%d-%m-%y") + '<br>'
UserPage += '</div>'
return HttpResponse(UserPage)
How can I solve it? I know that I can split url path, but I don't like it too much..
Maybe you should do this :
url(r'^(?P<UsuarioName>.+)/(?P<page>\d+)/?$', "actividades.views.ShowUserPage"),
url(r'^(?P<UsuarioName>.+)/$', "actividades.views.ShowUserPage"),
I changed the order of the urls, so that /me/3 wouldn't be matched first by (?P.+). I've also set a number type to the page argument, because it will always be a number, so there is no reason to catch anything else than than.
And then, you should try :
def ShowUserPage(request, UsuarioName, page=1):
It should allow the query without a page to call this function without a page argument (defaulting it to 1).
I didn't try any of this, so if it doesn't help, I'll take a deeper look into it.
I think I got it.
Default page = 1. Always,
next time, there will be a link for getting following pages. I can get it as a POST argument?¿?¿?
I am trying to produce a signature for the Amazon Product Advertising API, been at it a few hours and am still getting a 403 - could anyone have a quick look at the code and tell me if I am doing anything wrong please?
This is the function I use to create the signature
def create_signature(service, operation, version, search_index, keywords, associate_tag, time_stamp, access_key):
start_string = "GET\n" + \
"webservices.amazon.com\n" + \
"/onca/xml\n" + \
"AWSAccessKeyId=" + access_key + \
"&AssociateTag=" + associate_tag + \
"&Keywords=" + keywords + \
"&Operation=" + operation + \
"&SearchIndex=" + search_index + \
"&Service=" + service + \
"&Timestamp=" + time_stamp + \
"&Version=" + version
dig = hmac.new("MYSECRETID", msg=start_string, digestmod=hashlib.sha256).digest()
sig = urllib.quote_plus(base64.b64encode(dig).decode())
return sig;
And this is the function I use to return the string for the request
def ProcessRequest(request_item):
start_string = "http://webservices.amazon.com/onca/xml?" + \
"AWSAccessKeyId=" + request_item.access_key + \
"&AssociateTag=" + request_item.associate_tag + \
"&Keywords=" + request_item.keywords + \
"&Operation=" + request_item.operation + \
"&SearchIndex=" + request_item.search_index + \
"&Service=" + request_item.service + \
"&Timestamp=" + request_item.time_stamp + \
"&Version=" + request_item.version + \
"&Signature=" + request_item.signature
return start_string;
And this is the run code
_AWSAccessKeyID = "MY KEY"
_AWSSecretKey= "MY SECRET KEY"
def ProduceTimeStamp():
time = datetime.datetime.now().isoformat()
return time;
item = Class_Request.setup_request("AWSECommerceService", "ItemSearch", "2011-08-01", "Books", "harry%20potter", "PutYourAssociateTagHere", ProduceTimeStamp(), _AWSAccessKeyID)
item2 = Class_Request.ProcessRequest(item)
An example web request it spits out that produces at 403 is this:-
http://webservices.amazon.com/onca/xml?AWSAccessKeyId=AKIAIY4QS5QNDAI2NFLA&AssociateTag=PutYourAssociateTagHere&Keywords=harry%20potter&Operation=ItemSearch&SearchIndex=Books&Service=AWSECommerceService&Timestamp=2015-02-26T23:53:14.330000&Version=2011-08-01&Signature=KpC%2BUsyJcw563LzIgxf7GkYI5IV6EfmC0%2FsH8LuP%2FEk%3D
There is also a holder class called ClassRequest that just has a field for every request field
The instructions I followed are here if anyone is intrested:- http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html
I hope someone can help, I am new to Python and a bit lost
You can simply use one of the existing solutions
bottlenose
python-amazon-product-api
python-amazon-simple-product-api
available from PyPI.
OR
Compare your solution to one of those:
https://bitbucket.org/basti/python-amazon-product-api/src/41529579819c75ff4f03bc93ea4f35137716ebf2/amazonproduct/api.py?at=default#cl-143
Your timestamp, for instance, looks a bit short.
Check again that the timestamp is right, it should have the format of 2015-03-27T15:10:17.000Z and in your example web request it looks like: 2015-02-26T23:53:14.330000
A good tool to try out your links is Amazon's signed requests helper: https://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html
That Worked for me.
$str = "Service=AWSECommerceService&Operation=ItemSearch&AWSAccessKeyId={Access Key}&Keywords=Harry%20Potter&ResponseGroup=Images%2CItemAttributes%2COffers&SearchIndex=Books&Timestamp=2019-08-11T17%3A51%3A56.000Z";
$ar = explode("&", $str);
natsort($ar);
$str = "GET
webservices.amazon.com
/onca/xml
";
$str .= implode("&", $ar);
$str = urlencode(base64_encode(hash_hmac("sha256",$str,'{Secret Key Here}',true)));
http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&AWSAccessKeyId={Access Key}&Keywords=Harry%20Potter&ResponseGroup=Images%2CItemAttributes%2COffers&SearchIndex=Books&Timestamp=2019-08-11T17%3A51%3A56.000Z&Signature=$str
Remember: If you get this error
Your AccessKey Id is not registered for Product Advertising API. Please use the AccessKey Id obtained after registering at https://affiliate-program.amazon.com/assoc_credentials/home
Go to https://affiliate-program.amazon.com/assoc_credentials/home
This question already has answers here:
How can I print multiple things (fixed text and/or variable values) on the same line, all at once?
(13 answers)
Closed 9 months ago.
So for my first project it is a simple program that prints your name class you are in and what high school you went to. The one thing that is messing me up is for one of them I have to use one print() statement for all this and I need to format it so that each piece of information is on a different line.
What I want for the format:
first_name, last_name
course_id, course_name, email
school
But what I get is
first_name, last_name
course_id, course_name, email
school
How do I remove the space?
My code is as follows:
first_name = 'Daniel'
last_name = 'Rust'
course_id = 'Csci 160'
course_name = 'Computer Science 160'
email = 'blah#gmail.com'
school= 'Red River Highschool'
#variables printed for B
print(first_name, last_name, '\n', course_id, course_name, email, '\n', school, '\n')
print inserts a space between each argument. You can disable this by adding , sep='' after the last '\n', but then there won't be any spaces between first_name and last_name or between course_id and course_name, etc. You could then go on to insert , ' ' manually where you need it in the print statement, but by that point it might be simpler to just give print a single argument formed by concatenating the strings together with explicit spaces:
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name
+ ' ' email + '\n' + school + '\n')
As mentioned here, you can use the sep='' argument to the print() function. That will let you set the separator between printed values (which is a space by default) to whatever you want, including an empty string. You'll have to remember to add spaces between the values that you do want separated. E.g.,
print(first_name, ' ', last_name, '\n', course_id, [...], sep='')
There's a better way to do this, involving the format() method on strings, but your professor is probably saving that one for the next lesson so I won't cover it in detail now. Follow the link to the Python docs, and read the section on Format String Syntax, if you want more details. I'll just show you an example of what your code would look like using format():
print("{} {}\n{} {} {}\n{}".format(first_name, last_name, course_id, course_name, email, school))
Note no \n at the end, since print() automatically adds a newline unless you tell it otherwise.
I recommend reading through str.format() to print your information.
The spaces in your output come from the fact that you've called the print function, passing a list of strings, instead of passing the print function a single string.
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name + ' ' + email + '\n' + school)
yields
Daniel Rust
Csci 160 Computer Science 160 blah#gmail.com
Red River Highschool
Just don't add space in your code
print(first_name, last_name, '\n',course_id, course_name, email, '\n', school, '\n')
There are a number of ways to do so.
First can be str.format() as
print ('{} {}\n{} {} {}\n{}'.format(first_name, last_name, course_id, course_name, email, school))
Second can be
print (first_name, ' ', last_name, '\n',course_id, ' ', course_name, ' ', email, '\n',school, sep = '')
And the third can be
print (first_name + ' ' + last_name + '\n' + str(course_id) + ' ' + course_name + ' ' + email + '\n' + school)
Simple multiline print in python using f-string,
first_name = 'Daniel'
last_name = 'Rust'
course_id = 'Csci 160'
course_name = 'Computer Science 160'
email = 'blah#gmail.com'
school= 'Red River Highschool'
#variables printed for B
print(first_name, last_name, '\n', course_id, course_name, email, '\n', school, '\n')
print(f'''
{first_name}, {last_name}
{course_id}, {course_name}, {email}
{school}''')
Daniel Rust
Csci 160 Computer Science 160 blah#gmail.com
Red River Highschool
Daniel, Rust
Csci 160, Computer Science 160, blah#gmail.com
Red River Highschool
[Program finished]
How to print several lines by using one print statement and how to add new line?
pi = 3.14159 # approximate
diameter = 3
radius = diameter/2
area = pi * radius * radius
circumference = 2 * pi * radius
print("{}\n{}\n{}\n".format(area,radius,circumference))
output::
7.068577499999999
1.5
9.424769999999999
the above you will get corrcet answer for this code.