Ejemplo n.º 1
0
 def update_blood_donation_event(self, blood_donation_event):
     db = get_connection()
     cursor = db.cursor()
     if check_active(blood_donation_event["Drive_id"],
                     blood_donation_event["Operator_id"], cursor):
         update_query = "UPDATE BLOOD_DONATION_EVENT set"
         args = []
         for key in blood_donation_event:
             if blood_donation_event[key]:
                 update_query = update_query + "set " + key + "=%s"
                 args.append(blood_donation_event[key])
         try:
             db = get_connection()
             cursor = db.cursor()
             argument = tuple(args)
             cursor.execute(update_query, argument)
             db.commit()
             return {"status": 201, "message": "Event updated succesfully"}
         except mysql.Error as err:
             print("Failed to update entry: {}".format(err))
             return {"status": 500, "message": str(err)}
         finally:
             db.close()
     else:
         return {
             "status": 404,
             "message": "Event already expired, can't be updated"
         }
    def update_blood_donation_event(self, blood_donation_event):
        db = get_connection()
        cursor = db.cursor()
        if check_active(blood_donation_event["Drive_id"],
                        blood_donation_event["Operator_id"], cursor):
            update_query = "UPDATE BLOOD_DONATION_EVENT set Name = %s, \
            Date_of_event=%s, Venue=%s where Drive_id=%s and Operator_id=%s"

            try:
                db = get_connection()
                cursor = db.cursor()
                cursor.execute(update_query,
                               (blood_donation_event["Name"],
                                blood_donation_event["Date_of_event"],
                                blood_donation_event["Venue"],
                                blood_donation_event["Drive_id"],
                                blood_donation_event["Operator_id"]))
                db.commit()
                return {"status": 201, "message": "Event updated succesfully"}
            except mysql.Error as err:
                print("Failed to update entry: {}".format(err))
                return {"status": 500, "message": str(err)}
            finally:
                db.close()
        else:
            return {
                "status": 404,
                "message": "Event already expired, can't be updated"
            }
Ejemplo n.º 3
0
    def get_connection(self):
        '''
        gets a connection to the mongodb server.
        '''
        host = unicode(self.lineEditHost.text())
        port = unicode(self.lineEditPort.text())
        self.plainTextEditQueries.clear()

        if len and host:
            try:
                
                self.con = connection.get_connection(unicode(host), int(port))
                self.plainTextEditQueries.insertPlainText("Connected Successfully to MongoDB at " + '<' + self.con.host + '>')
                self.plainTextEditQueries.appendPlainText('Write your Pythonic query here...\n')
                
            except:
                font = QFont()
                font.setUnderline(True)
                self.plainTextEditQueries.setFont(font)
                self.plainTextEditQueries.insertPlainText("A problem has ocurred, no connection to MongoDB!")

        else:

            try:

                self.con = connection.get_connection()
                self.plainTextEditQueries.insertPlainText("Connected Successfully to MongoDB at " + '<' + self.con.host + '>')
                self.plainTextEditQueries.appendPlainText('Write your Pythonic query here...\n')
                      

            except:
                self.plainTextEditQueries.insertPlainText("A problem has ocurred, no connection to MongoDB!")
        
        self.populate_main_tree()
    def upadate_blood_bank(self, parameters, Operator_id):
        #update the special attributes of a particular blood unit
        if parameters["case"] == 1:
            if Operator.check_branch_id(Operator_id, parameters["Br_id"]):
                db = get_connection()
                cursor = db.cursor()
                update_query = "UPDATE BLOOD set Special_Attributes=%s where Blood_id=%s"
                try:
                    cursor.execute(update_query,
                                   (parameters["Special_Attributes"],
                                    parameters["Blood_id"]))
                    db.commit()
                    return {
                        "status": 201,
                        "message": "Bloodunit updated Successfully"
                    }
                except mysql.Error as err:
                    print("Failed to update entry: {}".format(err))
                    return {"status": 500, "message": str(err)}
                finally:
                    db.close()
            else:
                return {"status": 401, "message": "Unauthorised Access"}

    #Move asked quantity of particular blood group blood from 1 branch to other branch
        elif parameters["case"] == 2:
            source = Operator.check_branch_id(Operator_id,
                                              parameters["from_branch"])
            target = Operator.check_branch_id(Operator_id,
                                              parameters["to_branch"])
            if source and target:
                #if  True and True :
                db = get_connection()
                cursor = db.cursor()
                update_query = "UPDATE BLOOD SET Br_id=%s WHERE Br_id=%s AND Blood_Group=%s AND Date_of_Expiry > CURDATE() LIMIT %s"
                try:
                    cursor.execute(
                        update_query,
                        (parameters["from_branch"], parameters["to_branch"],
                         parameters["Blood_Group"], parameters["Count"]))
                    db.commit()
                    return {
                        "status": 201,
                        "message": "Bloodunit updated Successfully"
                    }
                except mysql.Error as err:
                    return {"status": 500, "message": str(err)}
            else:
                return {"status": 401, "message": "Unauthorised Access"}
        else:
            return {"status": 404, "message": "Case not found"}
