AttributeError: 'Driver' object has no attribute 'id' - python

i have a deployment on appengine, im getting this error when i'm tryng to assign a trip
def get(self):
from trips.end_trip import notify_cancelation
"""
GET /2/drivers/report_trip_arrival
> trip_id /custom_id
> device_id
> driver_id
> event_timestamp
< 200 application/json
Changes the trip status to 4, your taxi has arrived
"""
responseJSON = {}
self.response.headers['Content-Type'] = "application/json"
trip_id = self.request.get("trip_id")
custom_trip_id = self.request.get("custom_id")
device_id = self.request.get("device_id")
logging.info("Report arrival")
logging.info(str(trip_id))
logging.info(str(custom_trip_id))
logging.info(str(device_id))
#Get the trip
# fixing
try:
trip = trip_finder.find_trip(trip_id=trip_id, custom_id=custom_trip_id)
except:
trip = None
responseJSON["Status"] = "OK"
return
driver_id = self.request.get('driver_id')
if driver_id:
driver_id = int(driver_id)
if trip.selected_driver.get().id() != driver_id:
responseJSON = {'status': 'OK', 'Staus': 'OK'}
json.dump(responseJSON, self.response.out)
return
if trip:
#deferred.defer(notify_arrival, trip.key.id(), _queue="delivery")
params = {}
params["trip_id"] = trip.key.id()
taskqueue.add(url="/2/delivery/task/notify_arrival", params=params, queue_name="delivery")
last_status = trip.last_status()
#If we are already on status 4, we just return OK
if last_status.id != "4":
#Update the status
#ripStatus(trip=trip.key, id="4", message=trip_statuses["4"], timestamp=now()).put()
trip.change_status("4")
#Alert the passenger
name = trip.traveler_name.split()[0] if trip.traveler_name else ""
message_status = name + ", ha llegado tu taxi :)"
responseJSON["Status"] = "OK"
responseJSON["status"] = "OK"
# if the trip was canceled notify the driver
if last_status.id == "16":
#deferred.defer(notify_cancelation, trip.key.id(), _queue="endtrip")
params = {'trip_id': trip.key.id()}
taskqueue.add(url="/2/trips/task/notify_cancelation", params=params, queue_name="endtrip")
#deferred.defer(notify_cancelation, trip.key.id(), _queue="endtrip")
else:
responseJSON["Status"] = "OK"
responseJSON["status"] = "OK"
self.response.out.write(json.dumps(responseJSON))
This is the full details:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~precise-line-762/v-4-4-03.383164018327881359/security/security.py", line 47, in wrapper
return handler(request)
File "/base/data/home/apps/s~precise-line-762/v-4-4-03.383164018327881359/drivers/handlers.py", line 141, in get
if trip.selected_driver.get().id() != driver_id:
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3640, in __getattr__
return super(Expando, self).__getattribute__(name)
AttributeError: 'Driver' object has no attribute 'id'

You have to pick object's ID from key property.
Looks like your trip.selected_driver is a Key already. If you want to ensure the object exist then call trip.selected_driver.get().key.id()

Related

Django Python Error: 'dict' object has no attribute 'status_code'

