def create_app(dbInfo, config_filepath ="resource/config.cfg"): #app.config.from_object(__name__) #app.config.from_envvar('GRADE_SETTINGS', silent=True) # 기본 설정은 GradeServer_Config 객체에 정의되있고 운영 환경 또는 기본 설정을 변경을 하려면 # 실행 환경변수인 GradeServer_SETTINGS에 변경할 설정을 담고 있는 파일 경로를 설정 from GradeServer.GradeServer_config import GradeServerConfig app.config.from_object(GradeServerConfig) app.config.from_pyfile(config_filepath, silent=True) # Triple DES from GradeServer.GradeServer_py3des import TripleDES TripleDES.init() # Log from GradeServer.GradeServer_logger import Log Log.init() # SessionInterface 설정. from GradeServer.cache_session import RedisCacheSessionInterface app.session_interface = RedisCacheSessionInterface() # 데이터베이스 처리 from GradeServer.database import DBManager DBManager.init(app.config['DB_URL'].format(dbInfo[1], # DB root name dbInfo[2])) # DB Pasword DBManager.init_db() # 뷰 함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록전에 # 뷰 함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음 from GradeServer.controller import * from GradeServer.GradeServer_blueprint import GradeServer app.register_blueprint(GradeServer) return app
def close_db_session(exception = None): """요청이 완료된 후에 db연결에 사용된 세션을 종료함""" try: dao.remove() except Exception as e: from GradeServer.GradeServer_logger import Log Log.error(str(e))
def id_check(select, error = None): if request.method == 'POST': # 암호를 입력 안했을 때 if not request.form['password']: error ='Password' + get_message('fillData') else: try: memberId = session[SessionResources().const.MEMBER_ID] password = request.form['password'] check = select_match_member(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = memberId)).first() # 암호가 일치 할 때 #Checking Success if check_password_hash (check.password, TripleDES.encrypt(str(password))): # for all user if select == 'account': return redirect(url_for(RouteResources().const.EDIT_PERSONAL)) # server manager elif SETResources().const.SERVER_ADMINISTRATOR in session[SessionResources().const.AUTHORITY][0]: if select == 'server_manage_collegedepartment': return redirect(url_for('.server_manage_collegedepartment', collegePageNum = int(1), departmentPageNum = int(1))) elif select == 'server_manage_class': return redirect(url_for('.server_manage_class', pageNum = int(1))) elif select == 'server_manage_problem': return redirect(url_for('.server_manage_problem', activeTabId = OtherResources().const.ALL, pageNum = int(1))) elif select == 'server_manage_user': return redirect(url_for('.server_manage_user', activeTabId = OtherResources().const.ALL, pageNum = int(1))) elif select == 'server_manage_service': return redirect(url_for('.server_manage_service')) # class manager elif SETResources().const.COURSE_ADMINISTRATOR in session[SessionResources().const.AUTHORITY][0]: if select == 'user_submit': return redirect(url_for('.class_user_submit')) elif select == 'cm_manage_problem': return redirect(url_for('.class_manage_problem')) elif select == 'cm_manage_user': return redirect(url_for('.class_manage_user')) elif select == 'cm_manage_service': return redirect(url_for('.class_manage_service')) else: return unknown_error() # 암호가 일치 하지 않을 때 else: error = get_message('wrongPassword') except Exception as e: Log.error(str(e)) raise e return render_template(HTMLResources().const.ID_CHECK_HTML, error = error)
def download_file(): try: # Absolute Path directory = '/mnt/shared/Past/' # File Name StudentId_MemberName.zip filename = session[SessionResources().const.MEMBER_ID] + '_'\ + session[SessionResources().const.MEMBER_NAME] + '.zip' Log.info(session[SessionResources().const.MEMBER_ID] \ + ' download '\ + directory\ + '/' + filename) return send_from_directory(directory = directory, filename = filename) except Exception: pass
def download_file(): try: # Absolute Path directory = '/mnt/shared/Past/' # File Name StudentId_MemberName.zip filename = session[SessionResources().const.MEMBER_ID] + '_'\ + session[SessionResources().const.MEMBER_NAME] + '.zip' Log.info(session[SessionResources().const.MEMBER_ID] \ + ' download '\ + directory\ + '/' + filename) return send_from_directory(directory=directory, filename=filename) except Exception: pass
def to_process_written_code(pageNum, problemIndex): memberId = session[SessionResources().const.MEMBER_ID] memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX] problemName = remove_space_in_problemName(problemIndex) filePath, tempPath = make_path(PATH, memberIdIndex, memberId, problemName) try: os.mkdir(tempPath) usedLanguageName, usedLanguageVersion, fileName = write_code_in_file(tempPath) fileSize = os.stat(os.path.join(tempPath, fileName)).st_size fileIndex = 1 submissionIndex = get_submission_index(memberIdIndex, problemIndex) delete_submitted_files_data(submissionIndex) insert_submitted_files(submissionIndex, fileIndex, fileName, filePath, fileSize) send_to_celery(memberIdIndex, problemIndex, submissionIndex, usedLanguageName, usedLanguageVersion, fileSize, problemName, filePath, tempPath) Log.info(OtherResources().const.WRITED_CODE_SUBMITTED) except OSError as e: Log.error(str(e)) submit_error(tempPath, pageNum, OtherResources().const.FILE_ERROR) except Exception as e: dao.rollback() Log.error(str(e)) print e submit_error(tempPath, pageNum, OtherResources().const.DB_ERROR) time.sleep(0.4) return page_move(pageNum)
def to_process_written_code(pageNum, problemIndex): memberId = session[SessionResources().const.MEMBER_ID] memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX] problemName = remove_space_in_problemName(problemIndex) filePath, tempPath = make_path(PATH, memberIdIndex, memberId, problemName) try: os.mkdir(tempPath) usedLanguageName, usedLanguageVersion, fileName = write_code_in_file( tempPath) fileSize = os.stat(os.path.join(tempPath, fileName)).st_size fileIndex = 1 submissionIndex = get_submission_index(memberIdIndex, problemIndex) delete_submitted_files_data(submissionIndex) insert_submitted_files(submissionIndex, fileIndex, fileName, filePath, fileSize) send_to_celery(memberIdIndex, problemIndex, submissionIndex, usedLanguageName, usedLanguageVersion, fileSize, problemName, filePath, tempPath) Log.info(OtherResources().const.WRITED_CODE_SUBMITTED) except OSError as e: Log.error(str(e)) submit_error(tempPath, pageNum, OtherResources().const.FILE_ERROR) except Exception as e: dao.rollback() Log.error(str(e)) print e submit_error(tempPath, pageNum, OtherResources().const.DB_ERROR) time.sleep(0.4) return page_move(pageNum)
def to_process_uploaded_files(problemIndex, pageNum, browserName, browserVersion): memberId = session[SessionResources().const.MEMBER_ID] memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX] problemName = remove_space_in_problemName(problemIndex) filePath, tempPath = make_path(PATH, memberIdIndex, memberId, problemName) try: os.mkdir(tempPath) uploadFiles = request.files.getlist(OtherResources().const.GET_FILES) usedLanguageName = request.form[OtherResources().const.USED_LANGUAGE_NAME] usedLanguageVersion = request.form[OtherResources().const.USED_LANGUAGE_VERSION] submissionIndex = get_submission_index(memberIdIndex, problemIndex) sumOfSubmittedFileSize = file_save(submissionIndex, uploadFiles, tempPath, filePath) send_to_celery(memberIdIndex, problemIndex, submissionIndex, usedLanguageName, usedLanguageVersion, sumOfSubmittedFileSize, problemName, filePath, tempPath) Log.info(OtherResources().const.FILE_SUBMITTED) except OSError as e: Log.error(str(e)) submit_error(tempPath, pageNum, OtherResources().const.FILE_ERROR, browserName, browserVersion) except Exception as e: dao.rollback() Log.error(str(e)) print e submit_error(tempPath, pageNum, OtherResources().const.DB_ERROR, browserName, browserVersion) time.sleep(0.4) return page_move(pageNum, browserName, browserVersion)
def download_file(courseId, courseName): try: # Absolute Path directory = '/mnt/shared/PastCourses/' + str(courseId) + '_' + courseName # File Name StudentId_MemberName.zip filename = session[SessionResources().const.MEMBER_ID] + '_'\ + session[SessionResources().const.MEMBER_NAME] + '.zip' Log.info(session[SessionResources().const.MEMBER_ID] \ + ' download '\ + directory\ + '/' + filename) return send_from_directory(directory = directory, filename = filename) except Exception as e: Log.info(str(e)) # 메인 페이지로 옮기기 from flask import redirect, url_for, flash from GradeServer.resource.routeResources import RouteResources flash('Not Found File') return redirect(url_for(RouteResources().const.SIGN_IN))
def create_app(dbInfo, config_filepath="resource/config.cfg"): #app.config.from_object(__name__) #app.config.from_envvar('GRADE_SETTINGS', silent=True) # 기본 설정은 GradeServer_Config 객체에 정의되있고 운영 환경 또는 기본 설정을 변경을 하려면 # 실행 환경변수인 GradeServer_SETTINGS에 변경할 설정을 담고 있는 파일 경로를 설정 from GradeServer.GradeServer_config import GradeServerConfig app.config.from_object(GradeServerConfig) app.config.from_pyfile(config_filepath, silent=True) # Triple DES from GradeServer.GradeServer_py3des import TripleDES TripleDES.init() # Log from GradeServer.GradeServer_logger import Log Log.init() # SessionInterface 설정. from GradeServer.cache_session import RedisCacheSessionInterface app.session_interface = RedisCacheSessionInterface() # 데이터베이스 처리 from GradeServer.database import DBManager DBManager.init(app.config['DB_URL'].format( dbInfo[1], # DB root name dbInfo[2])) # DB Pasword DBManager.init_db() # 뷰 함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록전에 # 뷰 함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음 from GradeServer.controller import * from GradeServer.GradeServer_blueprint import GradeServer app.register_blueprint(GradeServer) return app
def to_process_uploaded_files(courseId, problemId, pageNum, browserName, browserVersion): memberId = session[SessionResources.const.MEMBER_ID] problemName = remove_space_in_problemName(problemId) filePath, tempPath = make_path(PATH, memberId, courseId, problemId, problemName) try: os.mkdir(tempPath) uploadFiles = request.files.getlist(OtherResources.const.GET_FILES) usedLanguageName = request.form[OtherResources.const.USED_LANGUAGE_NAME] sumOfSubmittedFileSize = file_save(memberId, courseId, problemId, uploadFiles, tempPath, filePath) send_to_celery(memberId, courseId, problemId, usedLanguageName, sumOfSubmittedFileSize, problemName, filePath, tempPath) Log.info("file submitted") except OSError as e: Log.error(str(e)) submit_error(tempPath, courseId, pageNum, 'fileError', browserName, browserVersion) except Exception as e: dao.rollback() Log.error(str(e)) submit_error(tempPath, courseId, pageNum, 'dbError', browserName, browserVersion) time.sleep(0.4) return page_move(courseId, pageNum, browserName, browserVersion)
def to_process_uploaded_files(problemIndex, pageNum, browserName, browserVersion): memberId = session[SessionResources().const.MEMBER_ID] memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX] problemName = remove_space_in_problemName(problemIndex) filePath, tempPath = make_path(PATH, memberIdIndex, memberId, problemName) try: os.mkdir(tempPath) uploadFiles = request.files.getlist(OtherResources().const.GET_FILES) usedLanguageName = request.form[ OtherResources().const.USED_LANGUAGE_NAME] usedLanguageVersion = request.form[ OtherResources().const.USED_LANGUAGE_VERSION] submissionIndex = get_submission_index(memberIdIndex, problemIndex) sumOfSubmittedFileSize = file_save(submissionIndex, uploadFiles, tempPath, filePath) send_to_celery(memberIdIndex, problemIndex, submissionIndex, usedLanguageName, usedLanguageVersion, sumOfSubmittedFileSize, problemName, filePath, tempPath) Log.info(OtherResources().const.FILE_SUBMITTED) except OSError as e: Log.error(str(e)) submit_error(tempPath, pageNum, OtherResources().const.FILE_ERROR, browserName, browserVersion) except Exception as e: dao.rollback() Log.error(str(e)) print e submit_error(tempPath, pageNum, OtherResources().const.DB_ERROR, browserName, browserVersion) time.sleep(0.4) return page_move(pageNum, browserName, browserVersion)
def to_process_written_code(courseId, pageNum, problemId): memberId = session[SessionResources.const.MEMBER_ID] problemName = remove_space_in_problemName(problemId) filePath, tempPath = make_path(PATH, memberId, courseId, problemId, problemName) try: os.mkdir(tempPath) usedLanguageName, fileName = write_code_in_file(tempPath) fileSize = os.stat(os.path.join(tempPath, fileName)).st_size fileIndex = 1 delete_submitted_files_data(memberId, problemId, courseId) insert_submitted_files(memberId, courseId, problemId, fileIndex, fileName, filePath, fileSize) send_to_celery(memberId, courseId, problemId, usedLanguageName, fileSize, problemName, filePath, tempPath) Log.info("writed code is submitted") except OSError as e: Log.error(str(e)) submit_error(tempPath, courseId, pageNum, 'fileError') except Exception as e: dao.rollback() Log.error(str(e)) submit_error(tempPath, courseId, pageNum, 'dbError') time.sleep(0.4) return page_move(courseId, pageNum)
def close_db_session(exception = None): """요청이 완료된 후에 db연결에 사용된 세션을 종료함""" try: dao.remove() except Exception as e: Log.error(str(e))
def board(activeTabCourseId, pageNum): try: # 검색시 FilterCondition List Filters = ['모두', '작성자', '제목 및 내용'] # 허용 과목 리스트 myCourses = select_current_courses(select_accept_courses().subquery()).subquery() # TabActive Course or All Articles # get course or All Articles articlesOnBoard = join_courses_names(# get TabActive Articles select_articles(activeTabCourseId = activeTabCourseId, isDeleted = ENUMResources().const.FALSE).subquery(), myCourses).subquery() # 과목 공지글 try: articleNoticeRecords = get_page_record((select_sorted_articles(articlesOnBoard, isNotice = ENUMResources().const.TRUE)), pageNum = int(1), LIST = OtherResources().const.NOTICE_LIST).all() except Exception: articleNoticeRecords = [] # 과목 게시글 try: if request.method == 'POST': Log.info(session[SessionResources().const.MEMBER_ID] + ' try keyword find in Board') try: for form in request.form: # FilterCondition if 'keyWord' != form: filterCondition = form keyWord = request.form['keyWord'] except Exception as e: filterCondition = None keyWord = None Log.info(session[SessionResources().const.MEMBER_ID] + e) else: filterCondition = None keyWord = None articlesOnBoardSub = select_sorted_articles(articlesOnBoard, isNotice = ENUMResources().const.FALSE, filterFindParameter = FilterFindParameter(filterCondition, keyWord)) count = select_count(articlesOnBoardSub.subquery().\ c.articleIndex).first().\ count articleRecords = get_page_record(articlesOnBoardSub, pageNum = pageNum, LIST = int(15)).all() except Exception: count = 0 articleRecords = [] try: myCourses = dao.query(myCourses).all() except Exception: myCourses = [] # myCourses Default Add ALL myCourses.insert(0, OtherResources().const.ALL) return render_template(HTMLResources().const.BOARD_HTML, articleRecords = articleRecords, articleNoticeRecords = articleNoticeRecords, myCourses = myCourses, pages = get_page_pointed(pageNum, count, int(15)), Filters = Filters, activeTabCourseId = activeTabCourseId) # classType, condition은 검색 할 때 필요한 변수 except Exception: return unknown_error()
def access_authority_check(problemLevel = None, memberIdIndex = None, submissionIndex = None, problemIndex = None, submissionReplyIndex = None, articleIndex = None, boardReplyIndex = None, isAdministrator = None, isWrite = None, isCode = None): try: # Zero Index Check if memberIdIndex == 0\ or problemIndex == 0\ or submissionReplyIndex == 0\ or (articleIndex == 0 and not isWrite)\ or boardReplyIndex == 0: return False # Get Authority type Turple authority = is_authority(session[SessionResources().const.AUTHORITY]) # Get my Index thisMemberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX] # Authority check authority is turple, size 3 if isAdministrator and authority[0]: if problemLevel\ and problemLevel not in (LanguageResources().const.GoldLevel[1], LanguageResources().const.SilverLevel[1], LanguageResources().const.BronzeLevel[1]): return False return True elif isAdministrator and not authority[0]: return False else: # Division Index if submissionIndex: submissionIndex = select_data_of_submission_board(submissionIndex).first() memberIdIndex = submissionIndex.memberIdIndex problemIndex = submissionIndex.problemIndex # MemberIdIndex Check if memberIdIndex\ and not select_member(memberIdIndex).first(): return False if problemIndex\ and not course_problem_check(isAdministrator, authority, memberIdIndex, problemIndex, thisMemberIdIndex, isCode): return False # Submission Reply Index check if submissionReplyIndex: replySubmissionIndex = select_replies_on_code(submissionIndex = None, submissionReplyIndex = submissionReplyIndex).first() replySubmissionIndex = select_data_of_submission_board(replySubmissionIndex.submissionIndex).first() if not course_problem_check(isAdministrator, authority, replySubmissionIndex.memberIdIndex, replySubmissionIndex.problemIndex, thisMemberIdIndex, isCode): return False # Board Check if articleIndex: article = select_article(articleIndex).first() if isWrite\ and article.writerIdIndex != thisMemberIdIndex: return False # All Pass Authority return True except Exception as e: Log.error(str(e)) return False
def close_db_session(exception=None): '''요청이 완료된 후에 db연결에 사용된 세션을 종료함''' try: dao.remove() except Exception as e: Log.error(str(e))
def access_authority_check(problemLevel=None, memberIdIndex=None, submissionIndex=None, problemIndex=None, submissionReplyIndex=None, articleIndex=None, boardReplyIndex=None, isAdministrator=None, isWrite=None, isCode=None): try: # Zero Index Check if memberIdIndex == 0\ or problemIndex == 0\ or submissionReplyIndex == 0\ or (articleIndex == 0 and not isWrite)\ or boardReplyIndex == 0: return False # Get Authority type Turple authority = is_authority(session[SessionResources().const.AUTHORITY]) # Get my Index thisMemberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX] # Authority check authority is turple, size 3 if isAdministrator and authority[0]: if problemLevel\ and problemLevel not in (LanguageResources().const.GoldLevel[1], LanguageResources().const.SilverLevel[1], LanguageResources().const.BronzeLevel[1]): return False return True elif isAdministrator and not authority[0]: return False else: # Division Index if submissionIndex: submissionIndex = select_data_of_submission_board( submissionIndex).first() memberIdIndex = submissionIndex.memberIdIndex problemIndex = submissionIndex.problemIndex # MemberIdIndex Check if memberIdIndex\ and not select_member(memberIdIndex).first(): return False if problemIndex\ and not course_problem_check(isAdministrator, authority, memberIdIndex, problemIndex, thisMemberIdIndex, isCode): return False # Submission Reply Index check if submissionReplyIndex: replySubmissionIndex = select_replies_on_code( submissionIndex=None, submissionReplyIndex=submissionReplyIndex).first() replySubmissionIndex = select_data_of_submission_board( replySubmissionIndex.submissionIndex).first() if not course_problem_check(isAdministrator, authority, replySubmissionIndex.memberIdIndex, replySubmissionIndex.problemIndex, thisMemberIdIndex, isCode): return False # Board Check if articleIndex: article = select_article(articleIndex).first() if isWrite\ and article.writerIdIndex != thisMemberIdIndex: return False # All Pass Authority return True except Exception as e: Log.error(str(e)) return False