invalid literal for int() with base 10: 'string name' - python

I am making an API module which saves weather data to my Django database by running a single Django management command, which retries all the data from a source API. I've created a model 'weather data' which has all the required datatypes. I've a management command written which directly saves data to my database.
The snippet of management command and models.py is shown below.
def handle(self,*args,**kwargs):
for city in input_file:
city_name = city.strip()
print(city_name)
full_api_url = api + city_name + '&mode=json&units=' + unit + '&APPID=' + user_api
full_wet_url = weather_api + city_name + '&mode=json&units=' + unit + '&APPID=' + user_api
try:
data = requests.get(full_api_url).json()
dta = requests.get(full_wet_url).json()
city_id = dta["id"]
longitude = dta["coord"]["lon"]
latitude= dta["coord"]["lat"]
for dt in data["list"]:
temp = dt["main"]["temp"]
temp_min = dt["main"]["temp_min"]
temp_max = dt["main"]["temp_max"]
pressure = dt["main"]["pressure"]
sea_level = dt["main"]["sea_level"]
grnd_level = dt["main"]["grnd_level"]
humidity = dt["main"]["humidity"]
weather = dt["weather"][0]
main = weather["main"]
description = weather["description"]
clouds = dt["clouds"]["all"]
wind_speed = dt["wind"]["speed"]
wind_deg = dt["wind"]["deg"]
dt_txt = dt["dt_txt"]
wd = weatherdata(city_name,city_id,latitude,longitude,dt_txt,temp,temp_min,temp_max,pressure,sea_level,grnd_level,humidity,main,description,clouds,wind_speed,wind_deg).save()
print ("Success")
except Exception as e:
print (e)
pass
class weatherdata(models.Model):
city_name = models.CharField(max_length = 80)
city_id = models.IntegerField(default=0)
latitude = models.FloatField(null=True , blank=True)
longitude = models.FloatField(null=True , blank=True)
dt_txt = models.DateTimeField()
temp = models.FloatField(null = False)
temp_min = models.FloatField(null = False)
temp_max = models.FloatField(null = False)
pressure = models.FloatField(null = False)
sea_level = models.FloatField(null = False)
grnd_level = models.FloatField(null = False)
humidity = models.FloatField(null = False)
main = models.CharField(max_length=200)
description = models.CharField(max_length=30)
clouds = models.IntegerField(null=False)
wind_speed = models.FloatField(null = False)
wind_degree = models.FloatField(null = False)
if I try executing 'python manage.py theweather'(the weather being the name of management command file), am getting an error stating:
nantapur
invalid literal for int() with base 10: 'Anantapur'
Chittoor
invalid literal for int() with base 10: 'Chittoor'
Kakinada
invalid literal for int() with base 10: 'Kakinada'
for all the city names in headquarters.csv file.
what is the solution for this error?

You should use named parameters, using positional ones is "unstable" since if you later add some field, then it might go wrong. Note that the first parameter is here the implicit primary key:
wd = weatherdata.objects.create(
city_name=city_name,
city_id=city_id,
latitude=latitude,
longitude=longitude,
dt_txt=dt_txt,
temp=temp,
temp_min=temp_min,
temp_max=temp_max,
pressure=pressure,
sea_level=sea_level,
grnd_level=grnd_level,
humidity=humidity,
main=main,
description=description,
clouds=clouds,
wind_speed=wind_speed,
wind_deg=wind_deg
)
That being said, I'm not sure the modeling is good here, it contains a lot of data duplication.
Note that class names are usually written in CamelCase, so it should be WeatherData, not weatherdata.

Related

Updating data in a model from views Django

