Exemplo n.º 1
0
    def put(self):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()
            print(args_data)
            print(post_data)
            user = args_data.get("user")
            # user = args_data.get("user", "all")
            # print(f'condition: {(not user or post_data)}')

            if not user or not post_data:
                response = {
                    "meta": self.meta,
                    "message": "unable to process request",
                    "status": "failure",
                }
                return response, self.bad_code, self.headers

            users_data.load(post_data, partial=True)

            columns = {"_id": 0}
            queries = {"_id": ObjectId(user)}
            collection = 'common_user_master'
            user_data = FlaskMongo.find(collection, columns, **queries)

            if user_data == []:
                response = {
                    "meta": self.meta,
                    "message": f"user {user} does not exists",
                    "status": "failure",
                }
                return response, self.bad_code, self.headers

            updates = post_data
            queries = {"_id": ObjectId(user)}
            collection = 'common_user_master'
            FlaskMongo.update(collection, updates, **queries)

            response = {
                "meta": self.meta,
                "message": f"user {user} updated successfully",
                "status": "success"
            }
            return response, self.success_code, self.headers

        except Exception as e:
            # raise e
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            return response, self.exception_code, self.headers
Exemplo n.º 2
0
    def get(self):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            print(args_data)

            user = args_data.get("user", "all")
            if user == "all":
                queries = {"deleted": 0}
                columns = {"_id": 0}
            else:
                queries = {"_id": ObjectId(user), "deleted": 0}
                columns = {"_id": 0}

            collection = 'common_user_master'
            query_data = FlaskMongo.find(collection, columns, **queries)

            print(f'query_data: {query_data}')

            response = {"meta": self.meta, "users": query_data}
            return response, self.success_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            return response, self.exception_code, self.headers
Exemplo n.º 3
0
	def post(self):
		'''
		'''
		try:
			post_data = request.get_json()
			token_data.load(post_data)

			columns = {"_id": 1, "account_type": 1}
			queries = post_data
			collection = 'common_user_master'
			user_data = FlaskMongo.find(collection, columns, queries)

			print(post_data)
			print(f'user_data: {user_data}')
			username = post_data.get('username')

			if user_data == []:
				response = {
					"meta": self.meta,
					# "message": f"user {username} does not exists",
					"message": "please check provided credentials",
					"status": "failure",
				}
				FlaskLogger.log('post', 'token_generation', response, log_level='info')
				return response, self.auth_code, self.headers

			user_data = user_data[0]
			auth_token = generate_auth_token(post_data, user_data)

			response = {
				"meta": self.meta,
				"token": auth_token,
				"status": "success"
			}
			FlaskLogger.log('post', 'token_generation', response, log_level='info')
			return response, self.success_code, self.headers

		except ValidationError as e:
			# raise e
			# print(e)
			response = {
				"meta": self.meta,
				"message": "unable to process request",
				"status": "failure",
				"errors": format_api_error(e.messages)
			}
			FlaskLogger.log('post', 'token_generation', response, log_level='error')
			return response, self.bad_code, self.headers

		except Exception as e:
			# raise e
			response = {
				"meta": self.meta,
				"message": "unable to process request",
				"status": "failure",
				"reason": str(e)
			}
			FlaskLogger.log('post', 'token_generation', response, log_level='warning')
			return response, self.exception_code, self.headers
