def write_json(self, value): """ Convert the value to JSON, then write to response. This will mostly be used by API handlers. """ response = json.dumps(value) self.response.headers[b'Content-Type'] = b'application/json' self.response.write(response)
def return_error(self, errors): if self.is_ajax: self.response.set_status(400) self.response.write(json.dumps(errors)) return self.template_values["title"] = "Donatie 2%" self.template_values["ngo"] = self.ngo self.template_values["counties"] = LIST_OF_COUNTIES self.template_values["errors"] = errors for key in self.request.POST: self.template_values[ key ] = self.request.POST[ key ] # render a response self.render()
def get(self): """default web page (index.html)""" #data = [['Age', 'Adopted', 'Euthanized'],['< 6 months', 1000, 400],['6-12 months', 1170, 460],['12-5 years', 660, 1120],['>5 years', 1030, 540]] # Get data from the json file. data = self.get_all_data() columns = data['columns'] rows = data['rows'] # specify the ages we will search for age_mapping = {u'Infant - Younger than 6 months':'<6mo', u'Youth - Younger than 1 year':'6mo-1yr', u'Older than 1 year':'1yr-6yr', u'Older than 7 years':'>7yr', u'':'Unspecified'} # create an 'empty' array storing the number of dogs in each outcome # specify the outcomes we will search for outcomes = ['Adopted', 'Euthanized', 'Foster', 'Returned to Owner', 'Transferred to Rescue Group', 'Other'] ages = ['<6mo', '6mo-1yr', '1yr-6yr', '>7yr', 'Unspecified'] age_by_outcome = [] for age in ages: res = {'Age': age} for outcome in outcomes: res[outcome] = 0 age_by_outcome = age_by_outcome + [res] # find the column id for ages ageid = columns.index(u'Age') # find the column id for outcomes outcomeid = columns.index(u'OutcomeType') # loop through each row for row in rows: # get the age of the dog in that row age = age_mapping[row[ageid]] # get the outcome for the dog in that row outcome = row[outcomeid] # if the age is a known value (good data) find # out which of the items in our list it corresponds to if age in ages: age_position = ages.index(age) # otherwise we will store the data in the 'Other' age column else: age_position = ages.index('Other') # if the outcome is a bad value, we call it 'Other' as well if outcome not in outcomes: outcome = 'Other' # now get the current number of dogs with that outcome and age outcomes_for_age = age_by_outcome[age_position] # and increase it by one outcomes_for_age[outcome] = outcomes_for_age[outcome] + 1 logging.info(age_by_outcome) # add it to the context being passed to jinja variables = {'data':json.dumps(age_by_outcome), 'y_labels':outcomes, 'x_labels':ages} # and render the response self.render_response('index.html', variables)
def post(self, ngo_url): post = self.request errors = { "fields": [], "server": False } self.ngo = NgoEntity.get_by_id(ngo_url) if self.ngo is None: self.error(404) return # if we have an ajax request, just return an answer self.is_ajax = self.request.get("ajax", False) def get_post_value(arg, add_to_error_list=True): value = post.get(arg) # if we received a value if value: # it should only contains alpha numeric, spaces and dash if re.match(r'^[\w\s.\-ăîâșț]+$', value, flags=re.I | re.UNICODE) is not None: # additional validation if arg == "cnp" and len(value) != 13: errors["fields"].append(arg) return "" return value # the email has the @ so the first regex will fail elif arg == 'email': # if we found a match if re.match(r'[^@]+@[^@]+\.[^@]+', value) is not None: return value errors["fields"].append(arg) return '' else: errors["fields"].append(arg) elif add_to_error_list: errors["fields"].append(arg) return "" donor_dict = {} # the donor's data donor_dict["first_name"] = get_post_value("nume").title() donor_dict["last_name"] = get_post_value("prenume").title() donor_dict["father"] = get_post_value("tatal").title() donor_dict["cnp"] = get_post_value("cnp", False) donor_dict["email"] = get_post_value("email").lower() donor_dict["tel"] = get_post_value("tel", False) donor_dict["street"] = get_post_value("strada").title() donor_dict["number"] = get_post_value("numar", False) # optional data donor_dict["bl"] = get_post_value("bloc", False) donor_dict["sc"] = get_post_value("scara", False) donor_dict["et"] = get_post_value("etaj", False) donor_dict["ap"] = get_post_value("ap", False) donor_dict["city"] = get_post_value("localitate").title() donor_dict["county"] = get_post_value("judet") # if he would like the ngo to see the donation donor_dict['anonymous'] = post.get('anonim') != 'on' # the ngo data ngo_data = { "name": self.ngo.name, "account": self.ngo.account.upper(), "cif": self.ngo.cif, "special_status": self.ngo.special_status } if len(errors["fields"]): self.return_error(errors) return captcha_response = submit(post.get(CAPTCHA_POST_PARAM), CAPTCHA_PRIVATE_KEY, self.request.remote_addr) # if the captcha is not valid return if not captcha_response.is_valid: errors["fields"].append("codul captcha") self.return_error(errors) return # the user's folder name, it's just his md5 hashed db id user_folder = security.hash_password('123', "md5") # a way to create unique file names # get the local time in iso format # run that through SHA1 hash # output a hex string filename = "{0}/{1}/{2}".format(USER_FORMS, str(user_folder), sha1( datetime.datetime.now().isoformat() ).hexdigest()) pdf = create_pdf(donor_dict, ngo_data) file_url = CloudStorage.save_file(pdf, filename) # close the file after it has been uploaded pdf.close() # create the donor and save it donor = Donor( first_name = donor_dict["first_name"], last_name = donor_dict["last_name"], city = donor_dict["city"], county = donor_dict["county"], email = donor_dict['email'], tel = donor_dict['tel'], anonymous = donor_dict['anonymous'], # make a request to get geo ip data for this user geoip = self.get_geoip_data(), ngo = self.ngo.key, pdf_url = file_url ) donor.put() # set the donor id in cookie self.session["donor_id"] = str(donor.key.id()) self.session["has_cnp"] = bool(donor_dict["cnp"]) # send and email to the donor with a link to the PDF file self.send_email("twopercent-form", donor) # if not an ajax request, redirect if self.is_ajax: self.response.set_status(200) response = { "url": self.uri_for("ngo-twopercent-success", ngo_url=ngo_url), "form_url": file_url } self.response.write(json.dumps(response)) else: self.redirect( self.uri_for("ngo-twopercent-success", ngo_url=ngo_url) )