Ejemplo n.º 5
0
def get_mysql_users():
	try:
		conn = get_connection()
		cursor = conn.cursor()
		sql = "select * from tbl_users"
		cursor.execute(sql)
		data = cursor.fetchall()
		#do something
		result = {
			"result": "ok",
			"message": "successful",
			"data": data
		}

	except Exception as e:
		result = {
			"result": "fail",
			"message": str(e),
			"data": None
		}

	finally:
		conn.commit()
		cursor.close()

	return jsonify(result)
Ejemplo n.º 6
0
def update_mysql_user():
	try:
		conn = get_connection()
		cursor = conn.cursor()
		received_data = request.data
		received_data = received_data.decode('utf-8')
		data = json.loads(received_data)
		userId = data['id']
		userName = data['username']

		sql = "update tbl_users set username = %s where id = %s"
		cursor.execute(sql,(userName,userId))

		result = {
			"result": "ok",
			"message": "successful"
		}

	except Exception as e:
		result = {
			"result": "fail",
			"message": str(e)
		}

	finally:
		conn.commit()
		cursor.close()

	return jsonify(result)
Ejemplo n.º 7
0
def register_mysql_user():
	try:
		conn = get_connection()
		cursor = conn.cursor()
		received_data = request.data
		received_data = received_data.decode('utf-8')
		data = json.loads(received_data)

		userName = data['username']

		sql = "insert into tbl_users(username) values(%s)"
		cursor.execute(sql,(userName,))

		result = {
			"result": "ok",
			"message": "successful"
		}

	except Exception as e:
		result = {
			"result": "fail",
			"message": str(e)
		}
	finally:
		conn.commit()
		cursor.close()

	return jsonify(result)
Ejemplo n.º 8
0
def execute_query(id):
    query = (q.query_list['get_query'], (id, ))
    result = db.get_data('sqlite', CONN, query)
    if result['status']:
        #query,num_of_rows,date_submitted,status,date_executed,application
        query = (result['data'][0][0], )
        num_of_rows = result['data'][0][1]
        status = result['data'][0][3]
        application = result['data'][0][5]
        database = result['data'][0][6]

        if status == 'SUBMITTED':
            conn_str = cn.get_connection(application, database)
            update_result = db.update_data(config.get_sql_type('database'),
                                           conn_str, query, num_of_rows)
            if update_result['status']:
                query = (
                    q.query_list['update_query'],
                    (datetime.now().strftime('%Y-%m-%d'),
                     update_result['data'], id),
                )
                querytable_update = db.update_data('sqlite', CONN, query, 1)
            return update_result
        else:
            {
                'data': None,
                'status': False,
                'message': "Query is not in SUBMITTED "
            }
Ejemplo n.º 9
0
def main():
        f = open('log.txt', 'w') #Opening the log txt file

        s = connection.get_connection()
        connection.announce(s)

        # Loop
        while 1:
                text = s.recv(2040)
                print text # This is the consoles output
                user = text.split('!')[0][1:] # User is the name of the person who sent the last message
                f.write(text) # Write the text to file
                if text.find('PING') !=-1: # This is to respond to the server when pinged, otherwise the bot will get kicked.
                        s.send("PONG %s\r\n")
                if text.find('!help') !=-1:
                        functions.list(s)
                if text.find('!credits') !=-1:
						functions.credits(s)
                if text.find('!tip') !=-1:
                        functions.tips(s)
                if text.find('!hello') !=-1:
                        functions.greet(s, user)
                if text.find('!leetmeter') !=-1:
                        functions.leet(s)
                if text.find('!MystPhysX') !=-1:
                        functions.myst(s)
Ejemplo n.º 10
0
    def googlesignin():
        try:
            db_connection = get_connection()

            id_token = request.headers['Authorization']
            user_request = requests.get(
                f'https://oauth2.googleapis.com/tokeninfo?id_token={id_token}')

            user_info = user_request.json()
            google_email = user_info.get('email')
            google_name = user_info.get('name')
            google_id = user_info.get('sub')

            sign_in_user = user_service.google_social_login(
                {
                    "email": google_email,
                    "name": google_name,
                    "user_social_id": google_id
                }, db_connection)

            if sign_in_user:
                access_token = user_service.generate_access_token(sign_in_user)
                return jsonify({"access_token": access_token}), 200

        finally:
            if db_connection:
                db_connection.close()