I'm getting the following error after a post:
'dict' object has no attribute 'status_code'
I'm using django 3.1.7 and python 3.8.
Can anyone help me with this problem? I'm new to this stuff and can't seem to solve it alone.
the .py:
from gluon import *
from .models import *
from lxml import etree as ET
import re
import requests
def update_customer(request, p_externalcode, p_addressexternalcode, p_street, p_nr, p_addition, p_zipcode, p_city, p_country, p_complexnr, p_region, p_company_code, controle, omgeving):
url = request.session['omgeving_url']+'/mds/soapservice/outbound.asmx'
lic = '{'+request.session['omgeving_lic']+'}'
gebruiker = request.session['omgeving_geb']
wachtwoord = request.session['omgeving_pas']
omgnaam = request.session['omgeving_naam']
headers = {'content-type':'text/xml', 'charset':'utf-8'}
# opbouw van de SOAP-xml
SOAP_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
PCA_NS = 'http://www.pcamobile.com/mds'
ns_map = {'SOAP': SOAP_NS}
pca_map = {None: PCA_NS}
envelope = ET.Element(ET.QName(SOAP_NS, 'Envelope'), nsmap=ns_map)
body = ET.SubElement(envelope, ET.QName(SOAP_NS, 'Body'), nsmap=ns_map)
rqoutboundmessage = ET.SubElement(body, ET.QName(PCA_NS,'RqOutboundMessage'), nsmap=pca_map)
header = ET.SubElement(rqoutboundmessage, 'Header')
version = ET.SubElement(header, 'Version')
companyid = ET.SubElement(header,'CompanyID')
messageid = ET.SubElement(header,'MessageID')
messagetype = ET.SubElement(header,'MessageType')
testmessage = ET.SubElement(header,'TestMessage')
rqdefinition = ET.SubElement(rqoutboundmessage,'RqCustomerDefinition')
nodes = ET.SubElement(rqdefinition,'Customers')
updated = ET.SubElement(nodes,'Updated')
node = ET.SubElement(updated,'Customer')
externalcode = ET.SubElement(node,'ExternalCode')
if str(p_addressexternalcode or '') != '':
if p_addressexternalcode[:10] == 'AholdStore':
name = ET.SubElement(node,'Name')
name.text = p_addressexternalcode[-4:]
address = ET.SubElement(node,'Address')
if str(p_addressexternalcode or '') != '':
addrexternalcode = ET.SubElement(address,'ExternalCode')
addrexternalcode.text = re.sub('[^ \-\.0-9#A-Z_a-z]+', '', p_addressexternalcode)
street = ET.SubElement(address,'Street')
nr = ET.SubElement(address,'Nr')
if str(p_addition or '') != '':
nraddition = ET.SubElement(address,'NrAddition')
nraddition.text = p_addition
zipcode = ET.SubElement(address,'ZipCode')
city = ET.SubElement(address,'City')
country = ET.SubElement(address,'Country')
countrycode = ET.SubElement(country,'ExternalCode')
if str(p_complexnr or '') != '':
complexname = ET.SubElement(address,'ComplexName')
complexname.text = p_complexnr
region = ET.SubElement(node,'Region')
regexternalcode = ET.SubElement(region,'ExternalCode')
companycode = ET.SubElement(node,'CompanyID')
#vulling van de SOAP-xml
companyid.text = lic
version.text = '1.0'
messageid.text = '{00009000-0000-0000-0000-000000000000}'
messagetype.text = 'RqCustomerDefinition'
testmessage.text = str(controle)
externalcode.text = re.sub('[^.0-9#A-Z_a-z]+', '', p_externalcode)
street.text = p_street
nr.text = str(p_nr)
zipcode.text = p_zipcode
city.text = p_city
countrycode.text = p_country
regexternalcode.text= p_region
companycode.text = p_company_code
# maak er een tekstfile van.
body = ET.tostring(envelope, pretty_print=True)
response = requests.post(url,data=body,headers=headers, auth=(gebruiker, wachtwoord))
root = ET.fromstring(response.text.encode('ascii','ignore'))
if response.status_code == 200:
status = 0
else:
status = 1
Verwerking.objects.create(omgeving=omgnaam, Status=status, bericht=body, antwoord=ET.tostring(root, pretty_print=True).decode())
return status
Terminal Response:
[21/Mar/2021 16:25:49] "GET /woningbeheer HTTP/1.1" 200 58463
[21/Mar/2021 16:25:50] "GET /static/js/main.js HTTP/1.1" 304 0
[21/Mar/2021 16:25:50] "GET /woningbeheer HTTP/1.1" 200 58468
Internal Server Error: /woningbeheer/syncPCAind/5897
Traceback (most recent call last):
File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python38\lib\site-packages\django\utils\deprecation.py", line 116, in __call__
response = self.process_response(request, response)
File "C:\Python38\lib\site-packages\django\middleware\common.py", line 106, in process_response
if response.status_code == 404:
AttributeError: 'dict' object has no attribute 'status_code'
[21/Mar/2021 16:25:53] "GET /woningbeheer/syncPCAind/5897 HTTP/1.1" 500 65689
Internal Server Error: /woningbeheer/syncPCAind/9640
Traceback (most recent call last):
File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python38\lib\site-packages\django\utils\deprecation.py", line 116, in __call__
response = self.process_response(request, response)
File "C:\Python38\lib\site-packages\django\middleware\common.py", line 106, in process_response
if response.status_code == 404:
AttributeError: 'dict' object has no attribute 'status_code'
[21/Mar/2021 16:39:41] "GET /woningbeheer/syncPCAind/9640 HTTP/1.1" 500 65689
Maybe useful:
AttributeError at /woningbeheer/syncPCAind/82689
'dict' object has no attribute 'status_code'
Request Method: GET
Request URL: http://127.0.0.1:8000/woningbeheer/syncPCAind/82689
Django Version: 3.1.7
Exception Type: AttributeError
Exception Value:
'dict' object has no attribute 'status_code'
Exception Location: C:\Python38\lib\site-packages\django\middleware\common.py, line 106, in process_response
Python Executable: C:\Python38\python.exe
Python Version: 3.8.8
Python Path:
['C:\\Users\\wgeboers\\OneDrive - Coen Hagedoorn Bouwgroep '
'B.V\\Django-Docker\\databeheer',
'C:\\Python38\\python38.zip',
'C:\\Python38\\DLLs',
'C:\\Python38\\lib',
'C:\\Python38',
'C:\\Python38\\lib\\site-packages']
Server time: Sun, 21 Mar 2021 15:44:25 +0000
Thanks in advance and if there is more information needed let me know.

