def get_current_user(): if request.method == 'POST': try: user_token = request.form['token'] if user_token is not None: data = {} cn.g.db = cn.connect_db() cur = cn.g.db.execute('select id, username, carrera, turno, ciclo, seccion, nombre from usuario where token='+str(user_token)) usuario = [dict(id=row[0], username=row[1], carrera=row[2], turno=row[3], ciclo=row[4], seccion=row[5], nombre=row[6])for row in cur.fetchall()] for user in usuario: data.update({ 'id':user.get('id'), 'username':user.get('nombre'), 'carrera':rs.get_carrera(user.get('carrera')), 'turno':rs.get_turno(user.get('turno')), 'ciclo':user.get('ciclo'), 'seccion':user.get('seccion'), 'nombre':user.get('nombre') }) cn.g.db.close() return json.dumps(data) else: return jsonify(message='Error query') except: return jsonify(message='Error query')
def post(self): """장바구니 담기 - 한번에 여러개의 상품 담기 가능 - 이미 같은 상품 옵션이 담겨 있으면 수량 변화 Author: 백승찬 Args: data (dict): 사용자가 추가한 product_option_id, quantity 값을 가지는 dictionary Raises: ProductOptionIdTypeError: product_option_id 타입이 int 가 아닐때 QuantityTypeError: quantity 타입이 int가 아닐때 CartQuantityError: 수량이 1개 미만일때 e: 예상하지 못한 에러처리 Returns: 200: { "data": 1 } """ cart_service = CartService() connection = None filters = request.json filters["account_id"] = g.account_info["account_id"] for filter in filters["data"]: if type(filter["product_option_id"]) != int: raise ProductOptionIdTypeError(PRODUCT_OPTION_ID_TYPE_ERROR, 400) if type(filter["quantity"]) != int: raise QuantityTypeError(QUANTITY_TYPE_ERROR, 400) if filter["quantity"] <= 0: raise CartQuantityError(CART_QUANTITY_ERROR, 400) try: connection = connect_db() result = cart_service.post_cart(connection, filters) connection.commit() return jsonify({"data": result}) except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def save_evaluation(fecha,curso): try: cn.g.db = cn.connect_db() cn.g.db.execute("insert into evaluacion(fecha, total, curso) values('"+fecha+"',0,"+curso+")") cn.g.db.commit() return True except: return False
def get(self): """셀러 계정 관리 셀러 계정 목록 조회, 셀러 계정 정보 엑셀 다운로드 Authon: 김현영 Raises: UnauthorizedError: 마스터가 아닌 계정의 요청일 때 e: [description] Returns: [type]: [description] """ auth = g.account_info if auth['account_type'] != MASTER_ACCOUNT_TYPE: raise UnauthorizedError(UNAUTHORIZED, 401) master_service = MasterService() connection = None try: filter = { "seller_id" : request.args.get("seller_id", ""), "seller_nickname" : request.args.get("seller_nickname", ""), "english_name" : request.args.get("english_name", ""), "korean_name" : request.args.get("korean_name", ""), "seller_type" : request.args.get("seller_type", ""), "clerk_name" : request.args.get("clerk_name", ""), "clerk_phone_number" : request.args.get("clerk_phone_number", ""), "clerk_email" : request.args.get("clerk_email", ""), "start_date" : request.args.get("start_date", ""), "end_date" : request.args.get("end_date", ""), "action_status" : request.args.get("action_status", ""), "offset" : int(request.args.get("offset", 0)), "limit" : int(request.args.get("limit", 10)), } connection = connect_db() if request.path == "/manage/sellers": result, count = master_service.get_seller_list(connection, filter) return jsonify({"data" : result, "count" : count}), 200 if request.path == "/manage/sellers/downloads": del filter["offset"] del filter["limit"] result = master_service.to_xlsx(connection, filter) return result except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def get_current_turno(): try: cn.g.db = cn.connect_db() cur = cn.g.db.execute('select id, nombre from turno') carreras = [dict(id=row[0], nombre=row[1])for row in cur.fetchall()] cn.g.db.close() return json.dumps(carreras) except: return jsonify(message='Error query')
def get_calificacion(usuario,evaluacion): try: cn.g.db = cn.connect_db() cur = cn.g.db.execute("select id from calificacion where usuario="+str(usuario)+" and evaluacion="+str(evaluacion)) evaluacion = [dict(id=row[0])for row in cur.fetchall()] cn.g.db.close() if(len(evaluacion)>0): return evaluacion[0].get('id') return None except: return None
def post(self, valid: ValidRequest): """주문하기 기능 Author: 백승찬 Args: { "orderer_name" : 주문자 이름 "orderer_phone_number" : 주문자 번호 "orderer_email : 주문자 이메일 "address_id" : 주소 아이디 "shipment_memo_id" : 배송 메모 아이디 "message" : 직접입력 시 입력하는 message "total_price" : 결제 총액 } Raises: CartIdTypeError: 리스트로 들어온 다수의 cart_id가 int 타입이 아니면 에러처리 e: 예상하지 못한 에러처리 Returns: { "data": { "order_id": 주문번호 } } """ order_service = OrderService() connection = None filters = valid.get_json() filters["account_id"] = g.account_info["account_id"] filters["carts"] = request.json["carts"] for filter in filters["carts"]: if type(filter['cart_id']) != int: raise CartIdTypeError(CART_ID_TYPE_ERROR, 400) try: connection = connect_db() result = order_service.post_order(connection, filters) connection.commit() return jsonify({"data": result}) except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def save_calificacion(option, usuario,evaluacion, criterio, valor): try: cn.g.db = cn.connect_db() if option == 'SAVE': cn.g.db.execute("insert into calificacion(usuario, evaluacion, criterio, valor) values("+str(usuario)+","+str(evaluacion)+","+str(criterio)+","+str(valor)+")") elif option == 'UPDATE': cn.g.db.execute("update calificacion set valor="+str(valor)+" where usuario="+str(usuario)+" and evaluacion="+str(evaluacion)+" and criterio="+str(criterio)) cn.g.db.commit() return True except: return False
def get_evaluation(fecha,curso): try: cn.g.db = cn.connect_db() cur = cn.g.db.execute("select id from evaluacion where fecha='"+str(fecha)+"' and curso="+str(curso)) evaluacion = [dict(id=row[0])for row in cur.fetchall()] cn.g.db.close() if(len(evaluacion)>0): return evaluacion[0].get('id') return None except: return None
def post(self, valid: ValidRequest): data = valid.get_form() data["account_id"] = g.account_info.get("account_id") data["account_type"] = g.account_info.get("account_type") # json 형태로 오는 options 따로 변수 선언 후 제거 options = literal_eval(data["options"]) del data["options"] main_image_file = request.files.get("main_image_file") image_files = request.files.getlist("image_files") if data["account_type"] not in [ MASTER_ACCOUNT_TYPE, SELLER_ACCOUNT_TYPE ]: raise UnauthorizedError(UNAUTHORIZED, 401) product_service = ProductService() image_service = ImageService() connection = None s3_connection = None image_urls = [] try: connection = connect_db() s3_connection = connect_s3() # 상품 등록 data = product_service.insert_new_product(connection, data, options) # 메인 이미지 S3 등록 image_urls.append( image_service.image_upload(s3_connection, main_image_file)) # 다른 이미지 S3 등록 for image_file in image_files: image_urls.append( image_service.image_upload(s3_connection, image_file)) product_service.insert_new_product_images(connection, data, image_urls) connection.commit() return jsonify({"message": "success"}) except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def get(self, valid: ValidRequest): """어드민 상품 관리 리스트 Author: 이서진 Returns: - 200: "data": { "count": 상품 리스트 총 개수 "products": [ { "created_at": 상품 등록 시간, "discount_start_time": 상품 할인 시작 시간, "discount_end_time": 상품 할인 끝 시간, "discount_rate": 상품 할인율, "image_url": 상품 대표 이미지 주소, "is_displayed": 진열 여부, "is_sold": 판매 여부, "name": 상품 이름, "price": 가격, "product_code": 상품 코드, "product_number": 상품 번호, "seller_category": 셀러 속성 } ] } - 400: validate param 오류 """ filters = valid.get_params() filters["account_id"] = g.account_info.get("account_id") filters["account_type"] = g.account_info.get("account_type") if filters["account_type"] not in [ MASTER_ACCOUNT_TYPE, SELLER_ACCOUNT_TYPE ]: raise UnauthorizedError(UNAUTHORIZED, 401) product_service = ProductService() connection = None try: connection = connect_db() result = product_service.get_product_list(connection, filters) return jsonify({"data": result}) except Exception as e: raise e finally: if connection is not None: connection.close()
def get_carrera(id_carrera, json=True): try: cn.g.db = cn.connect_db() cur = cn.g.db.execute('select nombre from carrera where id='+str(id_carrera)) carrera = [dict(nombre=row[0])for row in cur.fetchall()] cn.g.db.close() if json: return {'id':id_carrera, 'nombre':carrera[0].get('nombre')} else: return carrera[0].get('nombre') except: return {'id':id_carrera, 'nombre':'Ninguna'}
def update_information(): error = None result = {} if request.method == 'POST': try: cn.g.db = cn.connect_db() cn.g.db.execute("update usuario set nombre='"+str(request.form['nombre'])+"', carrera="+str(request.form['carrera'])+",turno="+str(request.form['turno'])+",ciclo="+str(request.form['ciclo'])+", seccion='"+str(request.form['seccion'])+"' where token='"+str(request.form['token'])+"'") cn.g.db.commit() result = {'status':True} except: result = {'status':False} return json.dumps(result)
def remove_employee(id): try: sql = """ DELETE FROM ADMIN.EMPLOYEES WHERE EMPLOYEE_ID = :id """ conn = connect_db() c = conn.cursor() c.execute(sql, [id]) conn.commit() conn.close() print("Removed employee with id: ", id) except (RuntimeError, TypeError, NameError): print("error on remove_employee()")
def get_employees_short(): sql = "SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME FROM ADMIN.EMPLOYEES" list = [] conn = connect_db() c = conn.cursor() c.execute(sql) for row in c: list.append(row) return list
def get(self): """배송지 수정하기 Author: 백승찬 Args: Raises: Returns: { "data": [ { "additional_address" : 추가 주소 정보 "address" : 주소 "address_history_id" : 주소 히스토리 아이디 "address_id" : 주소 아이디 "end_time" : 종료 시간 "is_defaulted" : 기본 배송지 여부 "is_deleted" : 삭제 여부 "name" : 수령인 이름 "phone_number" : 수령인 핸드폰 번호 "start_time" : 시작 시간 "zip_code" : 우편번호 } ] } """ shipment_service = ShipmentService() connection = None try: filters = {"account_id": g.account_info["account_id"]} connection = connect_db() result = shipment_service.get_address_information( connection, filters) connection.commit() return jsonify({"data": result}) except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def detale_usuario(token_user): dias = [1,2,3,4,5] detalles = [] profile = rs.get_profile(token_user) for dia in dias: cn.g.db = cn.connect_db() cur = cn.g.db.execute("select c.id, c.nombre, p.nombre from curso c inner join profesor p on p.id=c.profesor where carrera="+profile.get('carrera')+" and turno="+profile.get('turno')+" and ciclo="+profile.get('ciclo')+" and dia="+str(dia)+" and seccion='"+profile.get('seccion')+"'") cursos = [dict(id=row[0], nombre=row[1], profesor=row[2])for row in cur.fetchall()] if len(cursos) > 0: cursos[0].update({'dia':str(dia)}) detalles.append(cursos[0]) cn.g.db.close() return render_template('admin/detalles_user.html', detalles=detalles)
def get_departments(): conn = connect_db() c = conn.cursor() list = [] c.execute("SELECT * FROM ADMIN.DEPARTMENT") for row in c: department = Department(row[0], row[1]) list.append(department) # close connection conn.close() return list
def get_latest_id(): max_id_sql = "SELECT NVL(MAX(EMPLOYEE_ID), 0) AS MAX_ID FROM ADMIN.EMPLOYEES" conn = connect_db() c = conn.cursor() c.execute(max_id_sql) max_id = 0 max = c.fetchone() for num in max: max_id = num #debug print("MaxID: ", max_id) return max_id
def get_employees(): conn = connect_db() c = conn.cursor() list = [] c.execute("SELECT * FROM ADMIN.EMPLOYEES") for row in c: employee = Employee(row[0], row[1], row[2], row[3], row[4], row[5], row[6]) list.append(employee) # close connection conn.close() return list
def get(*args, order_id): """결제 완료 페이지 정보 가져오기 Author: 백승찬 Args: (PATH): order_id를 path parameter로 받음 Raises: OrderIdTypeError: order_id 가 int 타입이 아닐때 e: 예상하지 못한 에러처리 Returns: 200 : { "data": { "id": 주문번호 "total_price": 총 결제 금액 } } """ order_service = OrderService() connection = None filters = { "order_id": int(order_id), "account_id": g.account_info["account_id"] } if type(filters["order_id"]) != int: raise OrderIdTypeError(ORDER_ID_TYPE_ERROR, 400) try: connection = connect_db() result = order_service.get_order_complete(connection, filters) connection.commit() return jsonify({"data": result}) except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def get_link(): conn = connect_db() c = conn.cursor() list = [] c.execute("SELECT * FROM ADMIN.EMPLOYEE_TASK_LINK") for row in c: link = EmployeeTaskLink(row[0], row[1], row[2]) list.append(link) # close connection conn.close() return list
def get_status(): conn = connect_db() c = conn.cursor() list = [] c.execute("SELECT * FROM ADMIN.STATUS") for row in c: status = Status(row[0], row[1]) list.append(status) # close connection conn.close() return list
def get_info(): conn = connect_db() c = conn.cursor() list = [] c.execute("SELECT * FROM ADMIN.EMPLOYEE_INFO") for row in c: info = EmployeeInfo(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7]) list.append(info) # close connection conn.close() return list
def get_notes(): conn = connect_db() c = conn.cursor() list = [] c.execute("SELECT * FROM ADMIN.EMPLOYEE_NOTES") for row in c: note = EmployeeNotes(row[0], row[1], row[2], row[3]) list.append(note) # close connection conn.close() return list
def get_profile(token_user): try: cn.g.db = cn.connect_db() cur = cn.g.db.execute('select carrera, turno, ciclo, seccion, id from usuario where token='+str(token_user)) usuario = [dict(carrera=row[0], turno=row[1], ciclo=row[2], seccion=row[3], id=row[4])for row in cur.fetchall()] cn.g.db.close() return { 'carrera':str(usuario[0].get('carrera')), 'turno':str(usuario[0].get('turno')), 'ciclo':str(usuario[0].get('ciclo')), 'seccion':str(usuario[0].get('seccion')), 'id':str(usuario[0].get('id')) } except: return {}
def get_tasks(): conn = connect_db() c = conn.cursor() list = [] c.execute("SELECT * FROM ADMIN.TASKS") for row in c: task = Tasks(row[0], row[1], row[2], row[3], row[4]) list.append(task) # close connection conn.close() return list
def get_user(username, password): found_user = [] sql = "select * from admin.users where user_name = :username and user_pass = :password" conn = connect_db() c = conn.cursor() c.execute(sql, [username, password]) for row in c: found_user.append(row) if (found_user == []): return False else: print("User was found") return True
def patch(self, valid: ValidRequest): """카트 수량 변경 - 카트에 담긴 제품 수량 변경시 이력관리 - 수량 변경시 1개 미만으로 선택시 에러처리 Author: 백승찬 Args: cart_id (dict): 사용자가 수정한 cart_id 값을 가지는 dictionary quantity (dict): 사용자가 수정한 quantity 값을 가지는 dictionary Raises: CartQuantityError: 수량 선택이 1개 미만일때 에러처리 e: 예상하지 못한 에러처리 Returns: 200 : { "data": 1 } """ cart_service = CartService() connection = None filters = valid.get_json() filters["account_id"] = g.account_info["account_id"] if filters["quantity"] <= 0: raise CartQuantityError(CART_QUANTITY_ERROR, 400) try: connection = connect_db() result = cart_service.change_quantity_cart(connection, filters) connection.commit() return jsonify({"data": result}) except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def save_employee(employee): emp_sql = """ UPDATE ADMIN.EMPLOYEES SET DEPARTMENT_ID = :depID, FIRST_NAME = :fname, LAST_NAME = :lname, TITLE = :title, PHONE = :phone, EMAIL = :email WHERE EMPLOYEE_ID = :empID """ emp_info_sql = """ UPDATE ADMIN.EMPLOYEE_INFO SET STREET_ADDRESS = :address, CITY = :city, STATE = :state, ZIP_CODE = :zip, LICENSE_ID = :licenseID, SS_NUMBER = :ssn WHERE EMPLOYEE_ID = :empID """ try: empID = int(employee[0].empID) depID = int(employee[0].deptID) title = str(employee[0].title) fname = str(employee[0].fname) lname = str(employee[0].lname) phone = int(employee[0].phone) email = str(employee[0].email) address = str(employee[1].address) city = str(employee[1].city) state = str(employee[1].state) zip = int(employee[1].zipcode) licenseID = str(employee[1].licenseID) ssn = int(employee[1].ssn) conn = connect_db() c = conn.cursor() # update Employee table c.execute(emp_sql, {'depID': depID, 'fname': fname, 'lname': lname, 'title': title, 'phone': phone, 'email': email, 'empID': empID}) conn.commit() c.execute(emp_info_sql, {'address': address, 'city': city, 'state': state, 'zip': zip, 'licenseID': licenseID, 'ssn': ssn, 'empID': empID}) conn.commit() conn.close() except (RuntimeError, TypeError, NameError): print("error on save_employee()")
def patch(self, valid: ValidRequest): """배송지 수정하기 Author: 백승찬 Args: { "address_id" : 주소 아이디 "name" : 수령인 "phone_number : 수령인 전화번호 "is_defaulted : 기본 배송지 선택 여부 "address" : 주소 "additional_address" : 추가 주소 정보 "zip_code" : 우편번호 "is_deleted" : 삭제 여부 } Raises: Returns: { "data": 1 } """ shipment_service = ShipmentService() connection = None try: filters = valid.get_json() filters["account_id"] = g.account_info["account_id"] connection = connect_db() result = shipment_service.update_address_information( connection, filters) connection.commit() return jsonify({"data": result}) except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def delete(self): """카트 상품 삭제 - 한번에 여러 상품 삭제 가능 Author: 백승찬 Args: data (dict): 사용자가 삭제한 cart_id 리스트 Raises: CartIdTypeError: cart_id 가 int 타입이 아닐때 e: 예상하지 못한 에러처리 Returns: 200 : { "data": 1 } """ cart_service = CartService() connection = None filters = request.json filters["account_id"] = g.account_info["account_id"] for filter in filters["data"]: if type(filter["cart_id"]) != int: raise CartIdTypeError(CART_ID_TYPE_ERROR, 400) try: connection = connect_db() result = cart_service.delete_cart_product(connection, filters) connection.commit() return jsonify({"data": result}) except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def get(*args): filters = dict(request.args) search_service = SearchService() connection = None try: connection = connect_db() result = search_service.get_seller_name_search_list( connection, filters) return jsonify({"data": result}) except Exception as e: raise e finally: if connection is not None: connection.close()
def get(*args, seller_category_id, product_category_id=None): filters = dict(request.args) filters["seller_category_id"] = seller_category_id filters["product_category_id"] = product_category_id product_service = ProductService() connection = None try: connection = connect_db() result = product_service.get_product_category_list(connection, filters) return jsonify({"data": result}) except Exception as e: raise e finally: if connection is not None: connection.close()
def delete(self, valid: ValidRequest): """배송지 삭제하기 Author: 백승찬 Args: data (dict) : { "address_id" : 주소 아이디 } Raises: Returns: { "data": 1 } """ shipment_service = ShipmentService() connection = None try: filters = valid.get_json() filters["account_id"] = g.account_info["account_id"] connection = connect_db() result = shipment_service.delete_address_information( connection, filters) connection.commit() return jsonify({"data": result}) except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def check_login(username, password): try: cn.g.db = cn.connect_db() cur = cn.g.db.execute("select token from usuario where username='******' and password='******'") token = [dict(clave=row[0])for row in cur.fetchall()] cn.g.db.close() if len(token) > 0: return { 'status': True, 'message':'Welcome', 'token':token[0].get('clave') } else: return { 'status': False, 'message':'Login incorrect' } except: return {}
def post(self, valid: ValidRequest): account_service = AccountService() connection = None try: data = valid.get_json() connection = connect_db() result = account_service.login(data, connection) connection.commit() return jsonify({"message": LOGIN_SUCCESS, "data": result}), 201 except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def check_token(token): try: cn.g.db = cn.connect_db() cur = cn.g.db.execute("select token from usuario where token='"+str(token)+"'") token = [dict(token=row[0])for row in cur.fetchall()] cn.g.db.close() if len(token) > 0: return { 'status': True, 'message': 'Welcome', 'token': token[0].get('token') } else: return { 'status': False, 'message': 'Login incorrect' } except: return {}
def post(self, valid: ValidRequest): account_service = AccountService() connection = None try: data = valid.get_json() data['account_type_id'] = MASTER_ACCOUNT_TYPE connection = connect_db() result = account_service.create_account(data, connection) connection.commit() return jsonify({"message": ACCOUNT_CREATED, "data": result}), 201 except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def patch(self, valid: ValidRequest): """셀러 계정 관리 셀러 상태 변경 Authon: 김현영 Raises: UnauthorizedError: 마스터가 아닌 계정의 요청일 때 e: [description] Returns: """ auth = g.account_info if auth['account_type'] != MASTER_ACCOUNT_TYPE: raise UnauthorizedError(UNAUTHORIZED, 401) master_service = MasterService() connection = None try: data = valid.get_json() data["account_id"] = auth["account_id"] connection = connect_db() result = master_service.change_seller_status(connection, data) connection.commit() return jsonify({"message" : STATUS_UPDATE_SUCCESS, "data" : result}), 201 except Exception as e: connection.rollback() raise e finally: if connection is not None: connection.close()
def add_employee(data_list): emp_sql = """ INSERT INTO ADMIN.EMPLOYEES(DEPARTMENT_ID, FIRST_NAME, LAST_NAME, TITLE, PHONE, EMAIL) VALUES(:depID, :fname, :lname, :title, :phone, :email)""" emp_info_sql = """ INSERT INTO ADMIN.EMPLOYEE_INFO(EMPLOYEE_ID, STREET_ADDRESS, CITY, STATE, ZIP_CODE, LICENSE_ID, SS_NUMBER) VALUES(:empID, :address, :city, :state, :zipcode, :licenseID, :ssn)""" try: depID = int(data_list[0].deptID) title = str(data_list[0].title) fname = str(data_list[0].fname) lname = str(data_list[0].lname) phone = int(data_list[0].phone) email = str(data_list[0].email) address = str(data_list[1].address) city = str(data_list[1].address) state = str(data_list[1].state) zip = int(data_list[1].zipcode) licenseID = str(data_list[1].licenseID) ssn = int(data_list[1].ssn) conn = connect_db() c = conn.cursor() # insert new Employee c.execute(emp_sql, [depID, fname, lname, title, phone, email]) conn.commit() # get latest ID latest_empID = get_latest_id() # insert new EmployeeInfo c.execute(emp_info_sql, [latest_empID, address, city, state, zip, licenseID, ssn]) conn.commit() conn.close() except Exception as e: print("error on add_employee()") print(e)
def wrapper(*args, **kwargs): access_token = request.headers.get("Authorization") if access_token is None: raise LoginRequiredError(LOGIN_REQUIRED, 401) connection = None try: # 헤더에 있는 토큰을 디코드해서 payload에 담는다. payload = jwt.decode(access_token, SECRET_KEY, ALGORITHM) # payload = {"account_id" : user_info["account_id"]} account_dao = AccountDao() connection = connect_db() account = account_dao.account_check(connection, payload) if account["account_type_id"] != USER_ACCOUNT_TYPE: raise InvalidAccessError(UNAUTHORIZED_TOKEN, 401) if account["is_deleted"] == 1: raise InvalidAccessError(UNAUTHORIZED_TOKEN, 401) g.account_info = {"account_id": payload["account_id"]} except jwt.InvalidTokenError: raise InvalidAccessError(UNAUTHORIZED_TOKEN, 401) except Exception as e: raise e finally: if connection is not None: connection.close() return func(*args, **kwargs)
def get_puntaje(): try: if request.method == 'POST': user_token = request.form['token'] if user_token is not None: profile = rs.get_profile(user_token) user_id = profile.get('id') cn.g.db = cn.connect_db() cur = cn.g.db.execute('select evaluacion from calificacion where usuario='+user_id) evaluacion = [dict(eval=row[0])for row in cur.fetchall()] evaluacion = evaluacion[0].get('eval') cn.g.db.close() puntaje = rs.get_puntaje(evaluacion) data = { 'status': 'OK', 'puntaje': puntaje } return data else: jsonify(status='Fail') except: return jsonify(status='Fail')
def get_curso(): try: if request.method == 'POST': user_token = request.form['token'] if user_token is not None: data = {} profile = rs.get_profile(user_token) dia = datetime.datetime.today().weekday() + 1 cn.g.db = cn.connect_db() cur = cn.g.db.execute("select c.id, c.nombre, p.nombre from curso c inner join profesor p on p.id=c.profesor where carrera="+profile.get('carrera')+" and turno="+profile.get('turno')+" and ciclo="+profile.get('ciclo')+" and dia="+str(dia)+" and seccion='"+profile.get('seccion')+"'") usuario = [dict(id_curso=row[0], curso=row[1], profesor=row[2])for row in cur.fetchall()] for user in usuario: data.update({ 'id':user.get('id_curso'), 'curso':user.get('curso'), 'profesor':user.get('profesor') }) data.update({'state':'OK'}) cn.g.db.close() return json.dumps(data) else: return jsonify(state='FAIL') except: return jsonify(state='FAIL')
def turnos(): cn.g.db = cn.connect_db() cur = cn.g.db.execute('select id, nombre from turno') turnos = [dict(id=row[0], nombre=row[1])for row in cur.fetchall()] cn.g.db.close() return render_template('admin/turno.html', turnos=turnos)
def cursos(): cn.g.db = cn.connect_db() cur = cn.g.db.execute('Select cu.id, cu.nombre, ca.nombre, t.nombre, cu.ciclo, p.nombre, cu.seccion, cu.dia from curso cu inner join carrera ca on cu.carrera = ca.id inner join turno t on t.id = cu.turno inner join profesor p on p.id = cu.profesor') cursos = [dict(id=row[0], nombre=row[1], carrera=row[2], turno=row[3], ciclo=row[4], profesor=row[5], seccion=row[6], dia=row[7])for row in cur.fetchall()] cn.g.db.close() return render_template('admin/cursos.html', cursos=cursos)
def usuarios(): cn.g.db = cn.connect_db() cur = cn.g.db.execute('select u.id, u.username,c. nombre,t. nombre,u. ciclo,u. seccion, u.token, u.nombre from usuario u inner join carrera c on c.id = u.carrera inner join turno t on t.id = u.turno') usuarios = [dict(id=row[0], username=row[1], carrera=row[2], turno=row[3], ciclo=row[4], seccion=row[5], token=row[6], nombre=row[7])for row in cur.fetchall()] cn.g.db.close() return render_template('admin/usuario.html', usuarios=usuarios)
def criterios(): cn.g.db = cn.connect_db() cur = cn.g.db.execute('select id, nombre from criterios') criterios = [dict(id=row[0], nombre=row[1])for row in cur.fetchall()] cn.g.db.close() return render_template('admin/criterios.html', criterios=criterios)
def get_puntaje(evaluacion): cn.g.db = cn.connect_db() cur = cn.g.db.execute("select SUM(valor)/COUNT(*) as resultado from calificacion where evaluacion="+str(evaluacion)) puntaje = [dict(puntos=row[0])for row in cur.fetchall()] return puntaje[0].get('puntos')
def profesores(): cn.g.db = cn.connect_db() cur = cn.g.db.execute('select id, nombre from profesor') profesores = [dict(id=row[0], nombre=row[1])for row in cur.fetchall()] cn.g.db.close() return render_template('admin/profesor.html', profesores=profesores)
def carreras(): cn.g.db = cn.connect_db() cur = cn.g.db.execute('select id, nombre from carrera') carreras = [dict(id=row[0], nombre=row[1])for row in cur.fetchall()] cn.g.db.close() return render_template('admin/carrera.html', carreras=carreras)
def get_criterios(): cn.g.db = cn.connect_db() cur = cn.g.db.execute('select id, nombre from criterios') criterios = [dict(id=row[0], nombre=row[1])for row in cur.fetchall()] cn.g.db.close() return json.dumps(criterios)