Proper way to format date for Fedex API XML - python

I have a Django application where I am trying to make a call to Fedex's API to send out a shipping label for people wanting to send in a product for cash. When I try to make the call though it says there is a data validation issue with the Expiration field in the XML I am filling out. I swear this has worked in the past with me formatting the date as "YYYY-MM-DD", but now it is not. I read that with Fedex, you need to format the date as ISO, but that is also not passing the data validation. I am using a python package created to help with tapping Fedex's API.
Django view function for sending API Call
def Fedex(request, quote):
label_link = ''
expiration_date = datetime.datetime.now() + datetime.timedelta(days=10)
# formatted_date = "%s-%s-%s" % (expiration_date.year, expiration_date.month, expiration_date.day)
formatted_date = expiration_date.replace(microsecond=0).isoformat()
if quote.device_type != 'laptop':
box_length = 9
box_width = 12
box_height = 3
else:
box_length = 12
box_width = 14
box_height = 3
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
## Page 411 of FedEx Dev Guide - 20.14 Email Labels
CONFIG_OBJ = FedexConfig(key=settings.FEDEX_KEY, password=settings.FEDEX_PASSWORD, account_number=settings.FEDEX_ACCOUNT,
meter_number=settings.FEDEX_METER, use_test_server=settings.USE_FEDEX_TEST)
fxreq = FedexCreatePendingShipRequestEmail(CONFIG_OBJ, customer_transaction_id='xxxxxx id:01')
fxreq.RequestedShipment.ServiceType = 'FEDEX_GROUND'
fxreq.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
fxreq.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
fxreq.RequestedShipment.ShipTimestamp = datetime.datetime.now()
# Special fields for the email label
fxreq.RequestedShipment.SpecialServicesRequested.SpecialServiceTypes = ('RETURN_SHIPMENT', 'PENDING_SHIPMENT')
fxreq.RequestedShipment.SpecialServicesRequested.PendingShipmentDetail.Type = 'EMAIL'
fxreq.RequestedShipment.SpecialServicesRequested.PendingShipmentDetail.ExpirationDate = formatted_date
email_address = fxreq.create_wsdl_object_of_type('EMailRecipient')
email_address.EmailAddress = quote.email
email_address.Role = 'SHIPMENT_COMPLETOR'
# RETURN SHIPMENT DETAIL
fxreq.RequestedShipment.SpecialServicesRequested.ReturnShipmentDetail.ReturnType = ('PENDING')
fxreq.RequestedShipment.SpecialServicesRequested.ReturnShipmentDetail.ReturnEMailDetail = fxreq.create_wsdl_object_of_type(
'ReturnEMailDetail')
fxreq.RequestedShipment.SpecialServicesRequested.ReturnShipmentDetail.ReturnEMailDetail.MerchantPhoneNumber = 'x-xxx-xxx-xxxx'
fxreq.RequestedShipment.SpecialServicesRequested.PendingShipmentDetail.EmailLabelDetail.Recipients = [email_address]
fxreq.RequestedShipment.SpecialServicesRequested.PendingShipmentDetail.EmailLabelDetail.Message = "Xxxxxx Xxxxxx"
fxreq.RequestedShipment.LabelSpecification = {'LabelFormatType': 'COMMON2D', 'ImageType': 'PDF'}
fxreq.RequestedShipment.Shipper.Contact.PersonName = quote.first_name + ' ' + quote.last_name
fxreq.RequestedShipment.Shipper.Contact.CompanyName = ""
fxreq.RequestedShipment.Shipper.Contact.PhoneNumber = quote.phone
fxreq.RequestedShipment.Shipper.Address.StreetLines.append(quote.address)
fxreq.RequestedShipment.Shipper.Address.City = quote.city
fxreq.RequestedShipment.Shipper.Address.StateOrProvinceCode = quote.state
fxreq.RequestedShipment.Shipper.Address.PostalCode = quote.zip
fxreq.RequestedShipment.Shipper.Address.CountryCode = settings.FEDEX_COUNTRY_CODE
fxreq.RequestedShipment.Recipient.Contact.PhoneNumber = settings.FEDEX_PHONE_NUMBER
fxreq.RequestedShipment.Recipient.Address.StreetLines = settings.FEDEX_STREET_LINES
fxreq.RequestedShipment.Recipient.Address.City = settings.FEDEX_CITY
fxreq.RequestedShipment.Recipient.Address.StateOrProvinceCode = settings.FEDEX_STATE_OR_PROVINCE_CODE
fxreq.RequestedShipment.Recipient.Address.PostalCode = settings.FEDEX_POSTAL_CODE
fxreq.RequestedShipment.Recipient.Address.CountryCode = settings.FEDEX_COUNTRY_CODE
fxreq.RequestedShipment.Recipient.AccountNumber = settings.FEDEX_ACCOUNT
fxreq.RequestedShipment.Recipient.Contact.PersonName = ''
fxreq.RequestedShipment.Recipient.Contact.CompanyName = 'Xxxxxx Xxxxxx'
fxreq.RequestedShipment.Recipient.Contact.EMailAddress = 'xxxxxx#xxxxxxxxx'
# Details of Person Who is Paying for the Shipping
fxreq.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.AccountNumber = settings.FEDEX_ACCOUNT
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Contact.PersonName = 'Xxxxx Xxxxx'
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Contact.CompanyName = 'Xxxxx Xxxxxx'
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Contact.PhoneNumber = 'x-xxx-xxx-xxxx'
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Contact.EMailAddress = 'xxxxxxx#xxxxxxxxx'
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Address.StreetLines = 'Xxxxx N. xXxxxxx'
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Address.City = 'Xxxxxxx'
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Address.StateOrProvinceCode = 'XX'
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Address.PostalCode = 'xxxxx'
fxreq.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.Address.CountryCode = 'US'
# Package Info
package1 = fxreq.create_wsdl_object_of_type('RequestedPackageLineItem')
package1.SequenceNumber = '1'
package1.Weight.Value = 1
package1.Weight.Units = "LB"
package1.Dimensions.Length = box_length
package1.Dimensions.Width = box_width
package1.Dimensions.Height = box_height
package1.Dimensions.Units = "IN"
package1.ItemDescription = 'Phone'
fxreq.RequestedShipment.RequestedPackageLineItems.append(package1)
fxreq.RequestedShipment.PackageCount = '1'
try:
fxreq.send_request()
label_link = str(fxreq.response.CompletedShipmentDetail.AccessDetail.AccessorDetails[0].EmailLabelUrl)
except Exception as exc:
print('Fedex Error')
print('===========')
print(exc)
print('==========')
return label_link
Error Log
Error:cvc-datatype-valid.1.2.1: \\'2017-11-3\\' is not a valid value for \\'date\\'.\\ncvc-type.3.1.3: The value \\'2017-11-3\\' of element \\'ns0:ExpirationDate\\' is not valid."\\n }\\n }' (Error code: -1)