Ejemplo n.º 11
0
    def get(self):
        try:
            db = connection.get_connection()

            arguments = {
                'event_name'   : '%' + request.args.get('event_name', '') + '%',
                'event_number' : request.args.get('event_number', None),
                'event_status' : request.args.get('event_status', None),
                'start_date'   : request.args.get('start_date', None),
                'end_date'     : request.args.get('end_date', None),
                'is_exposed'   : request.args.get('is_exposed', None),
                'event_type'   : ast.literal_eval(request.args.get('event_type', None))
            }

            event_list = self.service.get_event_list(db, arguments)

        except Exception as e:
            traceback.print_exc()
            return jsonify({'message':e.message}), 400

        else:
            return jsonify(event_list), 200

        finally:
            db.close()
Ejemplo n.º 12
0
    def __init__(self):
        self._id = os.getpid()
        self._connection = get_connection()
        self._name = f'{self.__class__.__name__.lower()}:{self._id}'
        self._action_key = f'action:{self._id}'

        self._connection.set(self._name, self._id)
Ejemplo n.º 13
0
def main():
    f = open('log.txt', 'w')  #Opening the log txt file

    s = connection.get_connection()
    connection.announce(s)

    # Loop
    while 1:
        text = s.recv(2040)
        print text  # This is the consoles output
        user = text.split('!')[0][
            1:]  # User is the name of the person who sent the last message
        f.write(text)  # Write the text to file
        if text.find(
                'PING'
        ) != -1:  # This is to respond to the server when pinged, otherwise the bot will get kicked.
            s.send("PONG %s\r\n")
        if text.find('!help') != -1:
            functions.list(s)
        if text.find('!credits') != -1:
            functions.credits(s)
        if text.find('!tip') != -1:
            functions.tips(s)
        if text.find('!hello') != -1:
            functions.greet(s, user)
        if text.find('!leetmeter') != -1:
            functions.leet(s)
        if text.find('!MystPhysX') != -1:
            functions.myst(s)
Ejemplo n.º 14
0
    def put(self, coupon_id, seller_id):
        """
        쿠폰 수정

        Args:
            coupon_id: 수정할 쿠폰 아이디

        Returns:
            200: 시리얼 넘버를 담은 CSV 파일 리턴
            400: 존재하지 않는 쿠폰 아이디로 쿠폰 조회, 딕셔너리 키에러
            500: 데이터베이스 조작 에러, 내부 에러, 무결성 에러
            
        Author:
            이충희([email protected])

        History:
            2020-10-11(이충희): 초기 생성
        """
        try:
            conn = get_connection()

            data = request.get_json()

            coupon_name = data['coupon_name']
            description = data['description']

            coupon_id = validate_coupon_int_required(coupon_id, 'coupon_id')
            coupon_name = validate_coupon_str_required(coupon_name,
                                                       'coupon_name')
            description = validate_coupon_str_required(description,
                                                       'description')

            params = {}
            params['coupon_id'] = coupon_id
            params['coupon_name'] = coupon_name
            params['description'] = description

            self.service.update_coupon_info(conn, params)

        except (err.OperationalError, err.InternalError,
                err.IntegrityError) as e:
            conn.rollback()
            return jsonify({"errno": e.args[0], "errval": e.args[1]}), 500

        except TypeError as e:
            conn.rollback()
            return jsonify({"message": e.args[0]}), 400

        except KeyError as e:
            return jsonify({
                "message": "KEY_ERROR",
                "key_name": e.args[0]
            }), 400

        else:
            conn.commit()
            return jsonify({"message": "SUCCESS"}), 200

        finally:
            conn.close()
Ejemplo n.º 15
0
    def get(self, coupon_id, seller_id):
        """
        쿠폰 조회

        Args:

        Returns:
            200: 상품 JSON 리턴
            400: 쿼리 스트링 유효성 검사 에러
            500: 데이터베이스 조작 에러, 내부 에러
            
        Author:
            이충희([email protected])

        History:
            2020-10-10(이충희): 초기 생성
        """
        try:
            conn = get_connection()

            coupon_id = validate_coupon_int_required(coupon_id, 'coupon_id')

            result = self.service.get_coupon_info(conn, coupon_id)

        except (err.OperationalError, err.InternalError) as e:
            return jsonify({"errno": e.args[0], "errval": e.args[1]}), 500

        except TypeError as e:
            return jsonify({"message": e.args[0]}), 400

        else:
            return jsonify(result), 200

        finally:
            conn.close()
