def post(self): ''' ''' try: post_data = request.get_json() email_schema.load(post_data) receiver_email_id = post_data.get('receiver_email_id') email_message = post_data.get('email_message') mailer = Gmailer() background_task = Thread(target=mailer.send_mail, args=(receiver_email_id, email_message)) background_task.daemon = True background_task.start() response = { 'meta': self.meta, 'status': 'success', 'message': f'sending email successfully' } return response, self.processing_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', 'create_email', 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', 'create_email', response, input_data=str(post_data), log_level='warning') return response, self.exception_code, self.headers
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
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
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
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
def post(self): ''' ''' try: post_data = request.get_json() pdf_schema.load(post_data, partial=True) file_name = post_data.get('file_name') url = post_data.get('url') file_path = post_data.get('file_path') string = post_data.get('string') pdf_generator = PdfGenerator(file_name) if url: source = 'url' # pdf_generator.parse_url(url) background_task = Thread(target=pdf_generator.parse_url, args=(url, )) background_task.daemon = True background_task.start() if file_path: source = 'file_path' # pdf_generator.parse_file(file_path) background_task = Thread(target=pdf_generator.parse_file, args=(file_path, )) background_task.daemon = True background_task.start() if string: source = 'string' # pdf_generator.parse_string(string) background_task = Thread(target=pdf_generator.parse_file, args=(string, )) background_task.daemon = True background_task.start() response = { 'meta': self.meta, 'status': 'success', 'message': f'pdf generating from {source} successfully' } return response, self.processing_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', 'create_pdf', 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', 'create_pdf', response, input_data=str(post_data), log_level='warning') return response, self.exception_code, self.headers
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
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
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
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
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
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
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
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
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
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
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
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