Related

In Odoo 10,how can I specify a data in create_date,create_uid,instead of value in system,when I use method named 'create' to create a record

I create new record with the method named create() in local database with data pulled away from remote database.As we all know,there are four normal fields in Odoo such as create_date,write_date,create_uid,write_uid.I want these data to be in a remote databaseļ¼Œbut when I use method named create() to create the record,these data are the data at the time of local creation and not the remote data.
For example,in remote database,the creat_date is '2019-10-11',I can't change the value that is finally written to the local database even if I pass the value of the remote database into the dictionary.Finally,the value of field named create_date is '2019-12-03' rather than '2019-10-11'.The '2019-12-03' is the date now.The situation is similar for other fields such as write_date,create_uid,write_uid.
Please help me,thanks to everyone who thought about this question.
Following is my code.
The Class Model
class ReportRentalIncomeFromProperty(models.Model):
_name = 'report.rental.income.from.property'
_description = 'The report about the income from property rental'
_order = 'product_id, start_date'
# create_date = fields.Datetime('Created on')
create_uid = fields.Char('Created by')
# write_date = fields.Datetime('Last Modified on')
write_uid = fields.Char('Last Contributor')
product_id = fields.Many2one('product.product', 'Property House')
area_id = fields.Many2one('res.country.area', 'City')
district_id = fields.Many2one('res.country.district', 'District')
town_id = fields.Many2one('res.country.town', 'Town')
road_name = fields.Char('Road')
start_date = fields.Date('Start Date')
end_date = fields.Date('End Date')
should_pay = fields.Float('Should Pay')
real_pay = fields.Float('Real Pay')
balance_pay = fields.Float('Balance Pay')
rental_compliance_rate = fields.Float('Rental Compliance Rate(%)', group_operator="avg")
company_id = fields.Many2one('res.company', string='Company')
parent_company_id = fields.Many2one('res.company', related='company_id.parent_id', store=True,
string='Parent Company')
actual_business = fields.Many2many(
'rh.commercial.activities',
'house_rental_rent_income_business_db',
'actual_business_id',
'commercial_activities_id',
string='Actual business')
The function to pull away remote data to create new record in local database.
#api.multi
def synchronization_contract_performance_rate(self):
self.env['report.rental.income.from.property'].search([]).unlink()
product_dict = {}
A_product = self.env['product.product'].search([])
for a in A_product:
product_dict[a.name] = a.id
activities_dict = {}
D_activities = self.env['rh.commercial.activities'].search([])
for d in D_activities:
activities_dict[d.name] = d.id
address_dict = {}
i = 0
address_model_list = ['res.country.area', 'res.country.district', 'res.country.town']
address_field_list = ['area_id', 'district_id', 'town_id']
for addr in address_model_list:
C_address = self.env[addr].search([])
addr_dict = {}
for c in C_address:
addr_dict[c.name] = c.id
address_dict[i] = addr_dict
i += 1
record_list_1 = self.company_recursive_func()
for list_1 in record_list_1:
database = list_1[0]
link_url = list_1[1]
if link_url.startswith('http://'):
_uri = link_url.replace('http://', '')
my_odoo = odoorpc.ODOO(_uri, port=48080)
if link_url.startswith('https://'):
_uri = link_url.replace('https://', '')
my_odoo = odoorpc.ODOO(_uri, port=443, protocol='jsonrpc+ssl')
username = list_1[2]
password = list_1[3]
my_odoo.login(database, username, password)
company_id = list_1[4]
company_code = list_1[5]
product_actual_business_dict = {}
A_product_actual_business_ids = my_odoo.env['product.product'].search([])
A_product_actual_business = my_odoo.execute('product.product', 'read', A_product_actual_business_ids,
['actual_business'])
for a in A_product_actual_business:
name_list = []
for b in my_odoo.execute('rh.commercial.activities', 'read', a.get('actual_business'), ['name']):
name_list.append(b.get('name'))
product_actual_business_dict[a.get('id')] = name_list
remote_ids = my_odoo.env['report.rental.income.from.property'].search([])
remote_data_dict = my_odoo.execute('report.rental.income.from.property', 'read', remote_ids, ['product_id',
'start_date',
'create_date',
'create_uid',
'write_date',
'write_uid',
'end_date',
'should_pay',
'balance_pay',
'real_pay',
'rental_compliance_rate',
'area_id',
'road_name',
'district_id',
'town_id'])
for data in remote_data_dict:
remote_product_name = data.get('product_id')[1]
product_id = product_dict.get(remote_product_name + '(' + company_code + ')',
None)
if product_id:
i = 0
address_id_list = []
for address_field in address_field_list:
if data.get(address_field):
remote_address_name = data.get(address_field)[1]
local_address_id = address_dict[i].get(remote_address_name, None)
address_id_list.append(local_address_id)
else:
address_id_list.append(None)
i += 1
ids_list = []
find_names = product_actual_business_dict.get(data.get('product_id')[0])
for find_name in find_names:
id = activities_dict.get(find_name, None)
if id:
ids_list.append(id)
value = {
'product_id': product_id,
'area_id': address_id_list[0],
'district_id': address_id_list[1],
'town_id': address_id_list[2],
'road_name': data['road_name'],
'start_date': data['start_date'],
'end_date': data['end_date'],
'should_pay': data['should_pay'],
'real_pay': data['real_pay'],
'create_date': data['create_date'],
'create_uid': data['create_uid'][1],
'write_date': data['write_date'],
'write_uid': data['write_uid'][1],
'balance_pay':data['balance_pay'],
'rental_compliance_rate': data['rental_compliance_rate'],
'company_id': company_id,
'actual_business': [(6, 0, ids_list)]
}
self.env['report.rental.income.from.property'].create(value)
my_odoo.logout()
You can change standart odoo fields after you create your record with sql query
property_id = self.env['report.rental.income.from.property'].create(value)
self.env.cr.execute("UPDATE report_rental_income_from_property SET create_date='%s', create_uid=%s, write_date='%s', write_uid=%s WHERE id=%s" %
(value['create_date'], value['create_uid'], value['write_date'], value['write_uid'], property_id))