Ejemplo n.º 16
0
class AbstractDao(ABC):
    """Classe abstraite dont les DAO doivent hériter. Permet de gérer simplement la connection, et d'avoir des noms
    méthodes de base des DAO identique. Permet une meilleure lisibilité du code

    !!! chaque classe qui hérite d'une classe abstraite doit implémenter toutes les méthodes décorées pas @abstracmethod
    même si le corps de la méthode est un simple pass (PyCharm peut automatiquement faire cela pour vous)
    """

    connection = get_connection()

    @abstractmethod
    def find_by_id(self, id):
        """Va chercher une élément de la base grâce à son id et retourne l'objet python associé"""

    @abstractmethod
    def find_all(self):
        """Retourne tous les éléments d'une table sous forme de liste d'objets python"""

    @abstractmethod
    def update(self, business_object):
        """Met à jour la ligne en base de donnée associé à l'objet métier en paramètre"""

    @abstractmethod
    def create(self, business_object):
        """Insère une ligne en base avec l'objet en paramètre. Retourne l'objet mise à jour avec son id de la base"""

    @abstractmethod
    def delete(self, business_object):
        """Supprime la ligne en base représentant l'objet en paramètre"""
Ejemplo n.º 17
0
    def get_product(product_key_id):
        """
        상품 상세 정보 조회 API [GET]
        작성자: 이예은

        Args:

        [Header]
        Authorization : 로그인 토큰

        [URL Parameter]
        product_key_id  : 상품의 고유 ID를 통해 상세 페이지 접근

        Returns:
        success      : code : 200
        """
        db_connection = None

        try:
            db_connection = get_connection()
            if db_connection:

                # 마스터일 경우 모든 셀러 조회가 가능하고, 셀러일 경우 토큰 값으로 고유 ID에 해당하는 상품만 볼 수 있도록 seller 고유 id 설정
                seller_key_id = None

                if g.auth is not AUTH['MASTER']:
                    seller_key_id = g.user

                get_product = product_service.get_product(
                    product_key_id, seller_key_id, db_connection)

                return get_product

        finally:
            db_connection.close()
Ejemplo n.º 18
0
    def list_limits(self, Operator_id, parameter):
        Bbank_id = int(parameter["Bbank_id"])
        if Operator.check_bankid(Operator_id, Bbank_id):
            db = get_connection()
            cursor = db.cursor()
            select_query = "select br.Br_id,br.Br_Type,br.Street,br.City,br.Zip,bstk.Blood_Group,bstk.Btype_Limits from \
                    BLOOD_STOCK as bstk join BRANCH as br on (bstk.Br_id=br.Br_id) \
                        where Bbank_id=%s"

            try:
                cursor.execute(select_query, (Bbank_id, ))
                result = cursor.fetchall()
                stocks = []
                db.commit()
                for row in result:
                    stocks.append({
                        'Br_id': row[0],
                        'Br_Type': row[1],
                        "Street": row[2],
                        "City": row[3],
                        "Zip": row[4],
                        'Blood_Group': row[5],
                        'Btype_Limits': row[6]
                    })

                db.commit()
                return {"status": 201, "list": stocks}

            except mysql.Error as err:
                print("Internal Server error: {}".format(err))
                return {"status": 500, "message": str(err)}
            finally:
                db.close()
        else:
            return {"status": 401, "message": "Unauthorised Access"}
    def get_blood_donation_event(self, blood_donation_event):
        db = get_connection()
        cursor = db.cursor()

        get_query = f"SELECT Drive_id,Name,Date_of_event,\
        Venue,Operator_id FROM BLOOD_DONATION_EVENT WHERE Drive_id = {blood_donation_event['Drive_id']} \
                        AND Operator_id = {blood_donation_event['Operator_id']}"

        try:
            cursor.execute(get_query)
            result = cursor.fetchone()
            date = result[2].strftime('%Y-%m-%d')
            event = {
                "Drive_id": result[0],
                "Name": result[1],
                "Date_of_event": date,
                "Venue": result[3],
                "Operator_id": result[4]
            }
            db.commit()
            return {"status": 200, "entry": event}
        except mysql.Error as err:
            print(
                "Failed to fetch the blood donation event details : {}".format(
                    err))
            return {"status": 400, "entry": str(err)}
        finally:
            db.close()
Ejemplo n.º 20
0
    def get_color_filter():
        """
        상품 등록 - 컬러 필터 API [GET]
        작성자: 이예은

        Args:

        [Header]
        Authorization : 로그인 토큰

        Returns:
        response  : 컬러 필터 ID, 이름(영/한), 이미지 url
        code      : 200
        """

        db_connection = None

        try:
            db_connection = get_connection()
            if db_connection:
                color_filter = product_service.registration_page_color_filter(
                    db_connection)

                return {'color_filters': color_filter}, 200

        finally:
            if db_connection:
                db_connection.close()
