def next_verse(request): schema = VerseSchema() verse_id = request.GET.get("verse_id") if not verse_id: raise api_exceptions.BadRequestData( errors="verse_id is a mandatory parameter") if verse_id == "12.13.23": raise api_exceptions.BadRequestData( errors="This is the end of knowledge") canto, chapter, verse = verse_id.split(".") nex = None if "-" in verse: nex = int(verse.split('-')[1]) + 1 else: nex = int(verse) + 1 verse_id = ".".join([canto, chapter, str(nex)]) filter_params = {"verse_id": verse_id} verse_obj = get_verse(filter_params) if not verse_obj: verse_id = ".".join([canto, str(int(chapter) + 1), "1"]) filter_params = {"verse_id": verse_id} verse_obj = get_verse(filter_params) if not verse_obj: verse_id = ".".join([str(int(canto) + 1), "1", "1"]) filter_params = {"verse_id": verse_id} verse_obj = get_verse(filter_params) resp_data = schema.dump(verse_obj, many=True) return JsonResponse( make_response(resp_data, message="Successfully fetched next verse", code=GET_SUCCESS_CODE))
def put(self, request): req_data = json.loads(request.body) schema = (self.schema)() try: verse_updates = schema.load(req_data, partial=('verse', 'translation', 'purport')) except MarshmallowValidationError as e: raise api_exceptions.BadRequestData(errors=e.messages) remove = ['chapter_num', 'canto_num', 'verse_num'] for item in remove: if item in verse_updates.keys(): del verse_updates[item] verse_obj = Verse.objects.filter(verse_id=req_data["verse_id"]) if not verse_obj: raise api_exceptions.ValidationError(errors="Verse doesn't exist") try: verse_obj.update(**verse_updates) except (DjangoValidationError, IntegrityError) as e: raise api_exceptions.ValidationError(errors=e.message_dict) resp_data = make_response({}, message="Successfully updated verse", code=PUT_SUCCESS_CODE) return JsonResponse(resp_data)
def post(self, request): req_data = json.loads(request.body) schema = (self.schema)() resp_data = [] verse_id = req_data['verse_id'] for req in req_data['purporttags']: try: req['verse_id'] = verse_id new_purport_section_tag = schema.load(req) except MarshmallowValidationError as e: raise api_exceptions.BadRequestData(errors=e.messages) try: new_purport_section_tag["tag"] = Tag3.objects.get( name=new_purport_section_tag["tag"]) purport_section_tags = PurportSectionTag.objects.create( **new_purport_section_tag) except DjangoValidationError as e: raise api_exceptions.ValidationError(errors=e.message_dict) except IntegrityError as e: raise api_exceptions.ValidationError( errors="DB Integrity error") resp_data.append(schema.dump(purport_section_tags)) return JsonResponse( make_response(resp_data, "Successfully added purport tags", POST_SUCCESS_CODE))
def delete(self, request, id, format=None): tag = self.schema.model.objects.filter(id=id) if not tag: raise api_exceptions.ValidationError(errors="Not a valid tag_id") tag[0].delete() return JsonResponse( make_response({}, "Successfully deleted purport tag", DELETE_SUCCESS_CODE))
def logout(request): """ This API is used to logout the user session from system. """ request.session.delete() code = 201 return JsonResponse(make_response({}, "Successfully logged out", code=code), status=code)
def login(request): """ This API is used to login a user in system. Access Token is return per user session. """ schema = LoginSchema() response = dict() # validate request data try: data = schema.loads(request.body) except ValidationError as e: raise api_exceptions.BadRequestData(errors=e.messages) print(data) # authenticate user in system user = authenticate(username=data["username"], password=data["password"]) if not user: raise api_exceptions.BadRequestData(errors="Invalid credentials") # generate user session id session_id = generate_random_alphenumeric_number(32) # get session data session = UserSession exp_time = settings.JWT_WEB_EXP_DELTA_HOURS # if session exists, delete this session and create new one session.objects.filter(user=user).delete() # create new session for user try: session.objects.create(user=user, session_id=session_id) # # Handling scenario for multiple user creation at same time except IntegrityError: raise api_exceptions.BadRequestData(errors="Session already exists") # read private secret key private_key = settings.JWT_SECRET # set payload with user id and expiry time payload = { "user_id": str(user.id), "exp": (timezone.now() + timezone.timedelta(hours=exp_time)), "session_id": session_id, } # encode token with private key token = jwt.encode(payload, private_key).decode("utf-8") response["token"] = token response["user_id"] = str(user.id) response["account_type"] = user.user_type request.user = user print(response) return JsonResponse(make_response(response, "Successfully logged in", code=201), status=201)
def put(self, request, id, format=None): tag = self.schema.model.objects.filter(id=id) if request.user.user_type != 3: raise api_exceptions.PermissionDenied( errors="Only reviewers are allowed to update") if not tag: raise api_exceptions.ValidationError(errors="Not a valid tag_id") tag[0].reviewer = request.user tag[0].save() return JsonResponse( make_response({}, "Successfully reviewed purport tag", PUT_SUCCESS_CODE))
def get(self, request): filter_params = {} filters = ["verse_id", "canto_num", "chapter_num", "verse_num"] for key in filters: if request.GET.get(key): filter_params[key] = request.GET.get(key) verses = Verse.objects.filter(**filter_params) schema = (self.schema)() data = schema.dump(verses, many=True) resp_data = make_response(data, message="Successfully fetched verses", code=GET_SUCCESS_CODE) return JsonResponse(resp_data)
def get(self, request): verse_filter_params = { "verse__canto_num": "canto_num", "verse__chapter_num": "chapter_num" } tag_filter_params = {"verse__verse_id": "verse_id"} verse_filters = get_filters(request, verse_filter_params) tag_filters = get_filters(request, tag_filter_params) tag_objects = PurportSectionTag.objects.filter( **tag_filters).select_related("verse") tag_objects = tag_objects.filter(**verse_filters).order_by("start_idx") schema = (self.schema)() data = schema.dump(tag_objects, many=True) resp_data = make_response(data, message="Successfully fetched purport tags", code=GET_SUCCESS_CODE) return JsonResponse(resp_data)
def get(self, request): filter_params = {} filters = ["verse_id", "canto_num", "chapter_num"] for key in filters: if request.GET.get(key): filter_params[key] = request.GET.get(key) verses = get_verse(filter_params) schema = (self.schema)() resp_data = None if verses: data = schema.dump(verses, many=True) resp_data = make_response(data, message="Successfully fetched verses", code=GET_SUCCESS_CODE) else: raise api_exceptions.BadRequestData( errors="Doesn't match with any existing verses") return JsonResponse(resp_data)
def post(self, request): # TODO :- Need to handle validation of verse_id in POST and PUT updates req_data = json.loads(request.body) schema = (self.schema)() try: additional_details = schema.load(req_data) except MarshmallowValidationError as e: raise api_exceptions.BadRequestData(errors=e.messages) verse_id = additional_details.pop("verse_id") try: Verse.objects.filter(verse_id=verse_id).update( **additional_details) except (DjangoValidationError, IntegrityError) as e: raise api_exceptions.ValidationError(errors=e.message_dict) resp_data = make_response( {}, message="Successfully added verse context and title", code=POST_SUCCESS_CODE) return JsonResponse(resp_data)
def prev_verse(request): schema = VerseSchema() verse_id = request.GET.get("verse_id") if not verse_id: raise api_exceptions.BadRequestData( errors="verse_id is a mandatory parameter") if verse_id == "1.1.1": raise api_exceptions.BadRequestData( errors="This is the beginning of knowledge") canto, chapter, verse = verse_id.split(".") prev = None if "-" in verse: prev = int(verse.split('-')[1]) - 1 else: prev = int(verse) - 1 verse_id = ".".join([canto, chapter, str(prev)]) filter_params = {"verse_id": verse_id} verse_obj = get_verse(filter_params) queryset = Verse.objects.values('canto_num', 'chapter_num', 'verse_id', 'verse_num') print(verse_id) if not verse_obj: try: last_verse = queryset.filter( canto_num=canto, chapter_num=int(chapter) - 1).order_by("-verse_num")[0]["verse_id"] filter_params = {"verse_id": last_verse} verse_obj = get_verse(filter_params) except: verse_obj = None if not verse_obj: last_verse = queryset.filter(canto_num=int(canto) - 1).order_by( "-chapter_num", "-verse_num")[0]["verse_id"] filter_params = {"verse_id": last_verse} verse_obj = get_verse(filter_params) resp_data = schema.dump(verse_obj, many=True) return JsonResponse( make_response(resp_data, message="Successfully fetched next verse", code=GET_SUCCESS_CODE))
def post(self, request): req_data = json.loads(request.body) schema = (self.schema)() resp_data = [] verse_id = req_data["verse_id"] for req in req_data["translationtags"]: try: req['verse_id'] = verse_id new_translation_tag = schema.load(req) print(new_translation_tag) except MarshmallowValidationError as e: raise api_exceptions.BadRequestData(errors=e.messages) new_translation_tag["verse"] = Verse.objects.get( verse_id=new_translation_tag["verse_id"]) new_translation_tag["tag"] = Tag3.objects.get( name=new_translation_tag["tag"]) new_translation_tag["tagger"] = request.user try: translation_tags = self.schema.model.objects.create( **new_translation_tag) except DjangoValidationError as e: raise api_exceptions.ValidationError(errors=e.message_dict) except IntegrityError as e: if new_translation_tag.get("tagger_remark"): t_tag = self.schema.model.objects.filter( verse_id=new_translation_tag["verse_id"], tag=new_translation_tag["tag"]) t_tag.update( tagger_remark=new_translation_tag["tagger_remark"]) t_tag[0].save() resp_data.append(schema.dump(t_tag[0])) continue else: raise api_exceptions.ValidationError( errors="DB Integrity error") resp_data.append(schema.dump(translation_tags)) return JsonResponse( make_response(resp_data, "Successfully added translation tags", POST_SUCCESS_CODE))
def register(request): """ This API is used to register the user to system. """ schema = RegisterSchema() # validate request data try: data = schema.loads(request.body) except ValidationError as e: raise api_exceptions.BadRequestData(errors=e.messages) user_type_dict = {"user": 1, "tagger": 2, "reviewer": 3} data["user_type"] = user_type_dict[data["user_type"]] try: password = data.pop("password") user = Account.objects.create(**data) user.set_password(password) user.save() except (IntegrityError, DjangoValidationError) as e: raise api_exceptions.BadRequestData(errors=e.messages) return JsonResponse(make_response({}, "Successfully registered user", code=201), status=201)