[Odoo][v10] IndexError in cron in formview everything is ok

I have two that same methods, one working in form view for record and second is for cron.
When i run action in Form view everything is OK, i can get value :
self.deadline = deadlines[0][0]
but when i run in cron:
emp.debug = deadlines[0][0]
i have IndexError: list index out of range
but emp.debug = deadlines works
Full code:
class UserProfile(models.Model):
_name = 'users.profile'
user_id = fields.Many2one(related='project_id.user_id', string='User')
partner_id = fields.Many2one('res.partner', 'Partner')
follower_id = fields.Many2one('mail.followers', 'Follower')
project_id = fields.Many2one('project.project', 'Project')
# project_start_date # TODO max date from deadlines
project_active = fields.Boolean(related='project_id.active', string='Project active')
project_percent = fields.Float(related='project_id.x_project_percent', string='Project percent')
project_money = fields.Float(related='project_id.x_project_money_share')
# project_money_paid = fields.Char(related='project_id.x_paid_debug')
project_sale = fields.Many2one(related='project_id.x_sales_id', string='Sales')
deadline = fields.Many2one('project.project.deadlines', 'Deadline')
deadline_date = fields.Datetime(related='deadline.end_date')
debug = fields.Text()
def get_closest_date(self): # In form view
find_deadlines = self.env["project.project.deadlines"].search([('project_id', '=', self.project_id.id)])
deadlines = []
for record in find_deadlines:
datetime_without_tz = datetime.datetime.strptime(record.end_date, "%Y-%m-%d %H:%M:%S")
record_id = record.id
delta = datetime_without_tz - datetime.datetime.now()
delta_in_seconds = int(delta.total_seconds())
if delta_in_seconds > 0:
deadlines.append((record_id, delta_in_seconds))
deadlines.sort(key=itemgetter(1))
self.deadline = deadlines[0][0] # No indexError i can get value
self.debug = self.env["users.profile"].search([])[0].project_id.id
#api.model
def get_closest_date2(self): # For cron
emp_details_all = self.env["users.profile"].search([])
for emp in emp_details_all:
find_deadlines = self.env["project.project.deadlines"].search([('project_id', '=', emp.project_id.id)])
deadlines = []
for record in find_deadlines:
datetime_without_tz = datetime.datetime.strptime(record.end_date, "%Y-%m-%d %H:%M:%S")
record_id = record.id
delta = datetime_without_tz - datetime.datetime.now()
delta_in_seconds = int(delta.total_seconds())
if delta_in_seconds > 0:
deadlines.append((record_id, delta_in_seconds))
deadlines.sort(key=itemgetter(1))
emp.debug = deadlines[0][0] # IndexError
In the cron method you are looping over all users profiles so it seems like the error message IndexError is shown for a different record.
Check the deadlines variable in get_closest_date2 method before trying to get some value.