Ejemplo n.º 21
0
    def get(self, q):
        """
        NAV/SIDE_BAR 카테고리리스트 - Presentation Layer(View) function
        Args:
            service: 서비스 레이어 객체
            q      : 쿼리파라미터(셀러속성아이디)
        Returns:
            200:    
                쿼리파라미터에 해당되는 카테고리 JSONDATA
            400:
                {message : 모든 레이어에서 레이즈된 에러메시지}
        Author:
            김기욱([email protected])
        History:
            2020-09-25(김기욱) : 초기 생성
        """
        try:
            db = get_connection()
            category_set = self.service.get_category_set(q, db)

        except Exception as e:
            return jsonify({'message': f'{e}'}), 400

        else:
            return jsonify(category_set), 200

        finally:
            db.close()
Ejemplo n.º 22
0
    def get_product_options(*args):
        """
        주문 리스트
        Args:
            product_id     : 상품 아이디
        Returns:

        Authors:
            [email protected](최지선)
        
        History:
            2020.11.08(최지선) : 초기 생성
        """
        try:
            db_connection = get_connection()
            product = {'product_id': args[0]}
            product_options = order_service.get_product_option_lists(
                db_connection, product)
            return jsonify(product_options), 200

        except OutofStockError as e:
            db_connection.rollback()
            message = internal_code_sheet[e.code]
            return jsonify(message), (message['code'])

        except Exception as e:
            db_connection.rollback()
            return jsonify({'error': f'{e}'}), 500

        finally:
            db_connection.close()
Ejemplo n.º 23
0
    def get(self, product_id):
        """
        상품 상세페이지 - Presentation Layer(View) function
        Args:
            service    : 서비스 레이어 객체
            product_id : 상품아이디
        Returns:
            200:    
                상품상세 JSONDATA
            400:
                {message : 모든 레이어에서 레이즈된 에러메시지}
        Author:
            김기욱([email protected])
        History:
            2020-09-29(김기욱) : 초기 생성
        """
        try:
            db = get_connection()
            product = self.service.get_product(product_id, db)

        except Exception as e:
            return jsonify({'message': f'{e}'}), 400

        else:
            return jsonify(product), 200

        finally:
            db.close()
Ejemplo n.º 24
0
    def get(self):
        """
        메인페이지 상품리스트 - Presentation Layer(View) function
        Args:
            service: 서비스 레이어 객체
        Returns:
            200:    
                할인률이 존재하는 상품 & 판매량 상위 상품들로 묶은 리스트 JSONDATA
            400:
                {message : 모든 레이어에서 레이즈된 에러메시지}
        Author:
            김기욱([email protected])
        History:
            2020-09-22(김기욱) : 초기 생성
        """
        try:
            db = get_connection()
            products = self.service.get_main_products(db)

        except Exception as e:
            return jsonify({'message': f'{e}'}), 400

        else:
            return jsonify({'data': products}), 200

        finally:
            db.close()
    def get_operator(self):
        db = get_connection()
        cursor = db.cursor()

        get_query = "SELECT opr.Operator_id,opr.Name, opr.Email,opr.Bbank_id,bb.Name \
                    FROM OPERATOR as opr join BLOOD_BANK as bb on (bb.Bbank_id=opr.Bbank_id)"

        try:
            cursor.execute(get_query)
            result = cursor.fetchall()
            operator_list = []
            for row in result:
                operator_list.append({
                    "Operator_id": row[0],
                    "Name": row[1],
                    "Email": row[2],
                    "Bbank_id": row[3],
                    "Bbank_Name": row[4]
                })
            db.commit()
            return {"status": 200, "operator_list": operator_list}
        except mysql.Error as err:
            print("Failed to fetch the operator details : {}".format(err))
            return {"status": 400, "entry": str(err)}
        finally:
            db.close()
 def update_operator_email(self, operator_entry, Operator_id):
     if int(Operator_id) == operator_entry["Operator_id"]:
         if authenticate(operator_entry["old_Email"],
                         operator_entry["Password"]):
             db = get_connection()
             cursor = db.cursor()
             update_query = "update OPERATOR set Email=%s where Operator_id=%s"
             try:
                 cursor.execute(update_query,
                                (operator_entry["new_Email"],
                                 operator_entry["Operator_id"]))
                 db.commit()
                 return {
                     "status": 201,
                     "message": "Operator's email-id updated successfully"
                 }
             except mysql.Error as err:
                 print("Failed to update entry: {}".format(err))
                 return {"status": 500, "message": str(err)}
             finally:
                 db.close()
         else:
             return {"status": 401, "message": "Unauthorised Access"}
     else:
         return {"status": 401, "message": "Unauthorised Access"}
