def http_bad_request_view(request, *args, **kwargs): '''View handler for http 400 bad request ''' request_id = str(uuid4()) request_epoch = time.time() * 1000 request_parameters = resolve(request.path_info) request.url_info = { 'kwargs': request_parameters.kwargs, 'url_name': request_parameters.url_name, 'app_names': request_parameters.app_names, 'app_name': request_parameters.app_name, 'namespaces': request_parameters.namespaces, 'namespace': request_parameters.namespace, 'view_name': request_parameters.view_name } log_request(request_id, request, request_epoch, request_parameters.view_name) response = BadRequest().response log_response(request_id, request, request_epoch, response) return response
def manage_videos_search(request): """View to manage videos request Args: request: A Django HttpRequest Returns: response: videos list """ if request._body: request_data = json.loads(request._body) else: raise BadRequest("No query in POST body") # set of allowed search keys search_keys = {"title", "description", "channelTitle", "videoURL"} query = {} for term, value in request_data.items(): if term in search_keys: query[term] = value # searching videos with required query video_list = Video.objects.search_videos(query) response = {"metadata": {"count": len(video_list)}, "data": video_list} return OK(response)
def auth(request): if request.method == 'GET': email = request.GET.get('email', '') if not email or not validate_email(email): raise BadRequest("Invalid Email Address") otp = otpgen() gmail = Gmail(settings.GMAIL_USER, settings.GMAIL_PASSWORD) gmail.send_message( email, 'Vaccine Alert One Time Password', f'Please use OTP - {otp} to register for vaccine alert') encrypted_key = encrypt(otp).decode() data = {'encrypted_key': encrypted_key} return OK(data) if request.method == 'POST': body_unicode = request.body.decode('utf-8') request_data = json.loads(body_unicode) authorize_user(request_data['encrypted_key'], request_data['otp']) validate_email(request_data['email']) user_details = UserDetails.objects.fetch_user_details( request_data['email']) data = {"data": {"userDetails": user_details}} return OK(data)
def update_grid(self, grid_id, data): '''Method to update grid based on id Args: grid_id: string(uuid) data: dictionary Return: tuple (boolean, dictionary) Raise: HttpError ''' try: nodes = data.get('nodes') edges = data.get('edges') if not self.validator.validate(nodes, edges): return True, 'All the edges are not connected, Failed to update' err, grid = self.manager.update_grid_by_id(grid_id, data, True) if not err: return False, grid return True, grid if grid else 'Invalid Id' except Exception as e: traceback.print_exc() if e.__class__.__name__ == 'ValidationError': raise PymodmValidationError(e.__str__()) raise BadRequest(e.__str__())
def store_grid(self, data): '''Method to add a grid Args: data: Dict Return: Tuple (boolean, dict) Raise: PymodmValidationError or BadRequest ''' try: nodes = data.get('nodes') if len(set(nodes)) != len(nodes): return True, 'duplicate node names' if not self.validator.validate(nodes, data.get('edges')): return True, 'All the edges are not connected' return False, self.manager.add_grid(data, True) except Exception as e: traceback.print_exc() if e.__class__.__name__ == 'ValidationError': raise PymodmValidationError(e.__str__()) raise BadRequest(e.__str__())
def find_optimal_route(self, grid_id, start, end): '''Method to find optimal route between two given nodes Args: grid_id: string(uuid) Return: tuple (boolean, dict) Raise: HttpError ''' try: grid = self.manager.grid_by_id(grid_id, transform=True) if grid: optimal_route = find_optimal_route(grid.get('edges'), start, end) if optimal_route: return False, {"optimalRoute": optimal_route} return True, 'There is no route between given point !' return True, 'Invalid id' except Exception as e: traceback.print_exc() if e.__class__.__name__ == 'ValidationError': raise PymodmValidationError(e.__str__()) raise BadRequest(e.__str__())
def get(self, request, grid_id): '''get method to find the optimal route between two points Args: grid_id: string Return: dictionary Raise: BadRequest ''' start = request.query_params.get('start', None) end = request.query_params.get('end', None) if not start and not end: raise BadRequest(400, 'Please provide start and end nodes !') err, res = self.handler_obj.find_optimal_route(grid_id, start, end) if err: raise BadRequest(400, res) return JSONResponse({'data': res, 'message': 'success', 'statusCode': 200})
def post(self, request): '''get function process POST request Args: request: Request Object Return: JSONResponse Raise: BadRequest ''' data = request.data err, res = self.handler_obj.store_grid(data) if err: raise BadRequest(400, res) return Created({'data': res, 'message': 'success', 'statusCode': 201})
def delete(self, request, grid_id): '''DELETE method for each Gride Args: request: Request object grid_id: String(UUID) Return: JSONResponse Raise: BadRequest ''' #delete each grid err, res = self.handler_obj.delete_grid(grid_id) if err: raise BadRequest(400, res) return OK({'message': res, 'statusCode': 200})
def put(self, request, grid_id): '''Update method for each Gride Args: request: Request object grid_id: String(UUID) Return: JSONResponse Raise: BadRequest ''' data = request.data err, res = self.handler_obj.update_grid(grid_id, data) if err: raise BadRequest(400, res) return JSONResponse({'data': res, 'message': 'success', 'statusCode': 201})
def get(self, request, grid_id): '''get function to get each Gride Args: request: Request object grid_id: String(UUID) Return: JSONResponse Raise: BadRequest ''' #get each grid err, res = self.handler_obj.get_grid(grid_id) if err: raise BadRequest(400, res) return JSONResponse({'data': res, 'message': 'success', 'statusCode': 201})
def delete_grid(self, grid_id): '''Method to delete a grid by id Args: grid_id: string(uuid) Return: string ''' try: err, res = self.manager.delete_grid_by_id(grid_id) if err: return err, res return err, 'Successfully delete' except Exception as e: traceback.print_exc() if e.__class__.__name__ == 'ValidationError': raise PymodmValidationError(e.__str__()) raise BadRequest(e.__str__())
def request_validator(request_info): '''This method is used to validate all incoming requests before the request goes to handlers. It validates url params, query params and request body for expected schema. Args: request_info: Dictonary containing information extracted from Django's request object. Returns: True: If request validates according to route config. Raises: BadRequest: In case any of the query param does not match with the expected value Example: { "error": { "message": "Request validation failed", "code": 400, "errors": { "urlParams": [ { "message": "healthModuleId must be of integer type" } ] } } } ''' config_query = { 'routeName': request_info['route_name'], 'isActive': True, 'method': request_info['method'] } request_config = RequestValidationConfig.objects.get_one( queries=config_query) if request_config: response = {} query_param_schema = request_config.get('queryParams') url_param_schema = request_config.get('urlParams') request_body_schema = request_config.get('requestBodySchema') if query_param_schema: query_param_status = validate_params(query_param_schema, request_info, 'queryParams') if query_param_status: response["queryParams"] = query_param_status if url_param_schema: url_param_status = validate_params(url_param_schema, request_info, 'urlParams') if url_param_status: response["urlParams"] = url_param_status if request_body_schema: request_body_status = None try: data = json.loads(request_info['request_body'].decode('utf-8')) except Exception: request_body_status = [{"message": "Invalid request body."}] else: request_body_status = validate_json_body( data, request_body_schema) if request_body_status: response["requestBody"] = request_body_status if response: raise BadRequest(errors=response) return True
def register_user(request): body_unicode = request.body.decode('utf-8') request_data = json.loads(body_unicode) authorize_user(request_data['encrypted_key'], request_data['otp']) if request.method == 'POST': email = request_data['email'] pincode = request_data.get("pincode") if not email or not validate_email(email): raise BadRequest("Invalid Email Address") user_details = UserDetails.objects.fetch_user_details(email) if user_details: raise BadRequest("User Alerady registered") if pincode and not validate_pincode(pincode): raise BadRequest("Invalid Pincode") try: user_details = { "email": request_data['email'], "district": request_data.get("district"), "pincode": request_data.get("pincode"), "age": request_data["age"], } user_details = UserDetails.objects.insert_user_details( user_details) except Exception: raise BadRequest("Email, district, pincode, age are required") return OK({'data': user_details}) if request.method == 'PATCH': email = request_data['email'] user_details = UserDetails.objects.fetch_user_details(email) if (user_details['active'] == request_data['active'] and user_details.get("pincode", '') == request_data.get( "pincode", '') and user_details['age'] == request_data['age'] and user_details.get("district", '') == request_data.get( "district", '')): raise BadRequest("Nothing to Update") if not email or not validate_email(email) or not user_details: raise BadRequest("Invalid Email Address") if request_data.get("district", '') and validate_pincode( request_data.get("district", '')): raise BadRequest("Invalid Pincode") try: user_details = { "district": request_data.get("district"), "pincode": request_data.get("pincode"), "age": request_data["age"], "active": request_data["active"] } user_details = UserDetails.objects.update_user_details( email, user_details) except Exception: raise BadRequest("Email, district, pincode, age are required") return OK(user_details)