def valid_service_time_and_date(items): if len(items) == 0: raise ApiException("invalid serviceTimeAndDate", status_code=400) for item in items: if "date" not in item.keys(): raise ApiException("invalid serviceTimeAndDate missing 'date'", status_code=400) if "start" not in item.keys(): raise ApiException("invalid serviceTimeAndDate missing 'start'", status_code=400) return True
def validate_regular_service(service): required_entries = ('displayName', 'serviceTimeAndDate', "name") if valid_entries(required_entries, service): if len(service["serviceTimeAndDate"]) == 0: raise ApiException("missing service time and date", 400) try: valid_service_time_and_date(service["serviceTimeAndDate"]) except Exception as e: raise ApiException(e.__dict__.get("message"), status_code=400) return True else: raise ApiException( "missing required field, please make sure the following fields are present: {}" .format(str(required_entries)), status_code=400)
def delete_file(self, bucket, key): try: self.response = self.s3_client.delete_object(Bucket=bucket, Key=key) except Exception as e: raise ApiException( "something went wrong while deleting o s3 bucket", 400)
def internal_configurations(): query_params = request.args if request.method == "GET": internal_configs = InternalConfigurations() if query_params.get("feature"): return jsonify(internal_configs.find_by("feature", query_params.get("feature"))), 200 else: return jsonify(internal_configs.all), 200 elif request.method == "POST": internal_configs = InternalConfigurations(params=request.get_json()) if internal_configs.save: return jsonify({"message": "Internal Configuration created."}), 200 else: return jsonify({"message": "Internal Configuration not created."}), 400 elif request.method == "PUT": if not query_params.get("feature"): return jsonify({"missing query `feature`."}), 400 internal_configs = InternalConfigurations( feature=query_params.get("feature")) if internal_configs.exists: try: if internal_configs.update(request.get_json()): return jsonify({"message": "Succssefuly upated."}), 200 else: return jsonify({"message": "Something went wrong while upating."}), 200 except Exception as e: raise ApiException(e.message, 500) else: return jsonify({"message": "`{}`feature not found.".format(query_params.get("feature"))}), 404
def validate_user_profile(profile): required_entries = ('first_name', 'last_name', "email", "role", "password") if valid_entries(required_entries, profile): return True else: raise ApiException( "missing required field, please make sure the following fields are present: {}" .format(str(required_entries)), status_code=400)
def valid_seasonal_services(service): required_entries = ('title', 'displayName', 'services', "name", "month") if valid_entries(required_entries, service): services = service['services'] if len(services) == 0: raise ApiException("please provide services offered for {}".format( service["title"]), status_code=400) for service in services: try: valid_service_time_and_date(service["serviceTimeAndDate"]) except Exception as e: raise ApiException(e.__dict__.get("message"), status_code=400) return True else: raise ApiException( "missing required field, please make sure the following fields are present: {}" .format(str(required_entries)), status_code=400)
def upload_file(self, bucket, filename, file, path=''): try: key = filename if path: key = path + "/" + filename self.response = self.s3_resource.Bucket(bucket).put_object( Key=key, Body=file) except Exception as e: raise ApiException( "something went wrong while uploading to s3 bucket", 400)
def delete(self): if not self.params: self.message = "Missing 'name' param for delete operation." return False try: self.delete_by_schema_key(self._schema_key, self.params["feature"]) return True if self.status_code == 200 else False except KeyError: raise ApiException("Missing `feature` in request body.", 400) except Exception as e: return False
def ok(self): try: if self.service_type == "seasonal" or self.service_type == "commemoration": return SeasonalServiceInputSchema(self.params).valid elif self.service_type == "regular": return RegularServiceInputSchema(self.params).valid else: raise ApiException( "Invalid type '{}'.".format(self.service_type), 400) except SchemaError: self.error = SchemaError.__dict__.get('__doc__') return False
def contents(self): try: contents = self.response["Contents"] if contents[0]["Key"]: for item in contents: try: item["url"] = self.object_url(item["Key"]) except KeyError: raise ApiException("S3 bucket missing key.") return contents except KeyError: self.message = "No contents found in s3 bucket response." return ''
def list_files(self, bucket): try: contents = [] self.response = self.s3_client.list_objects(Bucket=bucket) for item in self.s3_client.list_objects(Bucket=bucket)['Contents']: contents.append(item) return contents except Exception as e: print(e) print(e.__dict__) self.message == e.__dict__.get("message") self.response = e.__dict__.get("response") if self.status_code == 404: raise ApiException("bucket not found", 400)
def validate_token(): if request.path in unprotected_path: return True token = request.headers.get("Authorization") if not token: raise ApiException("Missing authorization token.", status_code=401) web = HTTPcore( "https://xb54882p49.execute-api.us-east-1.amazonaws.com/prod/api/login", ) web.core("PUT", headers={"Authorization": token}) if web.get_status_code == 200: return True else: return False
def api_services(): args = request.args query_param = args.to_dict() #db = DynamoDb("services") if request.method == 'GET': services = Services() if len(args.to_dict()) == 2: data = services.where(query_param) if len(data) == 0: return jsonify({ "message": "No items found for {}.".format(str(query_param)) }), 404 else: return jsonify(data), 200 elif len(args.to_dict()) == 1: key = list(query_param.keys())[0] data = services.find_by(key, query_param.get(key)) if len(data) == 0: return jsonify({ "message": "No items found for {}.".format(str(query_param)) }), 404 return jsonify(data), 200 else: data = Services().all response = make_response(jsonify(data), 200) response.headers["Content-Range"] = len(data) response.headers['Access-Control-Expose-Headers'] = 'Content-Range' return response elif request.method == "POST": data = request.get_json() services = Services(params=data, type=args.get("type")) if not services.ok or services.exists: resp = {} if services.error: resp["error"] = services.error resp["message"] = services.message return jsonify(resp), 400 try: if services.save: return jsonify({"message": "Service created"}), 201 else: return jsonify({ "message": "Something went wrong when trying to create service" }), 500 except Exception as e: raise ApiException(e.__dict__.get("message"), status_code=400) elif request.method == 'PUT': data = request.get_json() if not args.get("name"): return jsonify({"message": "Missing query param 'name'."}), 400 services = Services() records = services.find_by("name", args.get("name")) if len(records) > 0: try: services.update(updates=data) return jsonify({"message": services.message}), 200 except Exception as e: raise ApiException(e.__dict__.get("message"), status_code=400) else: return jsonify({ "message": "no service found with the following name: {}".format( args.get("name")) }), 404 elif request.method == "DELETE": data = request.get_json() if not data: return jsonify({"message": "missing data"}), 400 services = Services(params=data) if args.get("type") and args.get("type") == "batch": try: services.delete_all(data) except Exception as e: raise ApiException( "Something went wrong when trying t batch delete", 500) else: try: if services.delete: return jsonify({"message": "Service deleted."}), 200 except Exception as e: raise ApiException(e.__dict__.get("message"), status_code=400)
def contact(): data = request.get_json() args = request.args bsc = False if args.get('from'): if args.get('from') == 'bsc': app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = store['bsc_email_password'] mail = Mail(app) bsc = True else: raise ApiException( 'Unkown email request for {}'.format(args.get('from')), 400) else: app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = store['zoho_password'] app.config['MAIL_SERVER'] = 'smtp.zoho.com' mail = Mail(app) if not data: raise ApiException("Request body cant be empty", 400) if not bsc: mail_item = Mails(params=data) to = mail_item.to or app.config["MAIL_USERNAME"] if bsc: child_info = data['child_info'] subject = "Summer Camp Registration Request for {}".format( child_info['first_name']) email = data['confirmation_for'] msg = Message(subject=subject, sender=app.config["MAIL_USERNAME"], recipients=[email]) full_name = "{} {}".format(child_info['first_name'], child_info['last_name']) msg.html = render_template("bsc_registration_confirmation.html", full_name=full_name, grade=child_info['grade'], status=data['registration_status']) mail.send(msg) return jsonify({'message': "Email confirmation sent."}), 200 elif mail_item.save: try: subject = "Mail from {}".format(mail_item.full_name) msg = Message(subject=subject, sender=app.config["MAIL_USERNAME"], recipients=[to]) msg.html = render_template("contact_from_website.html", full_name=mail_item.full_name, email=mail_item.email, message=mail_item.message.split('\n'), phone_number=mail_item.phone_number) mail.send(msg) return jsonify({"message": "Message saved and sent."}), 200 except Exception as e: return jsonify({ "message": "Message saved but not sent.", "error": e.__dict__ }), 500 return jsonify({ "message": "Mesage not saved.", "error": mail_item.error }), 400