Ejemplo n.º 27
0
    def get_expired_units(self, parameters, Operator_id):
        parameters["Bbank_id"] = int(parameters["Bbank_id"])
        if Operator.check_bankid(Operator_id, parameters["Bbank_id"]):
            db = get_connection()
            cursor = db.cursor()
            select_query = "SELECT * FROM BLOOD WHERE Date_of_Expiry < CURDATE() AND Br_id IN \
                        (SELECT Br_id FROM BRANCH WHERE Bbank_id=%s)"

            try:
                cursor.execute(select_query, (parameters["Bbank_id"], ))
                result = cursor.fetchall()
                blood_units = []
                db.commit()
                for row in result:
                    blood_units.append({
                        'Blood_id': row[0],
                        'Blood_Group': row[1],
                        'Br_id': row[2],
                        'Special_Attributes': row[6],
                        'Donor_id': row[3],
                        'Donation_Date': row[4],
                        'Date_of_Expiry': row[5]
                    })

                return {"status": 200, "result": blood_units}
            except mysql.Error as err:
                print("Internal Server error: {}".format(err))
                return {"status": 500, "message": str(err)}
            finally:
                db.close()
        else:
            return {"status": 401, "message": "Unauthorised Access"}
Ejemplo n.º 28
0
    def get(self, product_id, seller_id):
        """
        상품 이력 조회 뷰

        Args:

        Returns:
            200: 
                SUCCESS: 상품 이력 리스트 리턴
            500:
                OperationalError: 데이터베이스 조작 에러
                InternalError   : 데이터베이스 내부 에러

        Author:
            이충희([email protected])

        History:
            2020-10-03(이충희): 초기 생성
        """
        try:
            conn = get_connection()

            # product_id = int(product_id)

            results = self.service.get_product_history(conn, product_id)

        except (err.OperationalError, err.InternalError) as e:
            message = {"errno": e.args[0], "errval": e.args[1]}
            return jsonify(message), 500

        else:
            return jsonify(results), 200
        finally:
            conn.close()
Ejemplo n.º 29
0
    def post(self, *args):
        """
        기본 로그인 API

        Args:
            seller_info{
                seller_account : 셀러 아이디
                password       : 패스워드
            }

        Retruns:
            200, {'access_token':access_token}

            400, {'message': 'UNSUCCESS'}

            400, {"errno": e.args[0], "errval": e.args[1]} : DB와 관련된 오류

            (   
                #IntegrityError : 데이터베이스의 관계형 무결성에서 발생하는 예외 (외래키 검사 실패, 중복키, 기타)
                #DataError : 0으로 나누기, 범위를 벗어난 숫자 값,기타
                #NotSupportedError : 메서드 또는 데이터베이스 API를 사용한 경우 예외 발생 데이터베이스에서 지원하지 않는 경우( 트랜잭션을 지원하지 않는 연결의 .rollback () 또는 거래가 해제)
                #OperationalError : 데이터베이스와 관련된 오류에 대해 예외, 예기치 않은 연결 해제가 발생하면 데이터 소스 이름이 발견, 트랜잭션을 처리 할 수 ​​없음, 메모리 할당 처리 중 오류
                #InternalError : 데이터베이스가 내부 오류, 예를 들어 커서가 더 이상 유효하지 않습니다. 트랜잭션이 동기화되지 않음 등
            )

        Authors:
            [email protected](이지연)
        
        History:(
            2020.09.23(이지연) : 초기 생성
            2020.09.24(이지연) : 수정
                                -> view에서 db commit하도록 변경, 에러 처리 추가
            2020.09.25(이지연)  : 유효성 검사 추가
            2020.09.28(이지연)  : 유효성 검사 customexception -> validationexception 변경
            2020.10.02(이지연)  : 모델링 변경 -> 하나의 셀러 테이블을 sellers와 seller_informations으로 나누고 로직 변경
            2020.10.08(이지연)  : 피드백 반영 팀원들과 형식 맞춰 수정
    """

        try:
            conn = connection.get_connection()
            seller_info = {'seller_account': args[0], 'password': args[1]}

            # 로그인 성공 시 access_token 생성 메소드 실행 -> 성공 x : INVALID_USER, INVALID_TOKEN
            access_token = self.service.sign_in(seller_info, conn)

        #DB 오류
        except (err.IntegrityError, err.DataError, err.NotSupportedError,
                err.OperationalError, err.InternalError) as e:
            traceback.print_exc()
            message = {"errno": e.args[0], "errval": e.args[1]}
            # (1054, "Unknown column 'seller_accounts' in 'field list'")
            return jsonify(message), 400
        #그 외 오류(컬럼명 오타 등)
        except Exception as e:
            traceback.print_exc()
            return jsonify({'message': 'UNSUCCESS'}), 400
        else:
            return jsonify({'access_token': access_token}), 200
        finally:
            conn.close()
