I keep getting random indentationError using OS X and Pycharm (Tried switching tabs and spaces in pycharm settings no luck). If I run the project under linux it works just fine. The below code attempts to upload the users from a csv, I've attempted to comment and different fields that dont exist in this group of users.
import csv
from django.contrib.auth import get_user_model
User = get_user_model()
members = open('Volunteers.csv', "rU")
data = csv.DictReader(members)
default_password = User.objects.make_random_password()
def generate_username(first_name, last_name):
val = "{0}{1}".format(first_name[0], last_name[0]).lower()
x = 0
while True:
if x == 0 and User.objects.filter(username=val).count() == 0:
return val
else:
new_val = "{0}{1}".format(val, x)
if User.objects.filter(username=new_val).count() == 0:
return new_val
x += 1
if x > 1000000:
raise Exception("Name is super popular!")
for row in data:
email = row['Email']
first_name = row['First Name'],
last_name = row['Last Name'],
username = generate_username(first_name, last_name)
user = User.objects.create_user(username, email, default_password)
user.is_staff = False
user.volunteer = True
user.active = row['Active']
user.first_name = row['First Name']
user.last_name = row['Last Name']
user.organization = row['Organization']
user.interview = row['Interview']
user.house_number_street_name = row['Address']
user.state = row['State']
user.city = row['City']
user.zip_code = row['Zip Code']
user.daytime_phone = row['Daytime Phone']
user.home_phone = row['Home Phone']
user.cell_phone = row['Cell Phone']
user.organization = row['Organization']
user.emergency_contact = row['Emergency Contact']
user.days_available = row['Days Available']
user.food_pantry = row['Food Pantry']
user.interview = row['Interview']
user.bi_lingual = bool(row['Bilingual'])
user.fund_raising = row['Fund Raising']
user.board_member = row['Board Member']
user.sunshine_committee = row['Sunshine Committe']
user.solicit_donations = row['Solicit Donations']
user.record_keeping = row['Record Keeping']
user.truck_or_van = row['Truck or Van']
user.pick_up_food = row['Pick up Food']
user.deliver_food = row['Deliver Food']
user.save()
# user.comments = row['Comments']
# user.drivers_licence = row['Drivers Licence Number']
# user.unemployment = row['Unemployment']
# user.food_stamps = row['Food Stamps']
# user.disability = row['Disability']
# user.salary = row['Salary']
# user.pension = row['Pension']
# user.ss_ssi = row['Social and Supplemental Income']
The logs
IndentationError: unexpected indent
>>> user.record_keeping = row['Record Keeping']
File "<console>", line 1
user.record_keeping = row['Record Keeping']
^
IndentationError: unexpected indent
>>> user.truck_or_v user.truck_or_v ]
File "<console>", line 1
user.truck_or_v user.truck_or_v ]
^
IndentationError: unexpected indent
>>> user.pick_up_food = row['Pick up Food']
File "<console>", line 1
user.pick_up_food = row['Pick up Food']
^
IndentationError: unexpected indent
>>> user.deliver_food = row['Deliver Food']
File "<console>", line 1
user.deliver_food = row['Deliver Food']
^
IndentationError: unexpected indent
>>> user.save()
File "<console>", line 1
user.save()
^
Updated code that will run in reference to comment below asking to comment out lines with errors.
import csv
from django.contrib.auth import get_user_model
User = get_user_model()
members = open('Volunteers.csv', "rU")
data = csv.DictReader(members)
default_password = User.objects.make_random_password()
def generate_username(first_name, last_name):
val = "{0}{1}".format(first_name[0], last_name[0]).lower()
x = 0
while True:
if x == 0 and User.objects.filter(username=val).count() == 0:
return val
else:
new_val = "{0}{1}".format(val, x)
if User.objects.filter(username=new_val).count() == 0:
return new_val
x += 1
if x > 1000000:
raise Exception("Name is super popular!")
for row in data:
email = row['Email']
first_name = row['First Name'],
last_name = row['Last Name'],
username = generate_username(first_name, last_name)
user = User.objects.create_user(username, email, default_password)
user.is_staff = False
user.volunteer = True
user.active = row['Active']
user.first_name = row['First Name']
user.last_name = row['Last Name']
user.organization = row['Organization']
user.interview = row['Interview']
user.house_number_street_name = row['Address']
user.state = row['State']
user.city = row['City']
user.zip_code = row['Zip Code']
user.daytime_phone = row['Daytime Phone']
user.save()
# user.home_phone = row['Home Phone']
# user.cell_phone = row['Cell Phone']
# user.organization = row['Organization']
# user.emergency_contact = row['Emergency Contact']
# user.days_available = row['Days Available']
# user.food_pantry = row['Food Pantry']
# user.interview = row['Interview']
# user.bi_lingual = bool(row['Bilingual'])
# user.fund_raising = row['Fund Raising']
# user.board_member = row['Board Member']
# user.sunshine_committee = row['Sunshine Committe']
# user.solicit_donations = row['Solicit Donations']
# user.record_keeping = row['Record Keeping']
# user.truck_or_van = row['Truck or Van']
# user.pick_up_food = row['Pick up Food']
# user.deliver_food = row['Deliver Food']
# user.save()
# user.comments = row['Comments']
# user.drivers_licence = row['Drivers Licence Number']
# user.unemployment = row['Unemployment']
# user.food_stamps = row['Food Stamps']
# user.disability = row['Disability']
# user.salary = row['Salary']
# user.pension = row['Pension']
# user.ss_ssi = row['Social and Supplemental Income']
Related
I have the following list :
['[infotype02]', 'lastModifiedOn = serial<customMapping>', 'customString18 = BADGE_NUMBER<move>', 'firstName = FIRST_NAME<move>', 'lastName = LAST_NAME<move>', 'customString29 = USER_NAME<move>', 'email = EMAIL_ADDRESS<move>', 'documenttype = DOC_TYPE<move>', 'documentnumber = DOC_SERIA<customMapping>', 'documentnumberx2 = DOC_NUMBER<customMapping>', 'issuedate = DOC_ISSUE_DATE<move>', 'issueauthority = DOC_ISSUER<move>', 'nationalId = CNP<move>', 'company = COMPANY<move>', 'phoneNumber = PHONE_NUMBER<move>', 'startDate = HIRE_DATE<customMapping>', 'startDatex2 = TERMINATION_DATE<customMapping>', '[/infotype02]', '[infotype02]', 'lastModifiedOn = serial<customMapping>', 'customString18 = BADGE_NUMBER<move>', 'firstName = FIRST_NAME<move>', 'lastName = LAST_NAME<move>', 'customString29 = USER_NAME<move>', 'email = EMAIL_ADDRESS<move>', 'documenttype = DOC_TYPE<move>', 'documentnumber = DOC_SERIA<customMapping>', 'documentnumberx2 = DOC_NUMBER<customMapping>', 'issuedate = DOC_ISSUE_DATE<move>', 'issueauthority = DOC_ISSUER<move>', 'nationalId = CNP<move>', 'company = COMPANY<move>', 'phoneNumber = PHONE_NUMBER<move>', 'startDate = HIRE_DATE<customMapping>', 'startDatex2 = TERMINATION_DATE<customMapping>', '[/infotype02]']
for i in list; i = [infotype02]
I tried using re expression to get the string between the [], expected result infotype02 :
result = re.search('[(.*)]', i)
Then tried to append the result.group(1) to a new list and it returned an error :
lst.append(result.group(1))
AttributeError: 'NoneType' object has no attribute 'group'
I don't understand what is wrong with my re expresion and why isn't it finding the string between the []
You can just use a simple for-loop to accomplish this:
data = ['[infotype02]', 'lastModifiedOn = serial<customMapping>', 'customString18 = BADGE_NUMBER<move>', 'firstName = FIRST_NAME<move>',
'lastName = LAST_NAME<move>', 'customString29 = USER_NAME<move>', 'email = EMAIL_ADDRESS<move>', 'documenttype = DOC_TYPE<move>',
'documentnumber = DOC_SERIA<customMapping>', 'documentnumberx2 = DOC_NUMBER<customMapping>', 'issuedate = DOC_ISSUE_DATE<move>',
'issueauthority = DOC_ISSUER<move>', 'nationalId = CNP<move>', 'company = COMPANY<move>', 'phoneNumber = PHONE_NUMBER<move>',
'startDate = HIRE_DATE<customMapping>', 'startDatex2 = TERMINATION_DATE<customMapping>', '[/infotype02]', '[infotype02]',
'lastModifiedOn = serial<customMapping>', 'customString18 = BADGE_NUMBER<move>', 'firstName = FIRST_NAME<move>', 'lastName = LAST_NAME<move>',
'customString29 = USER_NAME<move>', 'email = EMAIL_ADDRESS<move>', 'documenttype = DOC_TYPE<move>', 'documentnumber = DOC_SERIA<customMapping>',
'documentnumberx2 = DOC_NUMBER<customMapping>', 'issuedate = DOC_ISSUE_DATE<move>', 'issueauthority = DOC_ISSUER<move>', 'nationalId = CNP<move>',
'company = COMPANY<move>', 'phoneNumber = PHONE_NUMBER<move>', 'startDate = HIRE_DATE<customMapping>', 'startDatex2 = TERMINATION_DATE<customMapping>',
'[/infotype02]']
new_list = []
for d in data:
if d[0] == '[' and not d[1] == '/':
#if re.match(r"\[[^/](.*)\]", d): # If you want to use `re`
new_list.append(d[1:-1])
print(new_list)
Output:
['infotype02', 'infotype02']
As you have 2 of these tags in your given list.
I have a Django function that takes in a Nessus file and then parses the data before saving it to the database, my Nessus file typically has about 30k rows and saving this to the database can take as much as 2 hours, I have tried using bulk_create but this breaks the code, meanwhile I use Django 1.11, is there a way I can speed up these large inserts to the database (postgres)
Here is my code:
def process_nessus_file(*args, **kwargs):
process_obj = kwargs.get('file')
context = kwargs.get('context')
request = kwargs.get('request')
file_obj = process_obj.first()
file_path = file_obj.file.path
context = etree.iterparse(
file_path,
events=('end', ),
tag="ReportHost"
)
total_issues = 0
detected_issues = 0
undetected_issues = 0
already_exist_issue = 0
low_risk_count = 0
medium_risk_count = 0
high_risk_count = 0
critical_risk_count = 0
low_new_issue = 0
medium_new_issue = 0
high_new_issue = 0
critical_new_issue = 0
vul_history = []
for event, elem in context:
first_identified = None
last_seen = None
host = elem.get('name')
logger.info('Processing issue for host : {}'.format(host))
for child in elem:
if child.tag == "HostProperties":
for host_prop_tags in child:
if host_prop_tags.attrib['name'] == "HOST_START":
first_identified = host_prop_tags.text
elif host_prop_tags.attrib['name'] == "HOST_END":
last_seen = host_prop_tags.text
if child.tag == "ReportItem":
main_tags = child.attrib
child_tags = dict()
for ch_tags in child:
if ch_tags.text:
tag_text = ch_tags.text.strip()
else:
tag_text = ch_tags.text
child_tags[ch_tags.tag] = tag_text
if child_tags.get('solution') and \
child_tags.get('solution') in ['n/a', 'N/A']:
child_tags['solution'] = ''
plugin_output = child_tags.get('plugin_output')
pluginid = int(main_tags.get('pluginID'))
if plugin_output and (pluginid == 10107):
if re.search(BANNER_PATTERN, plugin_output):
banner_pattern = plugin_output.replace("{}".\
format(BANNER_PATTERN), "")
banner = banner_pattern.strip()
else:
banner = ''
else:
banner = ''
risk = child_tags.get('risk_factor')
synopsis = child_tags.get('synopsis')
description = child_tags.get('description')
solution = child_tags.get('solution')
protocol = main_tags.get('protocol')
port = main_tags.get('port')
pluginname = main_tags.get('pluginName')
svcname = main_tags.get('svc_type')
try:
host_type = get_host_type(host)
user_host = check_host_exists(host, host_type)
if user_host and not NessusData.objects.filter(
plugin_id=int(pluginid), host=host,
port=int(port), name=pluginname
).exists():
try:
host_link_obj = Host.objects.get(
host=host
)
except Host.MultipleObjectsReturned:
host_link_obj = host.objects.filter(
host=host
).first()
except Host.DoesNotExist:
host_link_obj = Host.objects.create(
host=host,
user_host=user_host
)
nessus_obj = NessusFile.objects.create(
user_host=user_host,
host_link=host_link_obj,
linked_file=file_obj,
plugin_id=int(pluginid),
risk=risk, host=host,
protocol=protocol, port=int(port),
banner=banner, name=pluginname,
svc_type=svcname,
description=description,
first_identified=first_identified,
last_seen=last_seen,
synopsis=synopsis,
plugin_output=plugin_output,
solution=solution
)
issue = "Issue with host {}, port {} and"\
" pluginID {} is added.".\
format(
nessus_obj.host, nessus_obj.port,
nessus_obj.plugin_id
)
NessusFileLog.objects.create(
linked_file=file_obj,
issue_type="new",
issue=issue
)
detected_issues = detected_issues + 1
if risk == 'Medium':
medium_new_issue = medium_new_issue + 1
elif risk == 'Low':
low_new_issue = low_new_issue + 1
elif risk == 'High':
high_new_issue = high_new_issue + 1
elif risk == 'Critical':
critical_new_issue = critical_new_issue + 1
else:
nessus_obj = NessusFile.objects.filter(
plugin_id=int(pluginid), host=host,
port=int(port), name=pluginname
).first()
if nessus_obj and not nessus_obj.last_seen:
nessus_obj.last_seen = last_seen
nessus_obj.save()
issue = "Issue with host {}, port {} and"\
" pluginID {} is already exists.".\
format(host,port, pluginid)
NessusFileLog.objects.create(
linked_file=file_obj,
issue_type="duplicate",
issue=issue
)
already_exist_issue = already_exist_issue + 1
except Exception as e:
pass
if risk == 'Medium':
medium_risk_count = medium_risk_count + 1
elif risk == 'Low':
low_risk_count = low_risk_count + 1
elif risk == 'High':
high_risk_count = high_risk_count + 1
elif risk == 'Critical':
critical_risk_count = critical_risk_count + 1
total_issues = total_issues + 1
elem.clear()
while elem.getprevious() is not None:
del elem.getparent()[0]
I heard using raw sql queries will speed it up but I cant wrap my head around the process
I would like to save an object in my database during the Celery task. This object is an export file. The Celery task lets to create it and I would like to store it in my table.
This is my models.py :
class CeleryExportFile(models.Model):
name = models.CharField(max_length=100, verbose_name=_('Name of export file'), default='')
file = models.FileField(upload_to='media/', default='')
creation_date = models.DateTimeField(verbose_name=_('Creation date'), auto_now_add=True)
expiration_date = models.DateTimeField(verbose_name=_('Expiration date'))
def __str__(self):
return self.file
class Meta:
verbose_name = _('Celery Export File')
verbose_name_plural = _('Celery Export Files')
I have a Celery tasks.py file :
def get_xls_export(self, model="", search_info="", query_params=None):
app_label = 'app'
its_fp_or_up_product = False
query_params = query_params or {}
obsolete = False
if query_params.get('obsolete', '') == 'True':
obsolete = True
default_sorting_key = ''
show_date_format = settings.USER_DATE_FORMAT
if model == "finalproduct" or model == "upstreamproduct":
its_fp_or_up_product = True
default_sorting_key = 'manufacturer_name' if model == "finalproduct" else 'releasing_body__short_name'
if model == "releasebodyinstitution":
default_sorting_key = 'name'
model = apps.get_model(app_label=app_label, model_name=model)
# create a workbook in memory
output = io.BytesIO()
book = Workbook(output, {'constant_memory': True})
sheet = book.add_worksheet('Page 1')
# Sheet header, first row
row_num = 0
columns = model.export_field_excel()
rows_width_max = {}
bold_format = book.add_format({'bold': True})
max_col_width = []
for col_num in range(len(columns)):
rows_width_max[col_num] = columns[col_num].__len__()
sheet.write(row_num, col_num, columns[col_num], bold_format)
max_col_width.append(len(columns[col_num]) if len(columns[col_num]) > 10 else 10)
default_sorting = True
sorting_key = ''
# Define search get all object or sorted value.
if search_info != '':
create_filters = search_info.split(';')
if create_filters.__len__() == 1:
if 'sorting' in create_filters[0]:
default_sorting = False
sorting_key = create_filters[0].split('=')[1].replace('~', '-')
search_info = ''
else:
for criter in create_filters:
if 'sorting' in criter:
default_sorting = False
sorting_key = criter.split('=')[1].replace('~', '-')
search_info = search_info.replace(criter, "")
search_info = search_info[:-1]
objects = model.objects.all()
if not its_fp_or_up_product:
if obsolete:
objects = objects.obsolete()
else:
objects = objects.active()
if sorting_key:
objects = objects.order_by(sorting_key, 'pk')
if default_sorting:
objects = objects.order_by(default_sorting_key, 'pk')
if search_info != '':
create_filters = search_info.split(';')
for search_filter in create_filters:
search_filter = search_filter.split('=')
try:
if search_filter[1]:
objects = objects.filter(**{search_filter[0]: search_filter[1]})
except:
# Crud patch search
if search_filter[0] == 'q':
search_info = search_info.replace('q=', '')
objects = objects.filter(get_query(search_info, model.get_xls_values_list()))
rows = objects.values_list(*model.get_xls_values_list())
for row in rows:
row_num += 1
for col_num in range(len(row)):
# Patch True False for boolean field
is_bool = False
if type(row[col_num]) is bool:
is_bool = True
if col_num in model.get_date_field_number():
if row[col_num]:
sheet.write(row_num, col_num, row[col_num].strftime(show_date_format))
else:
if is_bool:
sheet.write(row_num, col_num, 'True' if row[col_num] else 'False')
else:
sheet.write(row_num, col_num, row[col_num])
if len(str(row[col_num])) > max_col_width[col_num]:
max_col_width[col_num] = len(str(row[col_num]))
# AutoFit col
for col_num in range(len(columns)):
sheet.set_column(col_num, col_num, max_col_width[col_num] + 1)
book.close()
output.seek(0)
name = str(name + "_" + str(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%s")) + '.xlsx')
CeleryExportFile.save(name=name, file=output, expiration_date=datetime.datetime.now())
# default_storage.save(name, output)
try:
self.send_email(name=name)
except ConnectionRefusedError as e:
return ['error_message', _('Error for sending email')]
return ['success_message', _('Generation of export file is done')]
I'm getting this issue :
[2019-02-14 12:23:56,151: ERROR/ForkPoolWorker-4] Task app.tasks.get_xls_export[80e7ea2e-4192-4df7-ba05-83a14805225f] raised unexpected: TypeError("save() got an unexpected keyword argument 'name'",)
Traceback (most recent call last):
File "/home/.pyenv/versions/3.6.2/envs/app/lib/python3.6/site-packages/celery/app/trace.py", line 382, in trace_task
R = retval = fun(*args, **kwargs)
File "/home/.pyenv/versions/3.6.2/envs/app/lib/python3.6/site-packages/celery/app/trace.py", line 641, in __protected_call__
return self.run(*args, **kwargs)
File "/home/Bureau/Projets/app/src/app/tasks.py", line 151, in get_xls_export
CeleryExportFile.save(name='test', file=book, expiration_date=datetime.datetime.now())
TypeError: save() got an unexpected keyword argument 'name'
How I can save my file into my database ?
I have to set name, file, .. as kwargs and create a save() method in my models.py with kwargs.pop ?
Just do it as following:
celery_export_file = CeleryExportFile(name=name, file=output, expiration_date=datetime.datetime.now())
celery_export_file.save()
or you can call create() method like:
CeleryExportFile.objects.create(name=name, file=output, expiration_date=datetime.datetime.now())
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)
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.