google cloud: downloading as an CSV

I have a download button that should return a users CSV. The code for it below:
class StartCSVHandler(ThreeScaleResourceHandler):
""" Starts generating a user's CSV file """
allowed_methods = ('new',)
requires_input = False
def post(self, *args, **kwargs):
user = self.current_user()
if not user:
self.abort(401, detail=ERROR_NOT_AUTHORIZED)
task_url = '/jobs/users/%s/data/csv' % user.key()
taskqueue.add(url=task_url, queue_name='users')
return {}
def generate_data_from_query(query, user, format, handler, filename, mission=None):
batch_size = 500
cursor = None
spottings = []
count = 0
mime_type = 'text/csv' if format == CSV_FORMAT else 'text/xml'
timestamp = '%0.6f' % time.time()
gcs_filename_template = '/{bucket}/{user}/{timestamp}/{filename}'
from global_config import config
gcs_filename = gcs_filename_template.format(
bucket='project-noah-backups',
# bucket=config['cloudstorage']['export_files_bucket'],
user=str(user.key()),
timestamp=timestamp,
filename=filename
)
logging.debug(str(user.key()))
f = cloudstorage.open(gcs_filename, mode='w', content_type=mime_type)
# blobstore_file_name = files.blobstore.create(mime_type=mime_type, _blobinfo_uploaded_filename=filename.encode('utf-8'))
while True:
if format == CSV_FORMAT:
writer = utils.UnicodeWriter(f)
if count == 0:
writer.writerow(csv_display_names)
elif format == KML_FORMAT and count == 0:
f.write(template.render('spotting_export_pre.kml', {}))
if cursor:
query.with_cursor(cursor)
spottings = query.fetch(batch_size)
if format == CSV_FORMAT:
dicts = [s.as_dict() for s in spottings]
logging.debug(dicts)
for spotting_dict in dicts:
writer.writerow([spotting_dict[k] for k in csv_keys])
elif format == KML_FORMAT:
output = template.render('spotting_export_mid.kml', {'spottings' : spottings, 'server_url' : utils.server_url(handler.request)})
f.write(output.encode('utf-8'))
cursor = query.cursor()
logging.info('written spottings %d to %d' % (count, count + len(spottings)))
count += len(spottings)
if not mission:
push_to_beacon_user(user, {'format':format,'progress':count})
else:
push_to_beacon_user_mission(user, mission, {'format':format,'progress':count})
if len(spottings) < batch_size:
break
if format == KML_FORMAT:
f.write(template.render('spotting_export_post.kml', {}))
blob_key = BlobKey(blobstore.create_gs_key(u'/gs' + gcs_filename))
logging.debug(blob_key)
return blob_key
def generate_data_from_user_spottings(user, format, handler):
filename = u'My-Spottings.%s' % format
# query = user.mySpottings
query = user.mySpottings
logging.debug(query)
return generate_data_from_query(query, user, format, handler, filename)
class GenerateUserDataHandler(NoahHandler):
def post(self, user_key=None, format=None):
if not user_key:
return
user = NoahUser.get(user_key)
if not user:
return
if format not in (CSV_FORMAT, KML_FORMAT):
return
blob_key = generate_data_from_user_spottings(user, format, self)
user = NoahUser.get(user_key)
if format == CSV_FORMAT:
if user.csv:
user.csv.delete()
user.csv = blob_key
user.put()
elif format == KML_FORMAT:
if user.kml:
user.kml.delete()
user.kml = blob_key
user.put()
logging.debug(user.recent_spottings)
logging.debug(str(blob_key))
push_to_beacon_user(user, {'format': format,'url':'/data?key=%s' % str(blob_key)})
class ThreeScaleResourceHandler(ResourceHandler):
#three_scale_authenticate
def get(self, *args, **kwargs):
super(ThreeScaleResourceHandler, self).get(*args, **kwargs)
#three_scale_authenticate
def post(self, *args, **kwargs):
super(ThreeScaleResourceHandler, self).post(*args, **kwargs)
#three_scale_authenticate
def put(self, *args, **kwargs):
super(ThreeScaleResourceHandler, self).put(*args, **kwargs)
#three_scale_authenticate
def delete(self, *args, **kwargs):
super(ThreeScaleResourceHandler, self).delete(*args, **kwargs)
This should download users data in the form of an CSV. The problem i am getting is two fold; firstly, the end point that this generates is '/api/v1/users/me/data/csv' and when visiting it, i receive the following error
{"error": {"title": "Unauthorized", "status": 401, "message": "You are not authorized to perform that action. Please use the api_key parameter with your registered key."}}
Secondly, the link it provides for the user to save cannot be found:
http://localhost:8080/data?key=encoded_gs_file:cHJvamVjdC1ub2FoLWJhY2t1cHMvYWdoa1pYWi1UbTl1WlhJVkN4SUlUbTloYUZWelpYSVlnSUNBZ0lDQWdBb00vMTU4MTAxODk3My4wODgyODEvTXktU3BvdHRpbmdzLmNzdg==
I am not entirely sure what i need to correct.
firstly, the end point that this generates is '/api/v1/users/me/data/csv' and when visiting it, i receive the following error: {"error": {"title": "Unauthorized", "status": 401, "message": "You are not authorized to perform that action. Please use the api_key parameter with your registered key."}}
Which handler in your code snippet handles /api/v1/users/me/data/csv? Is it StartCSVHandler? Are you sure it isn't being thrown because of this line? self.abort(401, detail=ERROR_NOT_AUTHORIZED)
Secondly, the link it provides for the user to save cannot be found: http://localhost:8080/data?key=encoded_gs_file:cHJvamVjdC1ub2FoLWJhY2t1cHMvYWdoa1pYWi1UbTl1WlhJVkN4SUlUbTloYUZWelpYSVlnSUNBZ0lDQWdBb00vMTU4MTAxODk3My4wODgyODEvTXktU3BvdHRpbmdzLmNzdg==
In what way? like you are trying to find the file on your machine or this link is throwing a 404?
On your localhost, encoded_gs_file files can be found here: http://localhost:8000/blobstore
If it's a 404, then what does your handler for /data do? It doesnt look like it's in your code snippet