Ejemplo n.º 30
0
    def get_option():
        """
        상품 등록 - 옵션 선택 API [GET]
        작성자: 이예은

        Args:

        [Header]
        Authorization : 로그인 토큰

        Returns:
        response : 옵션 색상 & 사이즈 id, 이름 ex) White, XL
        code     : 200
        """

        db_connection = None

        try:
            db_connection = get_connection()
            if db_connection:
                option_response = product_service.registration_page_options(
                    db_connection)

                return option_response

        finally:
            if db_connection:
                db_connection.close()
Ejemplo n.º 31
0
    def put(self, token_paylod):
        """
            상품 구매 취소하기 - Presentation Layer(view)) function
            Args : 
                token_paylod : 유저 엑세스 토큰
            Returns :

            Author :
                [email protected] (김태하)
            History:
                2020-10-12 ([email protected] (김태하)) : 초기 생성
        """
        try:
            db = get_connection()
            requestion = request.json
            order_cancellation = self.service.order_cancellation(
                token_paylod, requestion, db)
            if order_cancellation is False:
                db.rollback()
                return jsonify({'message': 'UNSUCCESS'}), 400

        except Exception as e:
            db.rollback()
            traceback.print_exc()
            return jsonify({'message': f'{e}'}), 400

        else:
            db.commit()
            return jsonify({'message': 'SUCCESS'}), 200

        finally:
            db.close()
Ejemplo n.º 32
0
    def post(self, token_paylod):
        """
            상품구매 - Presentation Layer(view)) function
            Args : 
                token_paylod : 유저 엑세스 토큰
            Returns :

            Author :
                [email protected] (김태하)
            History:
                2020-10-10 ([email protected] (김태하)) : 로직변경
                2020-10-05 ([email protected] (김태하)) : 초기생성
        """
        try:
            db = get_connection()
            requestion = request.json
            product_order = self.service.purchase(token_paylod, requestion, db)

            if product_order is True:
                db.commit()
                return jsonify({'message': 'SUCCESS'}), 200

            elif product_order is False:
                db.rollback()
                return jsonify({'message': 'UNSUCCESS'}), 400

        except Exception as e:
            traceback.print_exc()
            db.rollback()
            return jsonify({'message': f'{e}'}), 400

        finally:
            db.rollback()
            db.close()
Ejemplo n.º 33
0
 def connect(self):
     '''Connects to Monkey Farm'''
     config = get_connection(con_name='default')
     if config:
         rh = MFAPIKeyRequestHandler(config['url'])
         rh.auth(config['user'], config['api_key'])
         hub = MFInterface(request_handler=rh)
         return hub
     else:
         print 'It does not appear you have a ~/.mf.conf'
         sys.exit()
Ejemplo n.º 34
0
def getURL(filename):
    solr = connection.get_connection()
    queryURL = r'filename:(.)*' + filename

    output =  query.get(solr, constant.SOLR_CORE,  queryURL,1 )
    return output.result.dict['response']['docs'][0]['id']
Ejemplo n.º 35
0
import connection
from util import constant

def index(connection, collection, document):
    """
    Add the documents to the collection using the Solr connection.
    :param connection: the solr connection
    :param collection: the solr collection
    :param document: the documents to be index
    :return: Nothing
    """
    connection[collection].add(document)
    connection[collection].commit()

if __name__ == '__main__':
    connection = connection.get_connection()
    docs = [{"id":"1", "name":"a"},{"id":"2","name":"b"}]

    index(connection, constant.SOLR_CORE,docs)

Ejemplo n.º 36
0
def get(connection, collection, query, rows = -1):
    """
    Getting the data from collection matching the query
    :param connection: the Solr Connection
    :param collection: the Solr Collection
    :param query: Solr Query
    :param rows: number of rows to return
    :return: the list of documents returned by Solr
    """
    if rows == -1:
        return connection[collection].search({'q':query})
    else:
        return connection[collection].search({'q':query,'rows': rows})

def getCount(connection, collection, query):
    """
    Get only the number of documents from the collection matching the query
    :param connection: the Solr Connection
    :param collection: the Solr Collection
    :param query: Solr Query
    :return: the number of documents matched
    """
    docs = connection[collection].search({'q':query, 'rows': 0})
    return docs.result.response.numFound

if __name__ == '__main__':
    solr = connection.get_connection()
    print getCount(solr, 'zomato_reviews','*:*')


Ejemplo n.º 37
0
 def testConnection(self):
     new_con = connection.get_connection()
     self.assert_(type(new_con)==connection.Connection, 'this is not as pymongo object')