How to stop mails to be sent if the attachment data is empty in python?

I am writing a mail function in Python using csvwriter and StringIo, my motive is to send the mails with attachment only if the attachment is containing some data.
But, the function is also sending mails in case of empty file.
Please help me where i am making mistake.
def cbazaar_quantity_sync(self,products_data_quantity_sync,threep_numbers):
channel = Channel.objects.get(name='CBazaar')
channel_configurations = channel.channelconfiguration_set.all()
listed_threep_numbers = self.filter_products_listed_on_channel(channel,threep_numbers)
products_to_sync = self.filter_products_data(products_data_quantity_sync,listed_threep_numbers)
# pdb.set_trace()
data = products_to_sync
current_time = datetime.now()
task_start_time = "%s-%s-%s_%s:%s:%s"%(current_time.day, current_time.month, current_time.year, current_time.hour, current_time.minute, current_time.second)
csvresult = StringIO.StringIO()
csvresultwriter = csv.writer(csvresult)
csvresultwriter.writerow(["Pri.Vendor Name","Product Code","Product Size","Design No","Stock Qty","Shipping Lead Time","Replicable (Yes / No)","Is stock Qty exclusively allocated to CBazaar ( Yes / No)"])
if len(products_to_sync) != 0:
for product in data:
# pdb.set_trace()
Store_Name = str('voylla retail pvt ltd')
sku = str(product[2])
size = str(product[3])
threep_number = str(product[1])
qty = int(product[7])
leadtime = int(product[8])
mod = str(product[11])
none = str('None')
if mod == none:
leadtime = 2
replicable = str('Yes')
product_obj = Product.objects.get(threep_number=threep_number)
channel_sku = self.threep_sku_mapping_method(channel,product_obj)
# pdb.set_trace()
if channel_sku != 0:
sku=str(channel_sku)
if qty == 0:
continue
else:
csvresultwriter.writerow(['%s'%Store_Name,'%s'%sku,'%s'%size,'%s'%threep_number,'%d'%qty,'%d'%leadtime,'%s'%replicable])
else:
self.stdout.write('No products to sync with CBazaar.')
# #Build message for Production
# email = EmailMessage(subject='CBazaar Quantity Sync Details File', body='PFA CSV File attached with this mail.', from_email='help#voylla.com',
# to=['tamilmaran#cbazaar.com'], cc=['3pcatalogging#voylla.in'],
# headers = {'Reply-To': '3pcatalogging#voylla.in'})
# # Build message for Local
email = EmailMessage(subject='CBazaar Quantity Sync Details File', body='PFA CSV File attached with this mail.', from_email='help#voylla.com',
to=['abhishek.g#qa.voylla.com'],
headers = {'Reply-To': '3pcatalogging#voylla.in'})
# Attach csv file
email.attach("cbazaar_quantity_sync_"+task_start_time+".csv", csvresult.getvalue(), 'text/csv')
# Send message with built-in send() method
email.send()
#=================================================================#
##For sending Mail for "Zero Quantity Product" to Threep-Team
#=================================================================#
csvresult = StringIO.StringIO()
csvresultwriter = csv.writer(csvresult)
csvresultwriter.writerow(["Pri.Vendor Name","Product Code","Product Size","Design No","Stock Qty","Shipping Lead Time","Replicable (Yes / No)","Is stock Qty exclusively allocated to CBazaar ( Yes / No)"])
if len(products_to_sync) != 0:
for product in data:
# pdb.set_trace()
Store_Name = str('voylla retail pvt ltd')
sku = str(product[2])
size = str(product[3])
threep_number = str(product[1])
qty = int(product[7])
leadtime = int(product[8])
mod = str(product[11])
none = str('None')
if mod == none:
leadtime = 2
replicable = str('Yes')
product_obj = Product.objects.get(threep_number=threep_number)
channel_sku = self.threep_sku_mapping_method(channel,product_obj)
if qty == 0:
if channel_sku != 0:
sku=str(channel_sku)
csvresultwriter.writerow(['%s'%Store_Name,'%s'%sku,'%s'%size,'%s'%threep_number,'%d'%qty,'%d'%leadtime,'%s'%replicable])
else:
self.stdout.write('No Zero Quantity products to sync with CBazaar.')
# Build message for Threep-Team
email = EmailMessage(subject='CBazaar_"Zero_Quantity_product"_File', body='PFA CSV File attached with this mail.', from_email='help#voylla.com',
to=['abhishek.g#qa.voylla.com'])
# # Attach csv file
email.attach("cbazaar_zero_quantity_"+task_start_time+".csv", csvresult.getvalue(), 'text/csv')
# # Send message with built-in send() method
email.send()
return
The output i am getting also contains empty file with headers which i am passing.
I solved the problem to making the condition false :
the code snippet i change is just :
if len(products_to_sync) != 0:
for product in data:
# pdb.set_trace()
Store_Name = str('voylla retail pvt ltd')
sku = str(product[2])
size = str(product[3])
threep_number = str(product[1])
qty = int(product[7])
leadtime = int(product[8])
mod = str(product[11])
none = str('None')
if mod == none:
leadtime = 2
replicable = str('Yes')
product_obj = Product.objects.get(threep_number=threep_number)
channel_sku = self.threep_sku_mapping_method(channel,product_obj)
# pdb.set_trace()
if channel_sku != 0:
sku=str(channel_sku)
if qty == 0:
continue
else:
csvresultwriter.writerow(['%s'%Store_Name,'%s'%sku,'%s'%size,'%s'%threep_number,'%d'%qty,'%d'%leadtime,'%s'%replicable])
email = EmailMessage(subject='CBazaar Quantity Sync Details File', body='PFA CSV File attached with this mail.', from_email='help#voylla.com',
to=['abhishek.g#qa.voylla.com'],
headers = {'Reply-To': '3pcatalogging#voylla.in'})
# Attach csv file
email.attach("cbazaar_quantity_sync_"+task_start_time+".csv", csvresult.getvalue(), 'text/csv')
# Send message with built-in send() method
email.send()
else:
self.stdout.write('No products to sync with CBazaar.')