Django - AttributeError: 'tuple' object has no attribute 'get' [ DRF, Stripe, Python ]

I constantly get an error whenever I make a POST request to /api/tickets/:
Internal Server Error: /payment-stripe/
Traceback (most recent call last):
File "/ENV/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/ENV/lib/python3.8/site-packages/django/utils/deprecation.py", line 96, in __call__
response = self.process_response(request, response)
File "/ENV/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'tuple' object has no attribute 'get'
[03/Jan/2020 03:17:09] "POST /payment-stripe/ HTTP/1.1" 500 58576
Here is my stripe payment handling view that I think is causing the problem, but I can't find out why:
#require_http_methods(["POST"])
#csrf_exempt
def stripe_payment_handling(request):
"""
The following code is copied from Stripe Docs.
Everything inside the IF statements is how the ticket gets handled.
"""
payload = request.body
# Checks for the signature of stripe.
sig_header = request.headers['Stripe-Signature']
event = None
try:
# Tests if it can create a connection with Stripe.
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
# invalid payload: If it doesn't pass it gives back a 400
return "Invalid payload", 400
except stripe.error.SignatureVerificationError as e:
# invalid signature: If the Stripe Signature is not there it wont accept it.
return "Invalid signature", 400
# Create the a dictionary with the data
event_dict = event.to_dict()
print(event_dict)
if event_dict['type'] == "payment_intent.created":
# If someone redirects to the bank to pay it will create a payment intent
# Now it will use that value to validate the payment
intent = event_dict['data']['object']
ticket = Ticket.objects.get(
stripe_payment_intent=intent["id"]
)
ticket.status = "Created"
ticket.save()
elif event_dict['type'] == "payment_intent.succeeded":
# If the payment Succeeded:
intent = event_dict['data']['object']
# get the ticket with the intent id that was created from payment_intent.created
ticket = Ticket.objects.get(stripe_payment_intent=intent["id"])
# Change status to Completed
ticket.status = "Completed"
ticket.save()
# Reduce the amount of stock for the selected parking location
ticket.stock_type.quantity -= 1
ticket.stock_type.save()
# Send the email to the client
# The .send_ticket_email() function is part of the Ticket Model
ticket.send_ticket_email()
elif event_dict['type'] == "payment_intent.payment_failed":
# If the payment has failed:
intent = event_dict['data']['object']
# Get the error message
error_message = intent['last_payment_error']['message']
print("Failed: ", intent['id'], error_message)
# Notify the customer that payment failed
try:
# Find the ticket based on the intent id
ticket = Ticket.objects.get(stripe_payment_intent=intent["id"])
# Change its status to Failed
ticket.status = "Failed"
ticket.save()
# Send Failed email
# the .send_failed_email() function is part of the Ticket model
ticket.send_failed_email()
except Exception as e:
# if the payment intent wasn't found send an email to contact support:
print("Payment intent not found! => {0}".format(e))
elif event_dict['type'] == "payment_intent.canceled":
print("PAYMENT INTENT CANCELED")
elif event_dict['type'] == "payment_intent.amount_capturable_updated":
print("PAYMENT INTENT UPDATED")
else:
print("INTENT = {NONE}")
return HttpResponse(status=200)
(extra) Here is my api/views.py:
class TicketInitialize(generics.GenericAPIView):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
permission_classes = (permissions.AllowAny,)
def post(self, request, *args, **kwargs):
ticket_price = int(float(request.data["price"])) * 100
print(ticket_price)
stripe.api_key = 'my_stripe_api_key'
intent = stripe.PaymentIntent.create(
amount=ticket_price,
currency='eur',
payment_method_types=['card', 'ideal']
)
request.data["stripe_payment_intent"] = intent["id"]
stock = Stock.objects.get(id=request.data["stock_type"])
event = Event.objects.get(id=request.data["event"])
new_ticket = Ticket.objects.create(
first_name=request.data["first_name"],
last_name=request.data["last_name"],
quantity=request.data["quantity"],
cell_phone=request.data["cell_phone"],
email=request.data["email"],
price=request.data["price"],
service_fee=request.data["service_fee"],
stock_type=stock,
event=event,
stripe_payment_intent=request.data["stripe_payment_intent"]
)
return Response(intent)
my urls.py:
urlpatterns = [
path('payment-stripe/', views.stripe_payment_handling, name="stripe-endpoint"),
]
I don't understand why it keeps giving me the Attribute Error. It won't allow me to handle any webhooks from stripe or complete orders.
Thank you for taking a look, and I'm looking forward to your suggestions and answers!
Change return "Invalid signature", 400 to
return HttpResponse(status=400, content="Invalid signature")
and return "Invalid payload", 400 to
return HttpResponse(status=400, content="Invalid payload")