Exemplo n.º 4
0
    def get(self):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            test_id = args_data.get('testid')

            db = c_app.config.get('MONGO_DATABASE')
            collection1 = 'common_user_master'

            columns = {'_id': 0}
            queries = {}
            aggregate_pipeline = [{
                '$group': {
                    '_id': '$institute_name',
                    'count': {
                        '$sum': 1
                    }
                }
            }]
            institute_counts = FlaskMongo.find(collection1,
                                               columns,
                                               queries,
                                               aggregate=aggregate_pipeline)

            columns = {'_id': 0}
            queries = {}
            distinct_column = 'institute_name'
            institute_names = FlaskMongo.find(collection1,
                                              columns,
                                              queries,
                                              distinct=True,
                                              distinct_column=distinct_column)

            total_users = db[collection1].find({}).count()
            deleted_users = db[collection1].find({"deleted": 1}).count()
            users = {
                'total': total_users,
                'deleted': deleted_users,
                'active': total_users - deleted_users
            }

            columns = {'_id': 1}
            queries = {}
            users_ids = FlaskMongo.find(collection1, columns, queries)
            users_ids = [uid.get('_id') for uid in users_ids]

            stats = {
                'users_ids': users_ids,
                'users': users,
                'institute_counts': institute_counts,
                'institute_names': institute_names
            }

            response = {"meta": self.meta, "status": "success", "stats": stats}
            return response, self.success_code, self.headers

        except Exception as e:
            # raise e
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            return response, self.exception_code, self.headers
Exemplo n.º 5
0
    def post(self, **kwargs):
        '''
		'''
        try:
            post_data = request.get_json()

            rooms_data.load(post_data)
            print(post_data.keys())

            # Check for already exising entry:

            db = c_app.config.get('MONGO_DATABASE')
            collection = 'common_room_master'
            collection2 = 'common_user_master'
            teacher_id = post_data.get("teacher_id")
            room_name = post_data.get("room_name")

            columns = {"_id": 0}
            queries = {"teacher_id": teacher_id, "room_name": room_name}
            queries2 = {"_id": ObjectId(teacher_id)}
            room_data = FlaskMongo.find(collection, columns, queries)
            user_data = FlaskMongo.find(collection2, columns, queries2)

            print(post_data)
            print(f'room_data: {room_data}')

            if user_data == []:
                response = {
                    "meta": self.meta,
                    "message": f"teacher with id {teacher_id} does not exists",
                    "status": "failure",
                }
                FlaskLogger.log('post',
                                'add_rooms_info',
                                response,
                                input_data=str(post_data),
                                log_level='info')
                return response, self.bad_code, self.headers

            if room_data != []:
                response = {
                    "meta": self.meta,
                    "message": f"room {room_name} is already created",
                    "status": "failure",
                }
                FlaskLogger.log('post',
                                'add_rooms_info',
                                response,
                                input_data=str(post_data),
                                log_level='info')
                return response, self.bad_code, self.headers

            room_id = get_uuid1()
            post_data["room_id"] = room_id
            post_data["deleted"] = 0
            post_data["created"] = datetime.now().isoformat()
            FlaskMongo.insert(db, collection, post_data)

            response = {
                "meta": self.meta,
                "message": f"new room with id {room_id} added successfully",
                "status": "success"
            }
            FlaskLogger.log('post',
                            'add_rooms_info',
                            response,
                            input_data=str(post_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except ValidationError as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "errors": format_api_error(e.messages)
            }
            FlaskLogger.log('post',
                            'add_rooms_info',
                            response,
                            input_data=str(post_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('post',
                            'add_rooms_info',
                            response,
                            input_data=str(post_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 6
0
    def delete(self, **kwargs):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            # testquestion_data.load(args_data, partial=True)

            test_id = args_data.get("testid")
            queries = {'id': test_id, "deleted": 0}
            columns = {'_id': 0}
            collection1 = 'common_test_master'
            test_data = FlaskMongo.find(collection1, columns, queries)

            if not test_data:
                response = {
                    "meta": self.meta,
                    "message": f"test with id {test_id} does not exists",
                    "status": "failure",
                }
                FlaskLogger.log('delete',
                                'del_tests_info',
                                response,
                                input_data=str(args_data),
                                log_level='info')
                return response, self.bad_code, self.headers

            elif test_data:
                test_data = test_data[0]
                if test_data.get('deleted') == 1:
                    response = {
                        "meta": self.meta,
                        "message": f"test with id {test_id} does not exists",
                        "status": "failure",
                    }
                    FlaskLogger.log('delete',
                                    'del_tests_info',
                                    response,
                                    input_data=str(args_data),
                                    log_level='info')
                    return response, self.bad_code, self.headers

            updates1 = {"deleted": 1}
            queries1 = {"id": test_id}
            FlaskMongo.update(collection1, updates1, queries1)

            collection2 = 'common_question_master'
            updates2 = {"deleted": 1}
            queries2 = {"testid": test_id}
            FlaskMongo.update(collection2, updates2, queries2)

            response = {
                "meta": self.meta,
                "message": f"test with id {test_id} has been deleted",
                "status": "success",
            }
            FlaskLogger.log('delete',
                            'del_tests_info',
                            response,
                            input_data=str(args_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except ValidationError as e:
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": format_api_error(e.messages)
            }
            FlaskLogger.log('delete',
                            'del_tests_info',
                            response,
                            input_data=str(args_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('delete',
                            'del_tests_info',
                            response,
                            input_data=str(args_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 7
0
    def put(self, **kwargs):
        '''
			Issue: check time validators, works in post request
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()

            print(post_data)
            print(args_data)

            args_data.update(post_data)
            testquestion_data.load(post_data, partial=True)

            test_id = args_data.get("testid")
            queries = {'id': test_id, "deleted": 0}
            columns = {'_id': 0}
            collection = 'common_test_master'
            query_data = FlaskMongo.find(collection, columns, queries)

            if not query_data:
                response = {
                    "meta": self.meta,
                    "message": f"test with id {test_id} does not exists",
                    "status": "failure",
                }
                FlaskLogger.log('put',
                                'mod_tests_info',
                                response,
                                input_data=str({
                                    'ad': args_data,
                                    'pd': post_data
                                }),
                                log_level='info')
                return response, self.bad_code, self.headers

            collection1 = 'common_test_master'
            collection2 = 'common_question_master'

            updates1 = {
                "id": test_id,
                "details": post_data.get("details"),
                "schedule": post_data.get("schedule"),
                "duration": post_data.get("duration"),
                "start_time": post_data.get("start_time"),
                "end_time": post_data.get("end_time"),
                "no_mandatory_questions":
                post_data.get("no_mandatory_questions")
            }
            queries1 = {"id": test_id}
            FlaskMongo.update(collection1, updates1, queries1)

            for qna in post_data.get("qna"):
                data2 = {
                    "customerid": post_data.get("customerid"),
                    "testid": test_id,
                    "question": qna.get("question"),
                    "option1": qna.get("options")[0],
                    "option2": qna.get("options")[1],
                    "option3": qna.get("options")[2],
                    "option4": qna.get("options")[3],
                    "answer": qna.get("answer")
                }
                updates2 = data2
                queries2 = {
                    "_id": ObjectId(qna.get("_id")),
                    "testid": test_id,
                    "customerid": data2.get("customerid")
                }
                FlaskMongo.update(collection2, updates2, queries2)

            response = {
                "meta": self.meta,
                "message": f"test with id {test_id} updated successfully",
                "status": "success"
            }
            FlaskLogger.log('put',
                            'mod_tests_info',
                            response,
                            input_data=str({
                                'ad': args_data,
                                'pd': post_data
                            }),
                            log_level='info')
            return response, self.success_code, self.headers

        except ValidationError as e:
            print(f'exception: {e}\n')
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": format_api_error(e.messages)
            }
            FlaskLogger.log('put',
                            'mod_tests_info',
                            response,
                            input_data=str({
                                'ad': args_data,
                                'pd': post_data
                            }),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('put',
                            'mod_tests_info',
                            response,
                            input_data=str({
                                'ad': args_data,
                                'pd': post_data
                            }),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 8
0
    def post(self):
        '''
			A Test Attempt can be new or redo
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()
            post_data.update(args_data)

            print(post_data)

            testattempt_data.load(post_data)
            student_name = post_data.get("student_name")
            phone_no = post_data.get("phone_no")

            print(post_data.keys())

            # Check for already exising entry:

            db = c_app.config.get('MONGO_DATABASE')
            collection1 = 'common_test_student'
            collection2 = 'common_test_student_ques_answers'

            test_id = args_data.get("test_id")
            student_id = args_data.get("student_id")

            columns = {"_id": 0}
            queries = {
                "test_id": test_id,
                "student_id": student_id  #, "is_complete": True
            }
            test_data = FlaskMongo.find(collection1, columns, queries)
            test_qna_data = FlaskMongo.find(collection2, columns, queries)

            print(post_data)

            if test_data and test_qna_data:
                response = {
                    "meta": self.meta,
                    "message": f"Test {test_id} is under progress",
                    "status": "failure",
                }
                FlaskLogger.log('post',
                                'add_test_attempt_info',
                                response,
                                input_data=str(post_data),
                                log_level='info')
                return response, self.bad_code, self.headers
            else:
                data1 = {
                    "student_id": student_id,
                    "test_id": test_id,
                    "student_name": student_name,
                    "phone_no": phone_no,
                    "timestamp": datetime.now().isoformat()
                }
                FlaskMongo.insert(db, collection1, data1)

                data2 = [{
                    "student_id": student_id,
                    "test_id": test_id,
                    "question_id": qa.get("_id"),
                    "question": qa.get("question"),
                    "answer": qa.get("answer"),
                    "is_correct": qa.get("is_correct"),
                    "timestamp": datetime.now().isoformat()
                } for qa in post_data.get('qna')]

                # Bulk Insert Records Here:

                FlaskMongo.insert(db, collection2, data2, bulk=True)

                response = {
                    "meta": self.meta,
                    "message": f"test with id {test_id} started successfully",
                    "status": "success"
                }
                FlaskLogger.log('post',
                                'add_test_attempt_info',
                                response,
                                input_data=str(post_data),
                                log_level='info')
                return response, self.success_code, self.headers

        except ValidationError as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "errors": format_api_error(e.messages)
            }
            FlaskLogger.log('post',
                            'add_test_attempt_info',
                            response,
                            input_data=str(post_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('post',
                            'add_test_attempt_info',
                            response,
                            input_data=str(post_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 9
0
    def put(self):
        '''
			A Test Attempt can be new or redo
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()
            post_data.update(args_data)

            print(post_data)

            testattempt_data.load(post_data, partial=True)
            student_name = post_data.get("student_name")
            phone_no = post_data.get("phone_no")
            is_complete = post_data.get("is_complete")

            print(post_data.keys())

            # Check for already exising entry:

            db = c_app.config.get('MONGO_DATABASE')
            collection1 = 'common_test_student'
            collection2 = 'common_test_student_ques_answers'
            test_id = args_data.get("test_id")
            student_id = args_data.get("student_id")

            columns = {"_id": 0}
            queries = {
                "test_id": test_id,
                "student_id": student_id  #, "is_complete": True
            }

            print(post_data)

            test_data = FlaskMongo.find(collection1, columns, queries)
            test_qna_data = FlaskMongo.find(collection2, columns, queries)

            print(post_data)

            if not test_data and not test_qna_data:
                response = {
                    "meta": self.meta,
                    "message": f"No data found for Test with {test_id}",
                    "status": "failure",
                }
                FlaskLogger.log('put',
                                'mod_test_attempt_info',
                                response,
                                input_data=str(args_data, post_data),
                                log_level='info')
                return response, self.bad_code, self.headers
            else:
                queries1 = {"student_id": student_id, "test_id": test_id}
                updates1 = {
                    "student_name": student_name,
                    "phone_no": phone_no,
                    # "is_complete": is_complete
                }
                # data1["created"] = datetime.now().isoformat()

                FlaskMongo.update(collection1, updates1, queries1)

                for qa in post_data.get('qna'):
                    queries2 = {
                        "student_id": student_id,
                        "test_id": test_id,
                        "question_id": qa.get("_id"),
                        "question": qa.get("question"),
                    }
                    updates2 = {
                        "answer": qa.get("answer"),
                        "is_correct": qa.get("is_correct")
                    }

                    # Update Question Answers Here:

                    FlaskMongo.update(collection2, updates2, queries2)

            response = {
                "meta": self.meta,
                "message": f"test attempt with {test_id} updated successfully",
                "status": "success"
            }
            FlaskLogger.log('put',
                            'mod_test_attempt_info',
                            response,
                            input_data=str(args_data, post_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except ValidationError as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "errors": format_api_error(e.messages)
            }
            FlaskLogger.log('put',
                            'mod_test_attempt_info',
                            response,
                            input_data=str(args_data, post_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('put',
                            'mod_test_attempt_info',
                            response,
                            input_data=str(args_data, post_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 10
0
    def get(self, **kwargs):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            print(args_data)

            user = args_data.get("user", "all")
            pageno = int(args_data.get("pageno", 1))
            if user == "all":
                if pageno > 1:
                    skip = 10 * (pageno - 1)
                else:
                    skip = 0
                queries = {"deleted": 0, "account_type": self.account_type}
                columns = {"_id": 0, "deleted": 0}
                collection = 'common_user_master'
                query_data1 = FlaskMongo.find(collection, columns, queries)

                queries = {"deleted": 0, "account_type": self.account_type}
                columns = {"_id": 0, "deleted": 0}
                query_data2 = FlaskMongo.find(collection,
                                              columns,
                                              queries,
                                              skip=skip,
                                              limit=10)

                total_count = len(query_data1)
                total_pages = math.ceil(total_count / (10))
                query_data = {
                    'total':
                    total_pages,
                    'pageno':
                    pageno,
                    'previous':
                    pageno -
                    1 if pageno > 1 and pageno <= total_pages else None,
                    'next':
                    pageno + 1 if pageno < total_pages else None,
                    'data':
                    query_data2
                }

            else:
                queries = {
                    "_id": ObjectId(user),
                    "deleted": 0,
                    "account_type": self.account_type
                }
                columns = {"_id": 0, "deleted": 0}
                collection = 'common_user_master'
                query_data = FlaskMongo.find(collection, columns, queries)
                if query_data:
                    query_data = query_data[0]
                else:
                    query_data = {}

            print(f'query_data: {query_data}')

            response = {"meta": self.meta, "users": query_data}
            FlaskLogger.log('get',
                            f'{self.account_type}_info',
                            response,
                            input_data=str(args_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('get',
                            f'{self.account_type}_info',
                            response,
                            input_data=str(args_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 11
0
    def delete(self, **kwargs):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()
            print(args_data)
            # print(post_data)

            teacherusers_data.load(args_data, partial=True)
            userid = args_data.get("userid")
            # user = args_data.get("user", "all")
            # print(f'condition: {(not user or post_data)}')

            columns = {"_id": 0}
            queries = {"_id": ObjectId(userid)}
            collection = "common_user_master"

            user_data = FlaskMongo.find(collection, columns, queries)
            print(f'user_data: {user_data}')

            if not user_data:
                response = {
                    "meta": self.meta,
                    "message": f"user with id {userid} does not exists",
                    "status": "failure",
                }
                FlaskLogger.log('delete',
                                f'del_{self.account_type}_info',
                                response,
                                input_data=str(args_data),
                                log_level='info')
                return response, self.bad_code, self.headers

            elif user_data:
                user_data = user_data[0]
                if user_data.get('deleted') == 1:
                    response = {
                        "meta": self.meta,
                        "message": f"user with id {userid} does not exists",
                        "status": "failure",
                    }
                    FlaskLogger.log('delete',
                                    f'del_{self.account_type}_info',
                                    response,
                                    input_data=str(args_data),
                                    log_level='info')
                    return response, self.bad_code, self.headers

            updates = {"deleted": 1}
            queries = {"_id": ObjectId(userid)}
            collection = 'common_user_master'
            FlaskMongo.update(collection, updates, queries)

            response = {
                "meta": self.meta,
                "message": f"user with id {userid} deleted successfully",
                "status": "success"
            }
            FlaskLogger.log('delete',
                            f'del_{self.account_type}_info',
                            response,
                            input_data=str(args_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except ValidationError as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "errors": format_api_error(e.messages)
            }
            FlaskLogger.log('delete',
                            f'del_{self.account_type}_info',
                            response,
                            input_data=str(args_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('delete',
                            f'del_{self.account_type}_info',
                            response,
                            input_data=str(args_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 12
0
    def put(self, **kwargs):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()
            print(args_data)
            print(post_data)

            teacherusers_data.load(post_data, partial=True)
            user = args_data.get("user")

            columns = {"_id": 0}
            queries = {"_id": ObjectId(user)}
            collection = 'common_user_master'
            user_data = FlaskMongo.find(collection, columns, queries)

            if user_data == []:
                response = {
                    "meta": self.meta,
                    "message": f"user {user} does not exists",
                    "status": "failure",
                }
                FlaskLogger.log('put',
                                f'mod_{self.account_type}_info',
                                response,
                                input_data=str(args_data, post_data),
                                log_level='info')
                return response, self.bad_code, self.headers

            updates = post_data
            queries = {"_id": ObjectId(user)}
            collection = 'common_user_master'
            FlaskMongo.update(collection, updates, queries)

            response = {
                "meta": self.meta,
                "message": f"user {user} updated successfully",
                "status": "success"
            }
            FlaskLogger.log('put',
                            f'mod_{self.account_type}_info',
                            response,
                            input_data=str(args_data, post_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except ValidationError as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "errors": format_api_error(e.messages)
            }
            FlaskLogger.log('put',
                            f'mod_{self.account_type}_info',
                            response,
                            input_data=str(args_data, post_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('put',
                            f'mod_{self.account_type}_info',
                            response,
                            input_data=str(args_data, post_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 13
0
    def post(self):
        '''
		'''
        try:
            post_data = request.get_json()

            teacherusers_data.load(post_data)
            name = post_data.get("name")
            # mobile = post_data.get("mobile")
            print(post_data.keys())

            # Check for already exising entry:

            db = c_app.config.get('MONGO_DATABASE')
            collection = 'common_user_master'
            username = post_data.get("username")
            phone_no = post_data.get("phone_no")

            columns = {"_id": 0}
            queries = {"phone_no": phone_no}
            user_data = FlaskMongo.find(collection, columns, queries)

            print(post_data)

            if user_data != []:
                response = {
                    "meta": self.meta,
                    "message": f"user {username} is already registered",
                    "status": "failure",
                }
                FlaskLogger.log('post',
                                f'add_{self.account_type}_info',
                                response,
                                input_data=str(post_data),
                                log_level='info')
                return response, self.bad_code, self.headers

            post_data["account_type"] = self.account_type
            post_data["no_free_trial"] = 2
            post_data["is_active"] = True
            post_data["deleted"] = 0
            post_data["created"] = datetime.now().isoformat()
            FlaskMongo.insert(db, collection, post_data)

            response = {
                "meta": self.meta,
                "message": f"new user {name} added successfully",
                # "unique_id": post_data['unique_id'],
                "status": "success"
            }
            FlaskLogger.log('post',
                            f'add_{self.account_type}_info',
                            response,
                            input_data=str(post_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except ValidationError as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "errors": format_api_error(e.messages)
            }
            FlaskLogger.log('post',
                            f'add_{self.account_type}_info',
                            response,
                            input_data=str(post_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('post',
                            f'add_{self.account_type}_info',
                            response,
                            input_data=str(post_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 14
0
    def get(self, **kwargs):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            print(args_data)

            room_id = args_data.get("room_id", "all")
            teacher_id = args_data.get("teacher_id")
            pageno = int(args_data.get("pageno", 1))
            cols = args_data.get('cols')
            teacher_id = kwargs.get("_id")

            if room_id == "all":
                if pageno > 1:
                    skip = 10 * (pageno - 1)
                else:
                    skip = 0

                queries = {"deleted": 0, "teacher_id": teacher_id}
                columns = {"_id": 0, "deleted": 0}
                collection = 'common_room_master'
                query_data = FlaskMongo.find(collection, columns, queries)

                total_count = len(query_data)

                if cols:
                    columns = cols.split(',')
                    # print(f'\ncols: {cols}\n')
                    # print(f'\ncols: {dict((k, 0) for k in cols)}\n')
                    columns1 = {"_id": 0}
                    columns1.update(dict((k, 1) for k in columns))
                    queries1 = {"deleted": 0, "teacher_id": teacher_id}
                else:
                    queries1 = {"deleted": 0, "teacher_id": teacher_id}
                    columns1 = {"_id": 0, "deleted": 0}

                query_data1 = FlaskMongo.find(collection,
                                              columns1,
                                              queries1,
                                              skip=skip,
                                              limit=10)

                data = {}
                total_pages = math.ceil(total_count / (10))

                rooms_data = {
                    'total_count':
                    total_count,
                    'total':
                    total_pages,
                    'pageno':
                    pageno,
                    'previous':
                    pageno -
                    1 if pageno > 1 and pageno <= total_pages else None,
                    'next':
                    pageno + 1 if pageno < total_pages else None,
                    'data':
                    query_data1
                }

            else:
                queries = {
                    "deleted": 0,
                    "teacher_id": teacher_id,
                    "room_id": room_id
                }
                columns = {"_id": 0, "deleted": 0}
                collection = 'common_room_master'
                query_data = FlaskMongo.find(collection, columns, queries)
                if query_data:
                    query_data = query_data[0]
                else:
                    query_data = {}

                print(f'query_data: {query_data}')
                rooms_data = query_data

            response = {"meta": self.meta, "rooms_data": rooms_data}
            FlaskLogger.log('get',
                            'rooms_info',
                            response,
                            input_data=str(args_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('get',
                            'rooms_info',
                            response,
                            input_data=str(args_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 15
0
    def delete(self, **kwargs):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()
            print(args_data)
            # print(post_data)
            room_id = args_data.get("room_id")

            columns = {"_id": 0}
            queries = {"room_id": room_id, "deleted": 0}
            collection = "common_room_master"

            room_data = FlaskMongo.find(collection, columns, queries)
            print(f'room_data: {room_data}')

            if not room_data:
                response = {
                    "meta": self.meta,
                    "message": f"room with id {room_id} does not exists",
                    "status": "failure",
                }
                FlaskLogger.log('delete',
                                'del_rooms_info',
                                response,
                                input_data=str(args_data),
                                log_level='info')
                return response, self.bad_code, self.headers

            elif room_data:
                room_data = room_data[0]
                if room_data.get('deleted') == 1:
                    response = {
                        "meta": self.meta,
                        "message": f"room with id {room_id} does not exists",
                        "status": "failure",
                    }
                    FlaskLogger.log('delete',
                                    'del_rooms_info',
                                    response,
                                    input_data=str(args_data),
                                    log_level='info')
                    return response, self.bad_code, self.headers

            updates = {"deleted": 1}
            queries = {"room_id": room_id}
            collection = 'common_room_master'
            FlaskMongo.update(collection, updates, queries)

            response = {
                "meta": self.meta,
                "message": f"room with id {room_id} deleted successfully",
                "status": "success"
            }
            FlaskLogger.log('delete',
                            'del_rooms_info',
                            response,
                            input_data=str(args_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except Exception as e:
            # raise e
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('delete',
                            'del_rooms_info',
                            response,
                            input_data=str(args_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 16
0
    def put(self, **kwargs):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()
            print(args_data)
            print(post_data)
            room_id = args_data.get("roomid")

            rooms_data.load(post_data, partial=True)

            ######

            db = c_app.config.get('MONGO_DATABASE')
            collection = 'common_room_master'
            collection2 = 'common_user_master'
            teacher_id = args_data.get("teacherid")
            # room_name = post_data.get("room_name")

            columns = {"_id": 0}
            queries = {"teacher_id": teacher_id, "room_id": room_id}
            queries2 = {"_id": ObjectId(teacher_id)}
            room_data = FlaskMongo.find(collection, columns, queries)
            user_data = FlaskMongo.find(collection2, columns, queries2)

            print(post_data)
            print(f'room_data: {room_data}')

            if user_data == []:
                response = {
                    "meta": self.meta,
                    "message": f"teacher with id {teacher_id} does not exists",
                    "status": "failure",
                }
                FlaskLogger.log('put',
                                'mod_rooms_info',
                                response,
                                input_data=str({
                                    'ad': args_data,
                                    'pd': post_data
                                }),
                                log_level='info')
                return response, self.bad_code, self.headers

            if room_data == []:
                response = {
                    "meta": self.meta,
                    "message": f"room with id {room_id} does not exists",
                    "status": "failure",
                }
                FlaskLogger.log('put',
                                'mod_rooms_info',
                                response,
                                input_data=str({
                                    'ad': args_data,
                                    'pd': post_data
                                }),
                                log_level='info')
                return response, self.bad_code, self.headers

            ######

            updates = post_data
            queries = {"room_id": room_id}
            collection = 'common_room_master'
            FlaskMongo.update(collection, updates, queries)

            response = {
                "meta": self.meta,
                "message": f"room with id {room_id} updated successfully",
                "status": "success"
            }
            FlaskLogger.log('put',
                            'mod_rooms_info',
                            response,
                            input_data=str({
                                'ad': args_data,
                                'pd': post_data
                            }),
                            log_level='info')
            return response, self.success_code, self.headers

        except ValidationError as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "errors": format_api_error(e.messages)
            }
            FlaskLogger.log('put',
                            'mod_rooms_info',
                            response,
                            input_data=str({
                                'ad': args_data,
                                'pd': post_data
                            }),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('put',
                            'mod_rooms_info',
                            response,
                            input_data=str({
                                'ad': args_data,
                                'pd': post_data
                            }),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 17
0
    def post(self):
        '''
		'''
        try:
            post_data = request.get_json()

            users_data.load(post_data)
            name = post_data.get("name")
            mobile = post_data.get("mobile")
            print(post_data.keys())

            if not post_data:
                response = {
                    "meta": self.meta,
                    "message": "unable to process request",
                    "status": "failure",
                }
                return response, self.bad_code, self.headers

            # Check for already exising entry:

            db = c_app.config.get('MONGO_DATABASE')
            collection = 'common_user_master'
            username = post_data.get("username")
            phone_no = post_data.get("phone_no")

            columns = {"_id": 0}
            queries = {"phone_no": phone_no}
            user_data = FlaskMongo.find(collection, columns, **queries)

            print(post_data)

            if user_data != []:
                response = {
                    "meta": self.meta,
                    "message": f"user {username} is already registered",
                    "status": "failure",
                }
                return response, self.bad_code, self.headers

            post_data["no_free_trial"] = 2
            post_data["is_active"] = True
            post_data["deleted"] = 0
            post_data["created"] = datetime.now().isoformat()
            FlaskMongo.insert(db, collection, post_data)

            response = {
                "meta": self.meta,
                "message": f"new user {name} added successfully",
                # "unique_id": post_data['unique_id'],
                "status": "success"
            }
            return response, self.success_code, self.headers

        except ValidationError as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "errors": e.messages
            }
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            return response, self.exception_code, self.headers
Exemplo n.º 18
0
    def post(self):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()
            reset_trial_data.load(post_data)

            user_id = post_data.get("userid")
            collection = "common_user_master"
            queries = {"_id": ObjectId(user_id)}
            columns = {"_id": 0}

            user_data = FlaskMongo.find(collection, columns, queries)

            if not user_data:
                response = {
                    "meta": self.meta,
                    "message": f"user with id {user_id} does not exists",
                    "status": "failure"
                }
                # FlaskLogger.log('post', 'reset_trial', response, log_level='debug')
                FlaskLogger.log('post',
                                'reset_trial',
                                response,
                                log_level='info')
                # FlaskLogger.log('post', 'reset_trial', response, log_level='warning')
                # FlaskLogger.log('post', 'reset_trial', response, log_level='error')
                # FlaskLogger.log('post', 'reset_trial', response, log_level='critical')
                return response, self.bad_code, self.headers
            else:
                if args_data:
                    no_free_trial = int(args_data.get('no_free_trial'))
                else:
                    no_free_trial = 2

                updates = {"no_free_trial": no_free_trial}
                FlaskMongo.update(collection, updates, queries)

                response = {
                    "meta": self.meta,
                    "message":
                    f"trial for user with id {user_id} has been reset",
                    "status": "success"
                }
                FlaskLogger.log('post',
                                'reset_trial',
                                response,
                                log_level='info')
                return response, self.success_code, self.headers

        except ValidationError as e:
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": format_api_error(e.messages)
            }
            FlaskLogger.log('post', 'reset_trial', response, log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('post',
                            'reset_trial',
                            response,
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 19
0
    def put(self):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()
            post_data.update(args_data)

            testattempt_data.load(post_data, partial=True)

            # Check for already exising entry:

            db = c_app.config.get('MONGO_DATABASE')
            collection1 = 'common_test_student'
            collection2 = 'common_test_student_ques_answers'
            test_id = args_data.get("test_id")
            student_id = args_data.get("student_id")

            columns = {"_id": 0}
            queries = {
                "test_id": test_id,
                "student_id": student_id  #, "is_complete": True
            }
            test_data = FlaskMongo.find(collection1, columns, queries)

            if not test_data:
                response = {
                    "meta":
                    self.meta,
                    "message":
                    "unable to process request",
                    "status":
                    "failure",
                    "reason":
                    f"No test with id {test_id} found for student id {student_id}"
                }
                FlaskLogger.log('put',
                                'mod_test_complete_info',
                                response,
                                input_data=str(args_data, post_data),
                                log_level='info')
                return response, self.bad_code, self.headers
            else:
                updates1 = {'is_complete': post_data.get('is_complete')}
                queries1 = {"student_id": student_id, "test_id": test_id}
                FlaskMongo.update(collection1, updates1, queries1)

                response = {
                    "meta": self.meta,
                    "message":
                    f"Test with id {test_id} updated for student id {student_id}",
                    "status": "success"
                }
                FlaskLogger.log('put',
                                'mod_test_complete_info',
                                response,
                                input_data=str(args_data, post_data),
                                log_level='info')
                return response, self.success_code, self.headers

        except ValidationError as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "errors": format_api_error(e.messages)
            }
            FlaskLogger.log('put',
                            'mod_test_complete_info',
                            response,
                            input_data=str(args_data, post_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('put',
                            'mod_test_complete_info',
                            response,
                            input_data=str(args_data, post_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 20
0
def create_app(config_name):
    app = Flask(__name__,
                template_folder='../templates/',
                static_folder='../static')
    CORS(app)
    app.config.update(get_config(config_name))

    # App Binding:

    from bindings.flask_mongo import FlaskMongo
    from bindings.flask_logger import FlaskLogger

    mongo_app = FlaskMongo()
    mongo_app.init_app(app)

    log_app = FlaskLogger()
    log_app.init_app(app)

    api = Api(app, catch_all_404s=True)
    # api = Api()

    # print(app.config.keys())

    # Add API Routes:

    from routes.welcome import Welcome
    from routes.auth import Auth
    from routes.subscription import ResetTrial
    from routes.teacher import TeacherUsers
    from routes.student import StudentUsers
    from routes.admin import AdminUsers
    from routes.test import TestQuestionDetails, UnDeleteTest
    from routes.testattempt import TestAttemptDetails, TestAttemptComplete
    from routes.stat import TestScoresStats, StudentsStats
    from routes.rooms import RoomsApi
    from routes.rooms_enrolled import RoomsEnrolled

    from routes.stats.users import UsersStats
    from routes.stats.tests import TestsStats
    from routes.stats.rooms import RoomsStats
    from routes.stats.rooms_enrolled import RoomsEnrolledStats

    from routes.reports.creator import ReportsCreator
    from routes.mails.mailer import EmailsCreator

    api.add_resource(ReportsCreator,
                     '/edu/v1/utils/pdfs/create',
                     methods=['POST'],
                     endpoint='g_pdf')
    api.add_resource(EmailsCreator,
                     '/edu/v1/utils/mails/create',
                     methods=['POST'],
                     endpoint='g_mail')

    api.add_resource(UsersStats,
                     '/edu/v1/stats/users/get',
                     methods=['GET'],
                     endpoint='get_ustats')
    api.add_resource(TestsStats,
                     '/edu/v1/stats/tests/get',
                     methods=['GET'],
                     endpoint='get_tstats')
    api.add_resource(RoomsStats,
                     '/edu/v1/stats/rooms/get',
                     methods=['GET'],
                     endpoint='get_rstats')
    api.add_resource(RoomsEnrolledStats,
                     '/edu/v1/stats/rooms-enroll/get',
                     methods=['GET'],
                     endpoint='get_restats')

    api.add_resource(Welcome,
                     '/edu/v1/api/welcome',
                     methods=['GET'],
                     endpoint='welcome_api')

    api.add_resource(Auth,
                     '/edu/v1/api/login',
                     methods=['POST'],
                     endpoint='generate_token')

    api.add_resource(ResetTrial,
                     '/edu/v1/users/reset-trial',
                     methods=['POST'],
                     endpoint='reset_trial')

    api.add_resource(TeacherUsers,
                     '/edu/v1/users/teacher/get-user',
                     methods=['GET'],
                     endpoint='get_tuser')
    api.add_resource(TeacherUsers,
                     '/edu/v1/users/teacher/add-user',
                     methods=['POST'],
                     endpoint='add_tuser')
    api.add_resource(TeacherUsers,
                     '/edu/v1/users/teacher/mod-user',
                     methods=['PUT'],
                     endpoint='mod_tuser')
    api.add_resource(TeacherUsers,
                     '/edu/v1/users/teacher/del-user',
                     methods=['DELETE'],
                     endpoint='del_tuser')

    api.add_resource(StudentUsers,
                     '/edu/v1/users/student/get-user',
                     methods=['GET'],
                     endpoint='get_suser')
    api.add_resource(StudentUsers,
                     '/edu/v1/users/student/add-user',
                     methods=['POST'],
                     endpoint='add_suser')
    api.add_resource(StudentUsers,
                     '/edu/v1/users/student/mod-user',
                     methods=['PUT'],
                     endpoint='mod_suser')
    api.add_resource(StudentUsers,
                     '/edu/v1/users/student/del-user',
                     methods=['DELETE'],
                     endpoint='del_suser')

    api.add_resource(AdminUsers,
                     '/edu/v1/users/admin/get-user',
                     methods=['GET'],
                     endpoint='get_auser')
    api.add_resource(AdminUsers,
                     '/edu/v1/users/admin/add-user',
                     methods=['POST'],
                     endpoint='add_auser')
    api.add_resource(AdminUsers,
                     '/edu/v1/users/admin/mod-user',
                     methods=['PUT'],
                     endpoint='mod_auser')
    api.add_resource(AdminUsers,
                     '/edu/v1/users/admin/del-user',
                     methods=['DELETE'],
                     endpoint='del_auser')

    api.add_resource(TestQuestionDetails,
                     '/edu/v1/tests/get-test',
                     methods=['GET'],
                     endpoint='get_test')
    api.add_resource(TestQuestionDetails,
                     '/edu/v1/tests/create-test',
                     methods=['POST'],
                     endpoint='add_test')
    api.add_resource(TestQuestionDetails,
                     '/edu/v1/tests/mod-test',
                     methods=['PUT'],
                     endpoint='mod_test')
    api.add_resource(TestQuestionDetails,
                     '/edu/v1/tests/del-test',
                     methods=['DELETE'],
                     endpoint='del_test')

    api.add_resource(UnDeleteTest,
                     '/edu/v1/tests/undo-test-delete',
                     methods=['POST'],
                     endpoint='undo_test')

    api.add_resource(TestAttemptDetails,
                     '/edu/v1/testattempts/create-test',
                     methods=['POST'],
                     endpoint='create_testa')
    api.add_resource(TestAttemptDetails,
                     '/edu/v1/testattempts/mod-test',
                     methods=['PUT'],
                     endpoint='mod_testa')

    api.add_resource(TestAttemptComplete,
                     '/edu/v1/testcomplete/mod-test',
                     methods=['PUT'],
                     endpoint='mod_testc')

    api.add_resource(TestScoresStats,
                     '/edu/v1/teststats/get-test',
                     methods=['GET'],
                     endpoint='get_test_stats')
    api.add_resource(StudentsStats,
                     '/edu/v1/studentstats/get-test',
                     methods=['GET'],
                     endpoint='get_stu_stats')

    api.add_resource(RoomsApi,
                     '/edu/v1/rooms/create-room',
                     methods=['POST'],
                     endpoint='add_room')
    api.add_resource(RoomsApi,
                     '/edu/v1/rooms/get-room',
                     methods=['GET'],
                     endpoint='get_room')
    api.add_resource(RoomsApi,
                     '/edu/v1/rooms/mod-room',
                     methods=['PUT'],
                     endpoint='mod_room')
    api.add_resource(RoomsApi,
                     '/edu/v1/rooms/del-room',
                     methods=['DELETE'],
                     endpoint='del_room')

    api.add_resource(RoomsEnrolled,
                     '/edu/v1/rooms/create-room-enroll',
                     methods=['POST'],
                     endpoint='add_room_enroll')
    api.add_resource(RoomsEnrolled,
                     '/edu/v1/rooms/get-room-enroll',
                     methods=['GET'],
                     endpoint='get_room_enroll')
    api.add_resource(RoomsEnrolled,
                     '/edu/v1/rooms/mod-room-enroll',
                     methods=['PUT'],
                     endpoint='mod_room_enroll')
    api.add_resource(RoomsEnrolled,
                     '/edu/v1/rooms/del-room-enroll',
                     methods=['DELETE'],
                     endpoint='del_room_enroll')

    return app
Exemplo n.º 21
0
    def post(self, **kwargs):
        """
		"""
        try:
            args_data = request.args.to_dict()
            post_data = request.get_json()

            # print(post_data)
            print(f'kwargs: {kwargs}')

            testquestion_data.load(post_data)

            # Check for already exising entry:

            db = c_app.config.get('MONGO_DATABASE')
            collection1 = 'common_test_master'
            collection2 = 'common_question_master'
            collection3 = 'common_user_master'

            customer_id = post_data.get('customerid')
            room_name = post_data.get('room_name')

            columns = {"_id": 0, "deleted": 0}
            queries = {"_id": ObjectId(customer_id)}
            user_data = FlaskMongo.find(collection3, columns, queries)

            if not user_data:
                response = {
                    "meta": self.meta,
                    "message": f"user with id {customer_id} does not exists",
                    "status": "failure"
                }
                FlaskLogger.log('post',
                                'add_tests_info',
                                response,
                                input_data=str(post_data),
                                log_level='info')
                return response, self.bad_code, self.headers

            elif user_data[0].get("account_type") != 'teacher':
                response = {
                    "meta": self.meta,
                    "message":
                    f"user with id {customer_id} is not allowed to create tests",
                    "status": "failure"
                }
                FlaskLogger.log('post',
                                'add_tests_info',
                                response,
                                input_data=str(post_data),
                                log_level='info')
                return response, self.process_error_code, self.headers

            elif user_data[0].get("no_free_trial") < 1:
                response = {
                    "meta": self.meta,
                    "message":
                    f"user with id {customer_id} has 0 trials left. Please renew subscription.",
                    "status": "failure"
                }
                FlaskLogger.log('post',
                                'add_tests_info',
                                response,
                                input_data=str(post_data),
                                log_level='info')
                return response, self.process_error_code, self.headers

            else:
                testid = str(uuid.uuid1()).replace("-", "")
                teacher_id = kwargs.get("_id")

                data1 = {
                    "id":
                    testid,
                    "teacher_id":
                    teacher_id,
                    "room_name":
                    room_name,
                    "details":
                    post_data.get("details"),
                    "schedule":
                    post_data.get("schedule"),
                    "duration":
                    post_data.get("duration"),
                    "start_time":
                    post_data.get("start_time"),
                    "end_time":
                    post_data.get("end_time"),
                    "no_mandatory_questions":
                    post_data.get("no_mandatory_questions"),
                    "deleted":
                    0
                }
                FlaskMongo.insert(db, collection1, data1)

                for qna in post_data.get("qna"):
                    data2 = {
                        "customerid": post_data.get("customerid"),
                        "testid": testid,
                        "question": qna.get("question"),
                        "option1": qna.get("options")[0],
                        "option2": qna.get("options")[1],
                        "option3": qna.get("options")[2],
                        "option4": qna.get("options")[3],
                        "answer": qna.get("answer"),
                        "deleted": 0
                    }
                    FlaskMongo.insert(db, collection2, data2)

                no_free_trial = user_data[0].get("no_free_trial")
                if no_free_trial > 0:
                    no_free_trial = no_free_trial - 1

                    queries = {"_id": ObjectId(customer_id)}
                    updates = {"no_free_trial": no_free_trial}
                    FlaskMongo.update(collection3, updates, queries)

                response = {
                    "meta": self.meta,
                    "message":
                    f"new test with id {testid} created successfully",
                    "status": "success"
                }
                FlaskLogger.log('post',
                                'add_tests_info',
                                response,
                                input_data=str(post_data),
                                log_level='info')
                return response, self.success_code, self.headers

        except ValidationError as e:
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": format_api_error(e.messages)
            }
            FlaskLogger.log('post',
                            'add_tests_info',
                            response,
                            input_data=str(post_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            # print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('post',
                            'add_tests_info',
                            response,
                            input_data=str(post_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 22
0
    def get(self):
        '''
        '''
        try:
            args_data = request.args.to_dict()

            print(args_data)

            student_id = args_data.get('studentid')

            collection1 = 'common_test_student'
            # collection2 = 'common_test_master'

            columns = {'_id': 0, "test_id": 1, "is_complete": 1}
            queries1 = {'student_id': student_id}
            query_data1 = FlaskMongo.find(collection1, columns, queries1)

            # queries2 = {'id': student_id}
            # query_data2 = FlaskMongo.find(collection2, columns, queries2)

            if query_data1:
                # query_data1 = query_data1[0]
                print(f'query_data1: {query_data1}')

                # query_data1 = query_data1[0]
                # print(query_data1)

                stats = {
                    'total': len(query_data1),
                    'complete': 0,
                    'incomplete': 0,
                    'test-ids': []
                }

                for qd in query_data1:
                    if qd.get('is_complete'):
                        stats['complete'] = stats['complete'] + 1
                    stats['test-ids'].append(qd.get('test_id'))

                stats['incomplete'] = stats['total'] - stats['complete']

                response = {
                    "meta": self.meta,
                    # "message": f"no data found for test id {student_id}",
                    "status": "success",
                    "stats": stats
                }
                return response, self.success_code, self.headers

            else:
                response = {
                    "meta": self.meta,
                    "message":
                    f"no data found for student with id {student_id}",
                    "status": "failure"
                }
                return response, self.no_data_code, self.headers

        except Exception as e:
            # raise e
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            return response, self.exception_code, self.headers
Exemplo n.º 23
0
    def get(self, **kwargs):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            print(args_data)

            testid = args_data.get("testid", "all")
            pageno = int(args_data.get("pageno", 1))
            room_name = args_data.get('room_name')
            cols = args_data.get('cols')
            teacher_id = kwargs.get("_id")

            collection1 = 'common_test_master'
            collection2 = 'common_question_master'

            if testid == "all":
                if pageno > 1:
                    skip = 10 * (pageno - 1)
                else:
                    skip = 0

                columns1 = {"_id": 0}
                queries1 = {"deleted": 0}
                query_data1 = FlaskMongo.find(collection1, columns1, queries1)

                total_count = len(query_data1)
                print(f'total_count: {total_count}\n')

                if cols:
                    columns = cols.split(',')
                    # print(f'\ncols: {cols}\n')
                    # print(f'\ncols: {dict((k, 0) for k in cols)}\n')
                    columns1 = {"_id": 0, "room_name": room_name}
                    columns1.update(dict((k, 1) for k in columns))
                    queries1 = {"deleted": 0, "teacher_id": teacher_id}
                else:
                    columns = []
                    columns1 = {"_id": 0, "room_name": room_name}
                    queries1 = {"deleted": 0, "teacher_id": teacher_id}

                query_data2 = FlaskMongo.find(collection1,
                                              columns1,
                                              queries1,
                                              skip=skip,
                                              limit=10)

                data = {}

                print(f'query_data2: {query_data2}\n')

                if cols:
                    if len(columns) == 1:
                        select_column = columns[0]
                        print(f'select_column: {select_column}')
                        data = [d[select_column] for d in query_data2]
                    else:
                        data = query_data2
                else:
                    for idx, qd1 in enumerate(query_data2):
                        columns3 = {"_id": 0}
                        queries3 = {"testid": qd1.get("id")}
                        query_data3 = FlaskMongo.find(collection2, columns3,
                                                      queries3)
                        # print(f'query_data3: {query_data3}\n')
                        # print(f'type: {type(query_data3)}\n')

                        details = []

                        for qd3 in query_data3:
                            qd1.update(qd3)
                            details.append(qd1)
                        data[idx] = details

                total_pages = math.ceil(total_count / (10))

                test_data = {
                    'total_count':
                    total_count,
                    'total':
                    total_pages,
                    'pageno':
                    pageno,
                    'previous':
                    pageno -
                    1 if pageno > 1 and pageno <= total_pages else None,
                    'next':
                    pageno + 1 if pageno < total_pages else None,
                    'data':
                    data
                }

            else:
                queries1 = {"id": testid}
                columns1 = {"_id": 0}
                queries2 = {"testid": testid, "deleted": 0}
                columns2 = {"customerid": 0, "testid": 0}
                query_data1 = FlaskMongo.find(collection1, columns1, queries1)
                query_data2 = FlaskMongo.find(collection2, columns2, queries2)

                print(f'query_data1: {query_data1}\n')
                print(f'query_data2: {query_data2}\n')

                if query_data1 and query_data2:
                    query_data1 = query_data1[0]
                    query_data1['test_id'] = query_data1.pop('id')
                    query_data1['qna'] = query_data2
                    test_data = query_data1

                else:
                    test_data = {}

            response = {"meta": self.meta, "test_data": test_data}
            FlaskLogger.log('get',
                            'tests_info',
                            response,
                            input_data=str(args_data),
                            log_level='info')
            return response, self.success_code, self.headers

        except Exception as e:
            raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('get',
                            'tests_info',
                            response,
                            input_data=str(args_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 24
0
    def get(self):
        '''
        '''
        try:
            args_data = request.args.to_dict()
            test_id = args_data.get('testid')

            collection1 = 'common_test_student_ques_answers'
            collection2 = 'common_test_master'

            columns = {'_id': 0}
            queries1 = {'test_id': test_id}
            query_data1 = FlaskMongo.find(collection1, columns, queries1)

            queries2 = {'id': test_id}
            query_data2 = FlaskMongo.find(collection2, columns, queries2)

            if query_data1 and query_data2:
                query_data2 = query_data2[0]
                print(query_data2)

                # query_data1 = query_data1[0]
                # print(query_data1)

                stats = {
                    'total': query_data2.get('no_mandatory_questions'),
                    'correct': 0,
                    'incorrect': 0,
                    'score': 0
                }

                for qd in query_data1:
                    if qd.get('is_correct'):
                        stats['correct'] = stats['correct'] + 1
                stats['incorrect'] = stats['total'] - stats['correct']
                stats['score'] = str(
                    round(stats['correct'] / stats['total'] * 100, 2)) + '%'

                response = {
                    "meta": self.meta,
                    # "message": f"no data found for test id {test_id}",
                    "status": "success",
                    "stats": stats
                }
                return response, self.success_code, self.headers

            else:
                response = {
                    "meta": self.meta,
                    "message": f"no data found for test id {test_id}",
                    "status": "failure"
                }
                return response, self.no_data_code, self.headers

        except Exception as e:
            # raise e
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            return response, self.exception_code, self.headers
Exemplo n.º 25
0
    def post(self):
        """
		"""
        try:
            post_data = request.get_json()

            # print(post_data)

            testdeletion_data.load(post_data)

            # Check for already exising entry:

            collection1 = 'common_test_master'
            collection2 = 'common_question_master'

            test_id = post_data.get('test_id')
            columns1 = {"_id": 0, "deleted": 0}
            queries1 = {"id": test_id}
            test_data = FlaskMongo.find(collection1, columns1, queries1)

            if not test_data:
                response = {
                    "meta": self.meta,
                    "message": f"test with id {test_id} does not exists",
                    "status": "failure"
                }
                FlaskLogger.log('delete',
                                'undo_del_tests',
                                response,
                                input_data=str(args_data),
                                log_level='info')
                return response, self.bad_code, self.headers
            else:
                queries1 = {"id": test_id}
                updates1 = {"deleted": 0}
                FlaskMongo.update(collection1, updates1, queries1)

                collection2 = 'common_question_master'
                updates2 = {"deleted": 0}
                queries2 = {"testid": test_id}
                FlaskMongo.update(collection2, updates2, queries2)

                response = {
                    "meta": self.meta,
                    "message":
                    f"test with id {test_id} undeleted successfully",
                    "status": "success"
                }
                FlaskLogger.log('delete',
                                'undo_del_tests',
                                response,
                                input_data=str(args_data),
                                log_level='info')
                return response, self.success_code, self.headers

        except ValidationError as e:
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": format_api_error(e.messages)
            }
            FlaskLogger.log('delete',
                            'undo_del_tests',
                            response,
                            input_data=str(args_data),
                            log_level='error')
            return response, self.bad_code, self.headers

        except Exception as e:
            # raise e
            print(e)
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            FlaskLogger.log('delete',
                            'undo_del_tests',
                            response,
                            input_data=str(args_data),
                            log_level='warning')
            return response, self.exception_code, self.headers
Exemplo n.º 26
0
    def get(self):
        '''
		'''
        try:
            args_data = request.args.to_dict()
            test_id = args_data.get('testid')

            db = c_app.config.get('MONGO_DATABASE')
            collection1 = 'common_room_enroll_master'

            columns = {'_id': 0}
            queries = {}
            aggregate_pipeline = [{
                '$group': {
                    '_id': '$room_id',
                    'count': {
                        '$sum': 1
                    }
                }
            }]
            room_counts = FlaskMongo.find(collection1,
                                          columns,
                                          queries,
                                          aggregate=aggregate_pipeline)

            # columns = {'_id': 0}
            # queries = {}
            # distinct_column = 'institute_name'
            # institute_names = FlaskMongo.find(
            # 	collection1, columns, queries, distinct=True, distinct_column=distinct_column
            # )

            total_rooms_enroll = db[collection1].find({}).count()
            deleted_rooms_enroll = db[collection1].find({"deleted": 1}).count()
            banned_rooms_enroll = db[collection1].find({
                "banned": True
            }).count()
            rooms_enroll = {
                'total': total_rooms_enroll,
                'deleted': deleted_rooms_enroll,
                'active': total_rooms_enroll - deleted_rooms_enroll,
                'banned': banned_rooms_enroll,
                'unbanned': total_rooms_enroll - banned_rooms_enroll
            }

            columns = {'room_id': 1}
            queries = {}
            rooms_ids = FlaskMongo.find(collection1, columns, queries)
            rooms_ids = [rid.get('_id') for rid in rooms_ids]

            columns = {'_id': 0, 'room_id': 1, 'limit': 1}
            queries = {}
            rooms_limits = FlaskMongo.find(collection1, columns, queries)
            rooms_limits = [rid for rid in rooms_limits]

            columns = {'_id': 0, 'room_id': 1, 'limit': 1}
            queries = {}
            rooms_enroll_counts = FlaskMongo.find(collection1, columns,
                                                  queries)

            columns = {'_id': 0, 'room_id': 1, 'student_id': 1, 'created': 1}
            queries = {}
            rooms_enrollments = FlaskMongo.find(collection1, columns, queries)

            stats = {
                # 'rooms_ids': rooms_ids,
                'rooms_enroll': rooms_enroll,
                'rooms_enrollments': rooms_enrollments,
                # 'rooms_limits': rooms_limits
                # 'institute_names': institute_names
            }

            response = {"meta": self.meta, "status": "success", "stats": stats}
            return response, self.success_code, self.headers

        except Exception as e:
            # raise e
            response = {
                "meta": self.meta,
                "message": "unable to process request",
                "status": "failure",
                "reason": str(e)
            }
            return response, self.exception_code, self.headers