What is producing this python AttributeError when using get_current_user() method?

This line of code:
geted_nickname = user.nickname()
Of this Handler:
class MainHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user == None:
self.redirect(users.create_login_url(self.request.uri))
geted_nickname = user.nickname()
Is producing this error:
File "C:\Users\Py\Desktop\Apps\contract\main.py", line 99, in get
geted_nickname = user.nickname()
AttributeError: 'NoneType' object has no attribute 'nickname'
Since user is a NoneType object, the program should execute the if block self.redirect(users.create_login_url(self.request.uri)) , but this isn't happening. Why? How to fix that?
Thanks for any help!
Here the entire code:
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
import os
import webapp2
import jinja2
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
import re
from google.appengine.ext import db
USER_RE = re.compile(r"^[a-zA-Z0-9_ -]{3,20}$")
def valid_person(person):
return USER_RE.match(person)
PASS_RE = re.compile(r"^.{3,20}$")
def valid_SSN(SSN):
return PASS_RE.match(SSN)
EMAIL_RE = re.compile(r"^[\S]+#[\S]+\.[\S]+$")
def valid_email(email):
return EMAIL_RE.match(email)
clauses = {u'Software development agreement':"Don't be evil", 'Car Rental Contract':"non-skid the tires", 'House Rental Contract':"Don't break stuff"}
import time
import datetime
def dateToday():
today = datetime.datetime.today()
todayDay = str(today.day)
todayMonth = str(today.month)
monthExt = {'1':' January ', '2':'February', '3':' March ', '4':'April', '5':'May', '6':'June', '7':' July ', '8':'August', '9':'September', '10':'October', '11':'November ', '12':'December'}
todayYear = str(today.year)
return(todayDay + ' of ' + monthExt[todayMonth] + ' of ' + todayYear)
class Person(db.Model):
person_name = db.StringProperty(required = True)
nacionality = db.StringProperty(required = True)
marital_status = db.StringProperty(required = True)
profession = db.StringProperty(required = True)
SSN = db.IntegerProperty(required = True)
driver_license = db.IntegerProperty(required = True)
address = db.address = db.PostalAddressProperty(required = True)
class Contract(db.Model):
book_number = db.IntegerProperty(required = True)
initial_page = db.IntegerProperty(required = True)
final_page = db.IntegerProperty(required = True)
contract_type = db.StringProperty(required = True)
date = db.DateProperty (required = True, auto_now = True, auto_now_add = True)
class RegisteredUser(db.Model):
user_name = db.UserProperty()
user_nickname = db.StringProperty()
name = db.StringProperty()
user_position = db.StringProperty()
org_name = db.StringProperty()
org_address = db.StringProperty()
org_city = db.StringProperty()
org_state = db.StringProperty()
class ContractingParty(db.Model):
person = db.ReferenceProperty(Person, required=True, collection_name="party_to_contracts")
contract = db.ReferenceProperty(Contract, required=True)
condition = db.StringProperty(required = True, choices=set(["active position", "passive position", "witness"]))
class MainHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user == None:
self.redirect(users.create_login_url(self.request.uri))
geted_nickname = user.nickname()
registeredUser = db.GqlQuery("SELECT * FROM RegisteredUser WHERE user_nickname =:nickname", nickname = geted_nickname).get()
if registeredUser is None:
self.redirect('/register?user_nickname=%s' % (geted_nickname))
contract = db.GqlQuery("SELECT * FROM Contract ORDER BY date DESC").get()
if contract == None:
numBook = 1
numInitialPage = 1
numFinalPage = 1
else:
numBook = contract.book_number
numInitialPage = contract.final_page +1
numFinalPage = numInitialPage
template_values = {"numBook": numBook,
"numInitialPage": numInitialPage,
"numFinalPage": numFinalPage}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
def post(self):
choosed_contract_type = self.request.get("contract_type")
numBook = self.request.get("numBook")
numInitialPage = self.request.get("numInitialPage")
numFinalPage = self.request.get("numFinalPage")
person_name = self.request.get("person_name")
user_nacionality = self.request.get('nacionality')
user_profession = self.request.get('profession')
user_marital_status = self.request.get('marital_status')
user_driver_license = self.request.get('driver_license')
driver_license_error = ''
user_SSN = self.request.get('SSN')
SSN_error = ""
address = self.request.get('address')
person_name2 = self.request.get("person_name2")
user_nacionality2 = self.request.get('nacionality2')
user_profession2 = self.request.get('profession2')
user_marital_status2 = self.request.get('marital_status2')
user_driver_license2 = self.request.get('driver_license2')
user_SSN2 = self.request.get('SSN2')
SSN_error2 = ""
address2 = self.request.get('address2')
bsubmit = self.request.get('bsubmit')
if (bsubmit == 'Submit Contract') and (person_name and valid_person(person_name)) and (user_SSN and valid_SSN(user_SSN)):
contract_record = Contract(book_number = int(numBook),
initial_page = int(numInitialPage),
final_page = int(numFinalPage),
contract_type = choosed_contract_type)
contract_record.put()
contract_id = contract_record.key().id()
person_record = Person(person_name = person_name,
nacionality = user_nacionality,
profession = user_profession,
marital_status = user_marital_status,
driver_license = int(user_driver_license),
SSN = int(user_SSN),
address = address)
person_record.put()
person_id = person_record.key().id()
person_record2 = Person(person_name = person_name2,
nacionality = user_nacionality2,
profession = user_profession2,
marital_status = user_marital_status2,
driver_license = int(user_driver_license2),
SSN = int(user_SSN2),
address = address2)
person_record2.put()
person_id2 = person_record2.key().id()
self.redirect('/your_contract?contract_id=%s&person_id=%s&person_id2=%s' % (contract_id, person_id, person_id2))
else:
if not person_name or not valid_person(person_name):
person_name_error = "Oh no!!! this person name isn't valid!"
if not user_SSN or not valid_SSN(user_SSN):
SSN_error = "Oh no!!! SSN isn't valid!"
template_values = {"person_name": person_name,
"nacionality": user_nacionality,
"marital_status": user_marital_status,
"profession": user_profession,
"SSN": user_SSN,
"driver_license": user_driver_license,
## "email": user_email,
"person_name_error": person_name_error,
"SSN_error": SSN_error,
"driver_license_error": user_driver_license,
"address": address,
"person_name2":person_name2,
"nacionality2":user_nacionality2,
"marital_status2":user_marital_status2,
"profession2":user_profession2,
"driver_license2":user_driver_license2,
"SSN2":user_SSN2,
"address2":user_address2,
"contract_type":choosed_contract_type,
"numBook":geted_numBook,
"numInitialPage":geted_numInitialPage,
"numFinalPage":geted_numInitialPage,
}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
class your_contractHandler(webapp2.RequestHandler):
def get(self):
contract_id = self.request.get('contract_id')
contract = Contract.get_by_id(int(contract_id))
geted_contract_type = contract.contract_type
geted_clauses = clauses[geted_contract_type]
geted_numBook = contract.book_number
geted_numInitialPage = contract.initial_page
geted_numFinalPage = contract.final_page
geted_dateToday = dateToday()
user = users.get_current_user()
geted_nickname = user.nickname()
registered_user = db.GqlQuery("SELECT * FROM RegisteredUser WHERE user_nickname =:nickname", nickname = geted_nickname).get()
geted_autor_ato = registered_user.user_name
user_position = registered_user.user_position
org_name = registered_user.org_name
org_city = registered_user.org_city
org_state = registered_user.org_state
person_id = self.request.get('person_id')
person = Person.get_by_id(int(person_id))
geted_person_name = person.person_name
geted_user_nacionality = person.nacionality
geted_user_profession = person.profession
geted_user_marital_status = person.marital_status
geted_user_driver_license = person.driver_license
geted_user_SSN = person.SSN
geted_user_address = person.address
person_id2 = self.request.get('person_id2')
person2 = Person.get_by_id(int(person_id2))
geted_person_name2 = person2.person_name
geted_user_nacionality2 = person2.nacionality
geted_user_profession2 = person2.profession
geted_user_marital_status2 = person2.marital_status
geted_user_driver_license2 = person2.driver_license
geted_user_SSN2 = person2.SSN
geted_user_address2 = person2.address
your_contract = jinja_environment.get_template('your_contract.html')
your_contract_values = {"autor_ato":geted_autor_ato,
"user_position":user_position,
"org_name":org_name,
"org_city":org_city,
"org_state":org_state,
"contract_type":geted_contract_type,
"clauses":geted_clauses,
"dateContract":geted_dateToday,
"numBook":geted_numBook,
"numInitialPage":geted_numInitialPage,
"numFinalPage":geted_numInitialPage,
"person_name":geted_person_name,
"nacionality":geted_user_nacionality,
"marital_status":geted_user_marital_status,
"profession": geted_user_profession,
"driver_license":geted_user_driver_license,
"SSN":geted_user_SSN,
"address":geted_user_address,
"person_name2":geted_person_name2,
"nacionality2":geted_user_nacionality2,
"marital_status2":geted_user_marital_status2,
"profession2": geted_user_profession2,
"driver_license2":geted_user_driver_license2,
"SSN2":geted_user_SSN2,
"address2":geted_user_address2,
}
template = jinja_environment.get_template('index.html')
self.response.out.write(your_contract.render(your_contract_values))
class RegisterHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url(self.request.uri))
nickname = user.nickname()
template_values = {"user_nickname": nickname}
template = jinja_environment.get_template('register.html')
self.response.out.write(template.render(template_values))
def post(self):
user = users.get_current_user()
geted_user_nickname = user.nickname()
geted_user_name = self.request.get("user_name")
geted_user_position = self.request.get('position')
geted_org_name = self.request.get('org_name')
geted_org_address = self.request.get('org_adress')
geted_address = self.request.get('address')
geted_city = self.request.get('city')
registered_user = RegisteredUser(user = user,
user_name = geted_user_name,
user_nickname = geted_user_nickname,
position = geted_user_position,
org_name = geted_org_name,
org_address = geted_org_address,
city = geted_city,
)
registered_user.put()
## registered_user_id = registered_user.key().id()
self.redirect('/')
app = webapp2.WSGIApplication([('/', MainHandler), ('/your_contract', your_contractHandler), ('/register', RegisterHandler)],
debug=True)
According to the docs calling redirect does not stop code execution unless abort is set to True. It suggests returning the result of the redirect, e.g.:
return redirect('/some-path')
In your case, your method keeps executing, and user, which is None, is looking up an attribute that doesn't exist.