Django celery task_id is null

I'm trying to implement a progress bar in Django, I'm taking references from this code snippet I found http://djangosnippets.org/snippets/2898/ but my efforts are in vane because I don't know what happening but the task_idfor celery is always null when executes the method task, that's my code:
def add_categoria(request):
if request.POST:
form_cat = CategoriaModelForm(request.POST,request.FILES)
if form_cat.is_valid():
file = request.FILES['imagen']
job = upload_image_categoria(request).delay()
request.session['task_id'] = job.id
return HttpResponse(json.dumps({'task_id':job.id}))
else:
return HttpResponseBadRequest(json.dumps(form_cat.errors),
mimetype="application/json")
else:
form = CategoriaModelForm()
return render_to_response("ventas/form.html",{'form':form},context_instance=RequestContext(request))
#task()
def upload_image_categoria(request):
form = CategoriaModelForm(request.POST, request.FILES)
path = MEDIA_ROOT+'/categorias/%s' % form.cleaned_data['imagen'].name
file = request.FILES['imagen']
destination = open(path, 'wb+')
porcentaje = 0
acum = 0
for chunk in file.chunks():
time.sleep(0.1)
current_task.update_state(state='PROGRESS', meta={'current': porcentaje})
acum += len(chunk)
porcentaje = int((acum*100)/file.size)
destination.write(chunk)
#csrf_exempt
def upload_state(request):
""" A view to report the progress to the user """
data = 'Fail'
if request.is_ajax():
if 'task_id' in request.POST.keys() and request.POST['task_id']:
task_id = request.POST['task_id']
task = AsyncResult(task_id)
data = task.result or task.state
else:
data = 'No task id'
else:
data = 'This is not an ajax request'
json_data = json.dumps(data)
return HttpResponse(json_data, mimetype='application/json')
So, when I report the state of progress bar in upload_image_categoria at current_task.update_state(state='PROGRESS', meta={'current': porcentaje}) always I get this Traceback:
Traceback:
File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/Users/Tone/Documents/Proyectos/dgp/ventas/forms.py" in add_categoria
446. job = upload_image_categoria(request).delay()
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/app/task.py" in __call__
330. return self.run(*args, **kwargs)
File "/Users/Tone/Documents/Proyectos/dgp/ventas/forms.py" in upload_image_categoria
462. current_task.update_state(state='PROGRESS',meta={'current': i, 'total': 100})
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/app/task.py" in update_state
695. self.backend.store_result(task_id, meta, state)
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/backends/base.py" in store_result
282. self._store_result(task_id, result, status, traceback, **kwargs)
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/backends/amqp.py" in _store_result
128. routing_key=task_id.replace('-', ''),
Exception Type: AttributeError at /ventas/categorias/add/
Exception Value: 'NoneType' object has no attribute 'replace'
That's my settings.py for celery options:
BROKER_URL = "amqp://guest#localhost:5672//"
CELERY_IMPORTS = ("ventas.forms",)
CELERY_TRACK_STARTED = True
CELERY_RESULT_BACKEND = "amqp"
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
CELERY_RESULT_DBURI = "mysql://root#localhost/dgp"
So I don't know what's happening, worker is correctly, settings (I guess, is correctly) and always I get the same, I prove in some other projects with the same settings (this project particularly http://iambusychangingtheworld.blogspot.com.es/2013/07/django-celery-display-progress-bar-of.html) and it works perfectly so I don't know why here not, something I'm missing? Any ideas would be appreciate.
Regards!

App Engine: TypeError in handlers.py

I get a problem in a form handler in app engine (Python). Basically when I post the form to the handler I get the following traceback:
INFO 2011-02-07 14:06:59,364 dev_appserver.py:3317] "GET /favicon.ico HTTP/1.1" 404 -
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wsgiref/handlers.py", line 92, in run
self.result = application(self.environ, self.start_response)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 531, in __call__
handler.handle_exception(e, self.__debug)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 394, in handle_exception
self.error(500)
TypeError: 'bool' object is not callable
INFO 2011-02-07 14:07:01,986 dev_appserver.py:3317] "POST /newevent HTTP/1.1" 500 -`
On the browser I get the message 'A server error occurred. Please contact the administrator'. As you can see, the error happens before the POST command, and doesn't seem to stem from any of my handler code. Here's the handler class for that form (post_secure is a method called by the post method in the parent class):
class SaveEvent(BaseHandler):
def post_secure(self):
userinfo = db.GqlQuery("SELECT * FROM User WHERE fbid = :1", self.user['uid'])[0]
newevent = Event(parent=userinfo)
self.error = False
self.template_values = {}
if (self.request.get('eventname') == ""):
self.template_values['eventnameerror'] = True
self.error = True
else:
newevent.eventname = self.request.get('eventname')
if (self.request.get('venuename') == ""):
self.template_values['venuenameerror'] = True
self.error = True
else:
newevent.venuename = self.request.get('venuename')
if (re.match("[0-9]+\.[0-9][0-9]", self.request.get('eventprice')) == None):
self.template_values['eventpriceerror'] = True
self.error = True
else:
newevent.price_pence = int(float(self.request.get('eventprice')) * 100)
if (re.match("[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]", self.request.get('eventdate')) == None):
self.template_values['eventdateerror'] = True
self.error = True
else:
day = re.split("/", self.request.get('eventdate'))[0]
month = re.split("/", self.request.get('eventdate'))[1]
year = re.split("/", self.request.get('eventdate'))[2]
if (re.match("[0-2][0-9]:[0-5][0-9]", self.request.get('eventtime')) == None):
self.template_values['eventtimeerror'] = True
self.error = True
else:
hours = re.split(":", self.request.get('eventtime'))[0]
minutes = re.split(":", self.request.get('eventtime'))[1]
try:
newevent.date = datetime.datetime(year, month, day, hours, minutes, 0, 0)
except ValueError:
self.template_values['eventdatetimeerror'] = True
self.error = True
if (newevent.date < datetime.datetime.now()):
self.template_values['eventdateerror2'] = True
self.error = True
if (self.request.get('eventlink') == ""):
self.template_values['eventlinkerror'] = True
self.error = True
if (self.error == True):
self.template_values['eventname'] = self.request.get('eventname')
self.template_values['venuename'] = self.request.get('venuename')
self.template_values['eventprice'] = self.request.get('eventprice')
self.template_values['eventdate'] = self.request.get('eventdate')
self.template_values['eventtime'] = self.request.get('eventtime')
self.template_values['eventlink'] = self.request.get('eventlink')
self.tpl('addevent.html', self.template_values)
newevent.put()
self.template_values = {
'newevent' : newevent
}
self.tpl('eventadded.html', self.template_values)
The RequestHandler class has a method named error
error(code)
A shortcut method for handlers to use to return an error response. Clears the response output stream and sets the HTTP error code to code. Equivalent to calling self.response.clear() and self.response.set_status(code).
Your POST handler above overwrites that method with a boolean value, and then when the framework attempts to call self.error(500) it throws an exception because the value of self.error is no longer a callable.
Use a different member variable name than error to prevent this.

Categories