Ejemplo n.º 38
0
            create_tables(cursor, table_dir)

        ingest_file = version_dir + os.sep + "ingest" + os.sep + "execute.py"
        if os.path.exists(ingest_file):
            execute = imp.load_source('execute', ingest_file)
            execute.update(cursor, os.path.dirname(ingest_file))

        scripts_file = version_dir + os.sep + "scripts" + os.sep + "execute.py"
        if os.path.exists(scripts_file):
            execute = imp.load_source('execute', scripts_file)
            execute.update(cursor, os.path.diranem(scripts_file))

        insert_row(cursor, "version", os.path.basename(version_dir), columns=["version"])
    except Exception as e:
        logging.critical(e)
        logging.warn("Rolling back")
        connection.rollback()
        raise
    else:
        if cursor is not None:
            logging.info("Committing. Updated to version %s" % version_dir)
            connection.commit()

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    if len(sys.argv) > 1 and sys.argv[1] == "test":
        connection = None
    else:
        connection = get_connection()
    update_database(connection)
Ejemplo n.º 39
0
    parser.add_option("-f", "--find", dest="find",
                      action='store_true', default=False,
                      help='Finds the tag associates with give lat lon.')

    parser.add_option("-q", "--query", dest="query",
                      action='store_true', default=False,
                      help='Finds all the locations within the radius')

    parser.add_option("-p", "--profile", dest="profile", default="default",
                      type="string", help="redis conf profile to use",
                      metavar="PROFILE")

    (options, args) = parser.parse_args()
    profile = options.profile
    redis_conn = get_connection(profile)

    _assert_length(args, 2, "Need 2 parameters at the minimum: lat lon")

    lat = float(args[0])
    lon = float(args[1])

    if options.update:
        _assert_length(args, 3, "Need 3 parameters for update: lat lon tag")
        tag = args[2]
        update(redis_conn, lat, lon, tag)

    elif options.find:
        find(redis_conn, lat, lon)

    elif options.query:
Ejemplo n.º 40
0
 def __get_s3_bucket(self):
     return Bucket(
         connection=get_connection(self.context),
         name=self._get_config('BUCKET')
     )
Ejemplo n.º 41
0
    def rbon_check(cls, user):
      con =  get_connection()
      print 'con' , con
      cur = con.cursor()
      print 'cur' , cur

      yesterday  =  date.today()-timedelta(days=1)
      last_week  = [ (yesterday - timedelta(days =d)).strftime('%d/%m/%Y')
                     for d in range(7)]
      last_month = [ (yesterday - timedelta(days=d)).strftime('%d/%m/%Y')
                     for d in range(30)]
      yesterday  = [  yesterday.strftime('%d/%m/%Y') ]
      print 'yesterday' , yesterday
      print 'last_month' , last_month
      print 'last_week' , last_week
    
      query ="""
            select  
            sum(cast(VCPLUS as integer)), sum(cast(VCMOIN as integer)),
            sum(cast(UPPLUS as integer)), sum(cast(UPMOIN as integer)),
            sum(cast(TOTAL as integer)), sum(cast(CA_Emission as integer)),
            sum(cast(RA_Appels_traites as integer))
            FROM Main_Rebons 
            where JOURNEE in (?)
            And upper(usercre) in ('#')
            group by usercre
      """
      out = {'user_yesterday':[], 'user_week':[],'user_month':[]}
      
      for list , flag in  [(last_week , 'user_week'), (last_month , 'user_month'), (yesterday, 'user_yesterday')]:
            query2  = query.replace('?', ",".join(
                            map( lambda e: "'%s'"%e , list)))
            #query2  = query2.replace('#' , user.username)
            query2  = query2.replace('#' , 'PCCI87')
            print query2
            cur.execute(query2)
            out[flag]  = cur.fetchall()
            
      # The best
      
      
      query ="""
            select  
            sum(cast(VCPLUS as integer)), sum(cast(VCMOIN as integer)),
            sum(cast(UPPLUS as integer)), sum(cast(UPMOIN as integer)),
            sum(cast(TOTAL as integer)), sum(cast(CA_Emission as integer)),
            sum(cast(RA_Appels_traites as integer))
            FROM Main_Rebons 
            where JOURNEE in (?)
            group by usercre
            order by  sum(cast(TOTAL as integer)) desc
      """
      out2 = {'max_yesterday':[], 'max_week':[],'max_month':[]}
      
      for list , flag in  [(last_week , 'max_week'), (last_month , 'max_month'), (yesterday, 'max_yesterday')]:
            query2  = query.replace('?', ",".join(
                            map( lambda e: "'%s'"%e,list )))
            query2  = query2.replace('#' , user.username)
            print query2
            cur.execute(query2)
            out2[flag]  = [cur.fetchall()[0]]
      return out, out2