An strange python "if" syntax error

I get this error: Invaild syntax in my "if" statement and rly can't figur why, can anyone of you guys help me? I'm using python 3.2
here is the part of my code whit the error my code:
L = list()
LT = list()
tn = 0
players = 0
newplayer = 0
newplayerip = ""
gt = "start"
demsg = "start"
time = 1
status = 0
day = 1
conclient = 1
print("DONE! The UDP Server is now started and Waiting for client's on port 5000")
while 1:
try:
data, address = server_socket.recvfrom(1024)
if not data: break
################### reciving data! ###################
UPData = pickle.loads(data)
status = UPData[0][[0][0]
if status > 998: ##### it is here the error are given####
try:
e = len(L)
ori11 = UPData[0][1][0]
ori12 = UPData[0][1][1]
ori13 = UPData[0][1][2]
ori14 = UPData[0][1][3]
ori21 = UPData[0][1][4]
ori22 = UPData[0][1][5]
ori23 = UPData[0][1][6]
ori24 = UPData[0][1][7]
ori31 = UPData[0][2][0]
ori32 = UPData[0][2][1]
ori33 = UPData[0][2][2]
ori34 = UPData[0][2][3]
ori41 = UPData[0][2][4]
ori42 = UPData[0][2][5]
ori43 = UPData[0][2][6]
ori44 = UPData[0][2][7]
ori51 = UPData[0][3][0]
ori52 = UPData[0][3][1]
ori53 = UPData[0][3][2]
ori54 = UPData[0][3][3]
ori61 = UPData[0][3][4]
ori62 = UPData[0][3][5]
ori63 = UPData[0][3][6]
ori64 = UPData[0][3][7]
ori71 = UPData[0][4][0]
ori72 = UPData[0][4][1]
ori73 = UPData[0][4][2]
ori74 = UPData[0][4][3]
ori81 = UPData[0][4][4]
ori82 = UPData[0][4][5]
ori83 = UPData[0][4][6]
ori84 = UPData[0][4][7]
ori91 = UPData[0][5][0]
ori92 = UPData[0][5][1]
ori93 = UPData[0][5][2]
ori94 = UPData[0][5][3]
ori101 = UPData[0][5][4]
ori102 = UPData[0][5][5]
ori103 = UPData[0][5][6]
ori104 = UPData[0][5][7]
npcp11 = UPData[0][6][0]
npcp12 = UPData[0][6][1]
npcp13 = UPData[0][6][2]
npcp21 = UPData[0][6][3]
npcp22 = UPData[0][6][4]
npcp23 = UPData[0][6][5]
npcp31 = UPData[0][6][6]
npcp32 = UPData[0][6][7]
npcp33 = UPData[0][7][0]
npcp41 = UPData[0][7][1]
npcp42 = UPData[0][7][2]
npcp43 = UPData[0][7][3]
npcp51 = UPData[0][7][4]
npcp52 = UPData[0][7][5]
npcp53 = UPData[0][7][6]
npcp61 = UPData[0][7][7]
npcp62 = UPData[0][8][0]
npcp63 = UPData[0][8][1]
npcp71 = UPData[0][8][2]
npcp72 = UPData[0][8][3]
npcp73 = UPData[0][8][4]
npcp81 = UPData[0][8][5]
npcp82 = UPData[0][8][6]
npcp83 = UPData[0][8][7]
npcp91 = UPData[1][0][0]
npcp92 = UPData[1][0][1]
npcp93 = UPData[1][0][2]
npcp101 = UPData[1][0][3]
npcp102 = UPData[1][0][4]
npcp103 = UPData[1][0][5]
d0 = (status, )
d1 = (ori11,ori12,ori13,ori14,ori21,ori22,ori23,ori24)
d2 = (ori31,ori32,ori33,ori34,ori41,ori42,ori43,ori44)
d3 = (ori51,ori52,ori53,ori54,ori61,ori62,ori63,ori64)
d4 = (ori71,ori72,ori73,ori74,ori81,ori82,ori83,ori84)
d5 = (ori91,ori92,ori93,ori94,ori101,ori102,ori103,ori104)
d6 = (npcp11,npcp21,npcp31,npcp21,npcp22,npcp23,npcp31,npcp32)
d7 = (npcp33,npcp41,npcp42,npcp43,npcp51,npcp52,npcp53,npcp61)
d8 = (npcp62,npcp63,npcp71,npcp72,npcp72,npcp81,npcp82,npcp83)
d9 = (npcp91,npcp92,npcp93,npcp101,npcp102,npcp103)
pack1 = (d0,d1,d2,d3,d4,d5,d6,d7,d8)
pack2 = (d9, )
dat = pickle.dumps((pack1,pack2))
while tn < e:
server_socket.sendto(dat, (L[tn],3560))
tn = tn + 1
except:
pass
print("could not send data to some one or could not run the server at all")
else:
the part where the console tells me my error is is here:
if status > 998:
The problem is here:
status = UPData[0][[0][0]
The second opened bracket [ is not closed. The Python compiler keeps looking for the closing bracket, finds if on the next line and gets confused because if is not supposed to be inside brackets.
You may want to remove this bracket, or close it, according to your specific needs (the structure of UPData)

Categories