Hi i have a problem with updating data which is stored in a model. I would like to update the data which is stored in a model without a form, it is a function which sums up every user transaction and after every change I would like it to update.
my models:
class Portfolio(models.Model):
portfolio_id = models.AutoField(primary_key=True,blank=True)
portfolio_title = models.CharField(unique=True,max_length=200, null=True,blank=True)
user_name = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL,blank=True)
p_shares_num_sum = models.DecimalField(decimal_places=2,default=0,max_digits=999,editable=True, null=True,blank=True)
p_last_mod_date = models.DateField(auto_now_add=False,null=True,editable=True,blank=True)
p_comp_num_sum = models.DecimalField(decimal_places=2,default=0,max_digits=999,editable=True, null=True,blank=True)
p_to_buy_percentage = models.CharField(max_length=200,editable=True, null=True,blank=True)
p_profit_earned = models.DecimalField(decimal_places=6,editable=True,default=0,max_digits=999, null=True,blank=True)
def __str__(self):
return self.portfolio_title if self.portfolio_title else ''
```
The data which I want to send to it after every entry on site, with function
shares_num = visdata.aggregate(Sum(('shares_number')))
shares_num_sum = (shares_num['shares_number__sum'])
shares_num_sum = format(shares_num_sum, ".0f")
#profit_earned = visdata.aggregate(Sum(('course')))
#profit_sum = (profit_earned['course__sum'])
fare_paid = visdata.aggregate(Sum(('fare')))
fare_sum = (fare_paid['fare__sum'])
mod_date = visdata.order_by('-date').first().date
to_buy = visdata.filter(buy_sell='+').count()
to_sell = visdata.filter(buy_sell='-').count()
to_buy_percentage = 0
to_buy_percentage = to_buy / comp_number
to_buy_percentage = (to_buy_percentage) * 100
to_buy_percentage = format(to_buy_percentage, ".0f")
to_buy_percentage = str(to_buy_percentage) + '%'
#for customer restriction delete object and change VisData to visdata
aggregated_data = visdata.annotate(
intermid_result=F('course') - F('fare')
).annotate(
record_total=F('shares_number') * F('intermid_result')
).aggregate(
total=Sum('record_total')
)
profit_earned = aggregated_data['total']
profit_earned = format(profit_earned, ".2f")
summary_data = [int(shares_num_sum),int(comp_number),mod_date,str(to_buy_percentage),float(profit_earned)]
The function is written and prints me:
[4, 2, datetime.date(2021, 12, 20), '100%', 0.9]
If you have that data from function in your view, just get your current portolio object and asign to it's fields values, then call save() method from that object.
For example:
portfolio_object = Portfolio.objects.get(pk=some_pk)
portfolio_object.some_field = summary_data[0]
... here the rest of values
portfolio_object.save()
Remember that it'll execute every time you open that view, so think about some optimalization.

peewee - change schema dynamically

I have the same question/problem than this post -> peewee - modify db model meta (e.g. schema) dynamically . I want to change the schema field in my Meta class dynamically. This is my code:
class GPSPosition(Model):
def __init__(self, esquema, vehiculo, fechaFrom):
self.esquema = esquema + '_org'
self.vehiculo = vehiculo
self.fechaFrom = fechaFrom
orgid = BigIntegerField()
id = BigIntegerField()
vehicleid = BigIntegerField()
driverid = BigIntegerField()
originaldriverid = BigIntegerField(null=False)
blockseq = IntegerField(null=False)
time = DateTimeField(null=False)
latitude = FloatField(null=False)
longitude = FloatField(null=False)
altitude = SmallIntegerField(null=False)
heading = SmallIntegerField(null=False)
satellites = SmallIntegerField(null=False)
hdop = FloatField(null=False)#float
ageofreading = IntegerField(null=False)
distancesincereading = IntegerField(null=False)
velocity = FloatField(null=False)
isavl = BooleanField(null=False)
coordvalid = BooleanField(null=False)
speedkilometresperhour = DecimalField(null=False)
speedlimit = DecimalField(null=False)
vdop = SmallIntegerField(null=False)
pdop = SmallIntegerField(null=False)
odometerkilometres = DecimalField(null=False)
formattedaddress = CharField(null=False)
source = CharField(null=False)
class Meta:
database = db
schema = esquema
db_table = 'test_gpspositions'
primary_key = CompositeKey("orgid", "id")
Can someone please show me the light about this? Thanks!
Well I'll answer my own question since I found the answer time ago and it's very simple, just add this 1-2 lines at the point you want to change the schema name:
schemaname = 'your_schema_name'
setattr(YourPeeweeModel._meta, "schema", schemaname)
Works fine.

Instance Error On Foreign Key Field Django

Im stumped and need help on my function.
I have two tables student and student information. Student information is all guardian information of that student. I separated this data from the main student table so you can add as many guardians as you want to a students file with new records. The error I'm getting is as followed.
Cannot assign "'1'": "StudentInformation.studentpsid" must be a "Student" instance.
Attached you will see my code. Studentpsid in student information is a foreign key from student.
def ImportStudentGuardian(request):
AuthTokenP(request)
print("Getting student guardian data from SIS for K-8")
#Pulls K-8 Guardians
url = "removed for posting"
payload = {}
token = APIInformation.objects.get(api_name="PowerSchool")
key = token.key
headers = {'Authorization': 'Bearer {}'.format(key)}
response = requests.request("GET", url, headers=headers, data = payload)
encode_xml = response.text.encode('utf8')
xml_string = ET.fromstring(encode_xml)
students = xml_string.findall("student")
for student in students:
#XML Values
psid = student.find("id").text
try:
mother = student.find("contact").find("mother").text
except Exception:
mother = ""
try:
father = student.find("contact").find("father").text
except Exception:
father = ""
if Student.objects.filter(studentpsid=psid).exists():
print("Accessing guardian information.")
m = StudentInformation.objects.create(studentpsid=psid,guardian_name = mother, relation = "Mom") <---- Function Fails here
print("Record doesn't exist for mom, creating record.")
m.save()
d= StudentInformation.objects.create(studentpsid=psid,guardian_name = father, relation = "Dad")
print("Record doesn't exist for dad, creating record.")
d.save()
return ("Updated Guardian Information ")
Model
class Student(models.Model):
studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
student_name = models.CharField(max_length = 50)
first_name = models.CharField(max_length = 50, default = "")
last_name = models.CharField(max_length = 50,default = "")
gender = models.CharField(max_length = 1,default = "")
student_grade = models.CharField(max_length = 2, default = "")
home_room = models.CharField(max_length = 5, default = "")
student_enrollment = models.CharField(max_length = 2, default = "")
school_number = models.CharField(max_length = 15, default = "")
email = models.EmailField(default = "")
projected_graduation_year = models.CharField(max_length = 4, default = "")
counseling_goal = models.TextField(max_length = 255)
class_name = models.ManyToManyField(TeacherClass)
image = models.ImageField(default ="default.png", upload_to ='student_pics')
# Guardian Information For Student
class StudentInformation(models.Model):
studentpsid = models.ForeignKey(Student,on_delete = models.CASCADE, default = "" ,)
guardian_name = models.CharField(max_length = 50, default = "")
RELATION_CHOICES = [
(0, 'None'),
(1, 'Mom'),
(2, 'Dad'),
(3, 'Other'),
]
relation = models.PositiveSmallIntegerField(choices = RELATION_CHOICES,)
guardian_cell = models.CharField(max_length = 12, default = "")
guardian_email = models.EmailField(max_length = 80,blank = True, default = "")
prefered_contact = models.BooleanField(default = False, blank = True)
DAY_CHOICES = [
(0, 'None'),
(1, 'Monday'),
(2, 'Tuesday'),
(3, 'Wednesday'),
(4, 'Thursday'),
(5, 'Friday'),
]
day_of_week = models.PositiveSmallIntegerField(choices = DAY_CHOICES, default = 0 )
time = models.CharField(max_length= 7, default = "", blank = True)
While creating a record with the foreign key relation, and instance of the related table should be provided, so the table can maintain a relationship for that particular record.
Get the instance of the Student table with the given psid and use that while creating the StudentInformation record
EDIT : Included the part for creating the record only if mother and father values are available.
for student in students:
#XML Values
psid = student.find("id").text
try:
psid_obj = Student.objects.get(studentpsid=psid) #(pk = psid) also works as the field is primary key
try:
mother = student.find("contact").find("mother").text
m = StudentInformation.objects.create(studentpsid=psid_obj,guardian_name = mother, relation = "Mom")
m.save()
except Exception as err1:
print "Error at Mom", str(err1)
try:
father = student.find("contact").find("father").text
d= StudentInformation.objects.create(studentpsid=psid_obj,guardian_name = father, relation = "Dad")
d.save()
except Exception as err2:
print "Error at Dad",str(err2)
except:
print "Student Record Not found"
As the error says, you are assigning a char data type to the ForeignKey field.
You should first get the instance of that Student, and then assign it to your StudentInformation object, like this:
if Student.objects.filter(studentpsid=psid).exists():
print("Accessing guardian information.")
student = Student.objects.get(pk=psid) # this will fail if the student doesn't exist
m = StudentInformation.objects.create(studentpsid=student,guardian_name = mother, relation = "Mom") <---- Function Fails here
print("Record doesn't exist for mom, creating record.")
m.save()
d= StudentInformation.objects.create(studentpsid=student,guardian_name = father, relation = "Dad")
print("Record doesn't exist for dad, creating record.")
d.save()
return ("Updated Guardian Information ")

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))

Proper way to format date for Fedex API XML

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)

Categories