Esempio n. 1
0
    def get(self, user_id):

        # 토큰에서 유저 아이디 가져온다.
        token_user_id = get_jwt_identity()

        if token_user_id != user_id:
            return {'err_code': 1}, HTTPStatus.UNAUTHORIZED

        # 1. 데이터베이스에서 쿼리해서 유저정보 가져온다.
        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)

        query = """ select u.email, u.name, u.gender, m.title, r.rating
                    from rating r
                    join movie m on m.id = r.item_id
                    join movie_user u on u.id = r.user_id
                    where u.id = %s; """

        param = (user_id, )

        cursor.execute(query, param)
        records = cursor.fetchall()

        cursor.close()
        connection.close()

        # 2. 유저정보 없으면, 클라이언트에 유저정보 없다고 리턴
        if len(records) == 0:
            return {'err_code': 2}, HTTPStatus.BAD_REQUEST

        # 3. 있으면, 해당유저 정보를 리턴
        else:
            return {'ret': records}, HTTPStatus.OK
    def delete(self, recipe_id) :

        connection = get_mysql_connection()

        cursor = connection.cursor(dictionary=True)

        # 먼저, 인증토큰에서 유저아이디를 빼온다.
        user_id = get_jwt_identity()
        # 데이터베이스에 저장된 유저아이디와 같은지 비교한다.
        query = """ select * from recipe where id = %s; """ 
        param = (recipe_id, )
        cursor.execute(query, param)
        records = cursor.fetchall()
        
        if len(records) == 0 :
            return {'err_code': 1}, HTTPStatus.BAD_REQUEST
        if user_id != records[0]['user_id'] :
            return {'err_code' :2}, HTTPStatus.UNAUTHORIZED


        query = """ delete from recipe where id = %s; """

        param = (recipe_id , )

        cursor.execute(query, param)

        connection.commit()

        cursor.close()
        connection.close()

        return {}, HTTPStatus.OK
    def get(self) :
        # recipe 테이블에 저장되어 있는 모든 레시피 정보를 가져오는 함수

        # 1. DB 커넥션을 가져온다.
        connection = get_mysql_connection()

        print(connection)

        # 2. 커넥션에서 커서를 가져온다.
        cursor = connection.cursor(dictionary=True)

        # 3. 쿼리문을 작성한다.
        query = """select * from recipe;"""

        # 4. sql 실행
        cursor.execute(query)

        # 5. 데이터를 페치한다.         
        records = cursor.fetchall()

        print(records)

        ret = []
        for row in records :
            row['created_at'] = row['created_at'].isoformat()
            row['updated_at'] = row['updated_at'].isoformat()
            ret.append(row)

        # 6. 커서와 커넥션을 닫아준다.
        cursor.close()
        connection.close()

        # 7. 클라언트에 리스판스 한다.
        return {'count' : len(ret), 'ret' : ret}, HTTPStatus.OK
    def get(self, recipe_id):
        # 1. 경로의 붙어있는 값을 가져와야한다.(레시피 아이디)
        # 위의 get 함수에 변수로 받아온다.

        # 2. 디비 커넥션을 가져온다.
        connection = get_mysql_connection()
        # 3. 커서 가져온다
        cursor = connection.cursor(dictionary=True)
        # 4. 쿼리문 만든다.
        query = '''select *
                    from recipe
                    where id = %s; '''
        param = (recipe_id, )
        # 5. 쿼리 실행
        cursor.execute(query, param)

        records = cursor.fetchall()
        # 6. 자원해제
        cursor.close()
        connection.close()
        # 7. 클라이언트에게 리스판스

        if len(records) == 0:
            return {'message': 'not exite'}, HTTPStatus.Error

        ret = []
        for row in records:
            row['created_at'] = row['created_at'].isoformat()
            row['updated_at'] = row['updated_at'].isoformat()
            ret.append(row)

        return {'count': len(ret), 'ret': ret[0]}, HTTPStatus.OK
    def delete(self, recipe_id):
        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)

        ## 유저 아이디가 이 레시피 만든 유저가 맞는지 확인해 봐야한다.
        user_id = get_jwt_identity()  #헤더의 인증토큰을 가져온다.

        query = ''' select user_id from recipe 
                    where id = %s;'''

        param = (recipe_id, )

        cursor.execute(query, param)
        records = cursor.fetchall()

        if len(records) == 0:
            return {'err_code': "Not exist recipe."}, HTTPStatus.BAD_REQUEST

        if user_id != records[0]['user_id']:
            return {'err_code': '지울 수 있는 권한이 없다.'}, HTTPStatus.NOT_ACCEPTABLE

        query = '''delete from recipe
                    where id = %s;'''
        param = (recipe_id, )
        cursor.execute(query, param)
        connection.commit()

        cursor.close()
        connection.close()

        return {'message': 'success remove'}, HTTPStatus.OK
    def get(self, user_id):

        # 데이터 베이스에서 유저 아이디의 정보
        # /users/<int:user_id>/my => UserResource Get
        # id,email. username, is_active 이 3개 정보를 클라이언트에 응답

        # 토큰에서 유저아이디를 가져온다.
        token_user_id = get_jwt_identity()

        if user_id != token_user_id:
            return {
                'err_code': 'Please login your ID'
            }, HTTPStatus.UNAUTHORIZED

        # 데이터 베이스 연결
        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)
        # 쿼리문
        query = '''select id, email, username, is_active from user 
                where id = %s ;'''
        param = (user_id, )
        # 쿼리문 실행
        cursor.execute(query, param)
        records = cursor.fetchall()

        # 닫기
        cursor.close()
        connection.close()

        # print(records)
        # 유저 정보 리턴
        if len(records) == 0:
            return {'err_code': 1}, HTTPStatus.BAD_REQUEST
        else:
            return {"massage": records[0]}, HTTPStatus.OK
    def get(self):
        # 1. DB커넥션 가져오기
        connection = get_mysql_connection()
        print('커넥트 성공')
        # 2. 커서
        cursor = connection.cursor(dictionary=True)
        print('커서연결')
        # 3. 쿼리문
        query = """ select * from recipe; """
        # 4. sql 실행
        cursor.execute(query)

        # 5. 데이터를 페치한다.
        records = cursor.fetchall()

        print(records)

        ret = []
        for row in records:
            row['created_at'] = row['created_at'].isoformat()
            row['updated_at'] = row['updated_at'].isoformat()
            ret.append(row)

        # 6. 커서와 커넥션을 닫아 준다.
        cursor.close()
        connection.close()

        # 7. 클라이언트에 리스판스 한다.
        return {'test': 'hello', 'count': len(ret), 'ret': ret}, HTTPStatus.OK
    def post(self):
        # 1. 클라이언트가 요청한 request의 body에 있는 json 데이터를 가져오기
        data = request.get_json()

        # 2. 필수 항목이 있는지 체크
        if 'rating' not in data:
            return {'message': '필수값이 없습니다.'}, HTTPStatus.BAD_REQUEST

        # JWT 인증토큰에서 유저아이디 뽑아온다.
        user_id = get_jwt_identity()

        # 3. 데이터베이스 커넥션 연결
        connection = get_mysql_connection()

        # 4. 커서 가져오기
        cursor = connection.cursor(dictionary=True)

        # 5. 쿼리문 만들기
        query = """insert into rating(rating, item_id, user_id)
                    values (%s, %s, %s);"""

        param = (data['rating'], data['item_id'], user_id)

        # 6. 쿼리문 실행
        c_result = cursor.execute(query, param)
        print(c_result)

        connection.commit()

        # 7. 커서와 커넥션 닫기
        cursor.close()
        connection.close()

        # 8. 클라이언트에 response 하기
        return {'err_code': 0}, HTTPStatus.OK
Esempio n. 9
0
    def get(self, user_id):

        # 토큰에서 유저 아이디 가져온다.
        token_user_id = get_jwt_identity()

        if token_user_id != user_id:
            return {'err_code': 1}, HTTPStatus.UNAUTHORIZED

        # 1. 데이터베이스에서 쿼리해서 유저정보 가져온다.
        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)
        query = """select id, username, email, is_active
                    from user where id = %s; """
        param = (user_id, )
        cursor.execute(query, param)
        records = cursor.fetchall()

        cursor.close()
        connection.close()
        # 2. 유저정보 없으면, 클라이언트에 유저정보 없다고 리턴
        if len(records) == 0:
            return {'err_code': 1}, HTTPStatus.BAD_REQUEST
        # 3. 있으면, 해당 유저 정보를 리턴.
        else:
            return {'ret': records[0]}, HTTPStatus.OK
Esempio n. 10
0
    def post(self):
        data = request.get_json()

        # 0. 데이터가 전부 다 있는지 체크
        if 'username' not in data or 'email' not in data or 'password' not in data:
            return {'err_code': 1}, HTTPStatus.BAD_REQUEST

        # 1. 이메일 유효한지 체크
        try:
            # Validate.
            validate_email(data['email'])

        except EmailNotValidError as e:
            # email is not valid, exception message is human-readable
            print(str(e))
            return {'err_code': 3}, HTTPStatus.BAD_REQUEST

        # 2. 비밀번호 길이체크 및 암호화
        if len(data['password']) < 4 or len(data['password']) > 16:
            return {'err_code': 2}, HTTPStatus.BAD_REQUEST

        password = hash_password(data['password'])

        print(password)

        # 3. 데이터베이스에 저장.

        ## 실습. 디비에 데이터 인서트 시, 유니크로 인해서 데이터가
        #  들어가지 않는 경우를 대비하여, 코드를 수정하세요.

        try:

            connection = get_mysql_connection()
            cursor = connection.cursor()
            query = """ insert into user
                        (username, email, password)
                        values ( %s, %s, %s );"""
            param = (data['username'], data['email'], password)

            cursor.execute(query, param)
            connection.commit()

            # 디비에 데이터를 저장한 후, 저장된 아이디값을 받아온다.
            user_id = cursor.lastrowid  # cursor.getlastrowid()
            print(user_id)

        except Error as e:
            print(str(e))
            return {'err_code': 4}, HTTPStatus.NOT_ACCEPTABLE

        cursor.close()
        connection.close()

        # JWT 를 이용해서 인증토큰을 생성해 준다.
        access_token = create_access_token(identity=user_id)

        return {'token': access_token}, HTTPStatus.OK
Esempio n. 11
0
 def delete(self, recipe_id) : 
     connection = get_mysql_connection()
     cursor = connection.cursor()
     query = """ update recipe set is_publish = 0 where id = %s ; """
     param = (recipe_id, )
     cursor.execute(query, param)
     connection.commit()
     cursor.close()
     connection.close()
     return {}, HTTPStatus.OK
    def post(self):
        data = request.get_json()

        # 오류 체크
        if "username" not in data or "email" not in data or "password" not in data:
            return {'error_code': 1}, HTTPStatus.BAD_REQUEST

        # 1. 이메일 유효한지 체크
        try:
            # Validate.
            valid = validate_email(data['email'])

        except EmailNotValidError as e:
            # email is not valid, exception message is human-readable
            print(str(e))
            return {'error_code': 3}, HTTPStatus.BAD_REQUEST

        # 2. 비밀 번호 암호화
        if len(data["password"]) < 4 or len(data["password"]) > 10:
            return {'error_code': 2}, HTTPStatus.BAD_REQUEST

        password = hash_passwd(data['password'])
        print(password)

        # 3. 데이터 베이스에 저장
        try:
            connection = get_mysql_connection()
            cursor = connection.cursor()
            query = ''' insert into user(username, email, password)
                        values (%s, %s, %s);'''
            param = (data['username'], data['email'], password)

            cursor.execute(query, param)
            connection.commit()
            # print('------------------확인용 -----------------')
            user_id = cursor.lastrowid

            print(user_id)

        except Error as e:
            print(e)
            return {'error_code': "{}".format(e)}

        finally:
            cursor.close()
            connection.close()

        access_token = create_access_token(identity=user_id)

        return {'token': access_token}, HTTPStatus.OK
Esempio n. 13
0
    def post(self):

        # 1. 클라이언트로부터 이메일과 비밀번호를 받아온다.
        data = request.get_json()
        if 'email' not in data or 'password' not in data:
            return {'err_code': 1}, HTTPStatus.BAD_REQUEST

        # 2. 이메일 벨리데이션 체크
        try:
            validate_email(data['email'])

        except EmailNotValidError as e:
            print(str(e))
            return {'err_code': 2}, HTTPStatus.BAD_REQUEST

        # 3. 비밀번호가 맞는지 체크하기 위해서 데이터 베이스에서 위의 이메일로
        #    유저 정보를 가져온다. (select)
        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)
        query = """select id, password from yhdb.movie_user
                    where email = %s;"""

        param = (data['email'], )

        cursor.execute(query, param)
        records = cursor.fetchall()
        print(records)

        # 3-1. 회원가입이 안된 이메일로 요청했을때는, record에 데이터가 없으니까
        #      클라이언트에게 응답한다.
        if len(records) == 0:
            return {'err_code': 3}, HTTPStatus.BAD_REQUEST

        # 4. 위에서 가져온 디비에 저장되어있는 비밀번호와, 클라이언트로부터
        #    받은 비밀번호를 암호화 한것과 비교한다.
        password = data['password']
        hashed = records[0]['password']
        ret = check_password(password, hashed)

        # 5. 같으면 클라이언트에 200 리턴
        if ret is True:

            user_id = records[0]['id']
            access_token = create_access_token(identity=user_id)

            return {'token': access_token}, HTTPStatus.OK

        # 6. 다르면, 에러 리턴
        else:
            return {'err_code': 4}, HTTPStatus.BAD_REQUEST
    def post(self):
        data = request.get_json()
        print(data)
        if "email" not in data or "password" not in data:
            return {
                'error_code': "input your password or email"
            }, HTTPStatus.BAD_REQUEST

        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)

        try:
            # Validate.
            valid = validate_email(data['email'])

        except EmailNotValidError as e:
            # email is not valid, exception message is human-readable
            print(str(e))
            return {'error_code': 'not valid email'}, HTTPStatus.BAD_REQUEST

        query = '''select id, password
                    from user
                    where email = %s;'''

        param = (data['email'], )

        cursor.execute(query, param)
        records = cursor.fetchall()

        if records == []:
            return {'error_code': 'not exist email'}

        cursor.close()
        connection.close()

        # JWT를 이용해서 인증토큰을 생성해 준다.

        password = check_passwd(data['password'], records[0]['password'])
        if password is True:

            user_id = records[0]['id']
            access_token = create_access_token(identity=user_id)

            return {
                'message': 'access login',
                'token': access_token
            }, HTTPStatus.OK
        else:
            return {'message': 'wrong password'}, HTTPStatus.BAD_REQUEST
Esempio n. 15
0
    def get(self, recipe_id) :
        # localhost:5000/recipes/1
        # 1. 경로에 붙어있는 값(레시피테이블의 아이디)을 가져와야 한다.
        # 위의 get 함수의 파라미터로 지정해준다.
        # 따라서 recipe_id 에 값이 들어있다.

        # 2. 디비 커넥션 가져온다.
        connection = get_mysql_connection()

        # 3. 커서 가져오고
        cursor = connection.cursor(dictionary=True)

        # 4. 쿼리문 만들고
        # query = """ select 
        #             name,description,num_of_servings, cook_time,
        #             directions,is_publish, 
        #             date_format(created_at, '%Y-%m-%d %H:%i:%S') as created_at,
        #             date_format(updated_at, '%Y-%m-%d %H:%i:%S') as updated_at
        #             from recipe where id = %s ; """

        query = """ select 
                    name,description,num_of_servings, cook_time,
                    directions,is_publish, 
                    date_format(created_at, '%Y-%m-%d %T') as created_at,
                    date_format(updated_at, '%Y-%m-%d %T') as updated_at
                    from recipe where id = %s ; """
        param = (recipe_id,)

        # 5. 쿼리 실행
        cursor.execute(query, param)

        records = cursor.fetchall()

        # 6. 커서, 커넥션 닫기.
        cursor.close()
        connection.close()
        
        # 7. 실행 결과를 클라이언트에 보내준다.

        if len(records) == 0 :
            return {'message':'패스로 셋팅한 레시피 아이디는 없다.'}, HTTPStatus.BAD_REQUEST

        # result = []
        # for row in records :
        #     row['created_at'] = row['created_at'].isoformat()
        #     row['updated_at'] = row['updated_at'].isoformat()
        #     result.append(row)

        return {'count' : len(records), 'ret' : records[0]} 
    def put(self, recipe_id):
        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)
        query = '''update recipe 
                    set is_publish = 1
                    where id = %s;'''

        param = (recipe_id, )
        cursor.execute(query, param)
        connection.commit()

        cursor.close()
        connection.close()

        return {}, HTTPStatus.OK
    def delete(self, recipe_id):
        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)
        query = '''update recipe 
                    set is_publish = 0
                    where id = %s;'''
        param = (recipe_id, )
        cursor.execute(query, param)
        connection.commit()

        cursor.close()
        connection.close()

        return {}, HTTPStatus.OK


# 실습. 레시피 삭제 API에 , 인증 토큰 적용해서
# 레세피를 작성한 유저만, 레시피를 삭제할 수 있게 변경
Esempio n. 18
0
    def post(self) :
        # 1. 클라이언트가 요청한 request의 body 에 있는 
        # json 데이터를 가져오기

        #{ "name" : "된장찌게" ,  "description" : "된장찌게 끓이는 법", "num_of_servings":0,
        # "cook_time" : 40, "directions" : "물을 먼저 붓고, 맛있게 끓이세요. 두부도 넣으세요.", 
        # "is_publish" : 0 }
        
        data = request.get_json()
        
        # 2. 필수 항목이 있는지 체크
        if 'name' not in data :
            return {'message':'필수값이 없습니다.'} , HTTPStatus.BAD_REQUEST

        # JWT 인증토큰에서 유저아이디 뽑아온다.
        user_id = get_jwt_identity()
        
        # 3. 데이터베이스 커넥션 연결
        connection = get_mysql_connection()

        # 4. 커서 가져오기
        cursor = connection.cursor(dictionary=True)

        # 5. 쿼리문 만들기
        query = """ insert into recipe (name, description, num_of_servings, 
                                        cook_time, directions, is_publish, user_id)
                    values (%s, %s, %s, %s, %s, %s, %s); """
        param = ( data['name'], data['description'], data['num_of_servings'], data['cook_time'], data['directions'], data['is_publish'], user_id )

        # 6. 쿼리문 실행
        c_result = cursor.execute(query, param)
        print(c_result)

        connection.commit()

        # 7. 커서와 커넥션 닫기

        cursor.close()
        connection.close()

        # 8. 클라이언트에 reponse 하기

        return {'err_code':0}, HTTPStatus.OK
    def post(self):
        # 1. 클라이언트가 요청한 reuest의 바디에 있는 json데이터 가져오기
        data = request.get_json()
        # print(data)
        # 2. 필수항목 있는지 체크
        key = [
            'name', 'description', 'num_of_servings', 'cook_time',
            'directions', 'is_publish'
        ]
        for i in key:
            if i not in data:  #예외 처리를 잘해야 꼼꼼한 코딩이다.
                return {
                    'message': ' {} input right message'.format(i)
                }, HTTPStatus.BAD_REQUEST

        ## JWT 인증토큰에서 유저아이디를 뽑아낸다.
        user_id = get_jwt_identity()
        print('------------------------------------')
        print(user_id)

        # 3. 데이터 베이스 커넥션 연결
        connection = get_mysql_connection()
        # 4. 커서 가져오기
        cursor = connection.cursor(dictionary=True)
        # 5. 쿼리문 만들기
        query = """ insert into recipe(name, description, num_of_servings, cook_time, directions, is_publish, user_id)
                    values(%s,%s,%s,%s,%s,%s,%s);   """

        param = [
            data["name"], data['description'], data['num_of_servings'],
            data['cook_time'], data['directions'], data['is_publish'], user_id
        ]

        # 6. 쿼리문 실행
        cursor.execute(query, param)
        connection.commit()
        # 7. 커서와 커넥션 닫기
        cursor.close()
        connection.close()
        # 8. 클라이언트에 리스판스
        return {'message': 0}, HTTPStatus.OK
    def get(self):

        # movie 테이블에 저장되어 있는 정보를 검색해서 가져오는 함수
        # 1. DB 커넥션을 가져온다.
        data = request.get_json()

        if 'title' not in data:
            return {'message': 'Parmeter Error'}, HTTPStatus.BAD_REQUEST

        connection = get_mysql_connection()

        print(connection)

        # 2. 커넥션에서 커서를 가져온다.
        cursor = connection.cursor(dictionary=True)

        # 3. 쿼리문을 작성한다.
        query = """select u.name, u.gender, r.rating
                   from rating r
                   join movie_user u on r.user_id = u.id
                   join movie m on m.id = r.item_id
                   where m.title = %s limit %s, 25;"""

        param = (data['title'], data['offset'])
        # 4. SQL 실행
        cursor.execute(query, param)

        # 5. 데이터를 페치한다.
        records = cursor.fetchall()

        # 6. 커서와 커넥션을 닫아준다.
        cursor.close()
        connection.close()

        # 7. 클라이언트에 리스폰스 한다.
        if len(records) == 0:
            return {'message': 'Title name error'}, HTTPStatus.NOT_FOUND
        else:
            return {'ret': records}, HTTPStatus.OK
    def put(self, recipe_id):
        data = request.get_json()
        print(data)

        if 'cook_time' not in data or 'directions' not in data:
            return {"err_code": "wrong parameter"}, HTTPStatus.BAD_REQUEST

        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)

        ## 유저 아이디가 이 레시피 만든 유저가 맞는지 확인해 봐야한다.
        user_id = get_jwt_identity()  #헤더의 인증토큰을 가져온다.

        query = ''' select user_id from recipe 
                    where id = %s;'''

        param = (recipe_id, )

        cursor.execute(query, param)
        records = cursor.fetchall()
        if len(records) == 0:
            return {'err_code': "Not exist recipe."}, HTTPStatus.BAD_REQUEST

        if user_id != records[0]['user_id']:
            return {'err_code': '바꿀 수 있는 권한이 없다.'}, HTTPStatus.NOT_ACCEPTABLE

        # 업데이트 쿼리
        query = '''update recipe 
                    set cook_time = %s, directions = %s
                    where id = %s;'''

        param = (data['cook_time'], data['directions'], recipe_id)
        cursor.execute(query, param)
        connection.commit()

        cursor.close()
        connection.close()

        return {"message": "success"}, HTTPStatus.OK
    def get(self):
        # 영화 리뷰를 작성하기 위한 영화 정보를 검색하는 함수
        # 1. DB 커넥션을 가져온다.
        data = request.get_json()

        if 'title' not in data:
            return {'message': 'Parmeter Error'}, HTTPStatus.BAD_REQUEST

        connection = get_mysql_connection()

        print(connection)

        # 2. 커넥션에서 커서를 가져온다.
        cursor = connection.cursor(dictionary=True)

        # 3. 쿼리문을 작성한다.
        query = """select m.id, m.title, count(r.rating) as reviews, round(avg(r.rating),2) as average
                    from rating r
                    join movie m on r.item_id = m.id
                    where m.title = %s
                    group by m.title;"""

        param = (data['title'], )
        # 4. SQL 실행
        cursor.execute(query, param)

        # 5. 데이터를 페치한다.
        records = cursor.fetchall()

        # 6. 커서와 커넥션을 닫아준다.
        cursor.close()
        connection.close()

        # 7. 클라이언트에 리스폰스 한다.
        if len(records) == 0:
            return {'message': 'Title name error'}
        else:
            return {'ret': records}, HTTPStatus.OK
    def get(self):
        # movie 테이블에 저장되어 있는 모든 정보를 정렬해서 가져오는 함수
        # 1. DB 커넥션을 가져온다.
        data = request.get_json()

        if 'order' not in data:
            return {'message': 'Parmeter error'}, HTTPStatus.BAD_REQUEST

        connection = get_mysql_connection()

        print(connection)

        # 2. 커넥션에서 커서를 가져온다.
        cursor = connection.cursor(dictionary=True)

        # 3. 쿼리문을 작성한다.
        query = """select m.title, count(r.rating) as reviews, round(avg(r.rating),2) as average
                    from rating r
                    join movie m on r.item_id = m.id
                    group by m.title 
                    order by %s desc
                    limit %s, 25;"""
        # print(data['order'])
        param = (data['order'], data['offset'])

        # 4. SQL 실행
        cursor.execute(query, param)

        # 5. 데이터를 페치한다.
        records = cursor.fetchall()

        # 6. 커서와 커넥션을 닫아준다.
        cursor.close()
        connection.close()

        # 7. 클라이언트에 리스폰스 한다.
        return {'ret': records}, HTTPStatus.OK
Esempio n. 24
0
    def put(self, recipe_id) :        
        # 업데이트 함수 작성.
        # cook_time과 directions 만 업데이트 할수 있도록 해주세요.
        # cook_time과 directions 은 필수값입니다.
        data = request.get_json()
        if 'cook_time' not in data or 'directions' not in data :
            return {'message':'파라미터 잘못됬습니다.'}, HTTPStatus.BAD_REQUEST

        # 커넥션 가져오기
        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary= True)

        # 유저아이디가, 이 레시피 만든 유저가 맞는지 확인해 봐야 한다.
        user_id = get_jwt_identity()
        
        query = """ select user_id from recipe where id = %s; """
        param = (recipe_id, )
        cursor.execute(query, param)
        records = cursor.fetchall()
        if len(records) == 0 :
            return {'err_code' : 1}, HTTPStatus.BAD_REQUEST
        
        if user_id != records[0]['user_id'] :
            return {'err_code' : 2}, HTTPStatus.NOT_ACCEPTABLE

        # 업데이트 쿼리
        query = """ update recipe 
                set cook_time = %s, directions = %s
                where id = %s;  """
        param = (data['cook_time'],data['directions'], recipe_id)
        cursor.execute(query, param)
        connection.commit()

        cursor.close()
        connection.close()

        return {}, HTTPStatus.OK
    def get(self, user_id):
        data = request.get_json()

        token_user_id = get_jwt_identity()

        if token_user_id != user_id:
            return {'err_code': 1}, HTTPStatus.UNAUTHORIZED

        connection = get_mysql_connection()

        cursor = connection.cursor(dictionary=True)

        query = """select m.title, r.rating
                    from rating r
                    join movie m on m.id = r.item_id
                    join movie_user u on u.id = r.user_id
                    where u.id = %s;"""

        param = (user_id, )

        cursor.execute(query, param)
        records = cursor.fetchall()

        records = DataFrame(records, columns=['title', 'rating'])
        print(records)

        movie_correlations = pd.read_csv('movie_correlations.csv')

        myRatings = records
        similar_movies_list = pd.DataFrame()
        for i in np.arange(0, len(myRatings)):
            movie_title = myRatings['title'][i]
            similar_movie = movie_correlations[myRatings['title'][i]].dropna(
            ).sort_values(ascending=False).to_frame()
            similar_movie.columns = ['Correlation']
            similar_movie['Weight'] = similar_movie['Correlation'] * myRatings[
                'rating'][i]
            similar_movies_list = similar_movies_list.append(similar_movie)
        result = similar_movies_list.sort_values('Weight',
                                                 ascending=False).head(10)
        result = result['Weight']
        # print(result)
        index = result.index.values
        # print(index[1])

        query = """select title from movie
                    where id = %s or id = %s or id = %s or id = %s or id = %s or id = %s or id = %s or id = %s or id = %s or id = %s;"""

        param = []
        for i in np.arange(0, len(index)):
            # print(index[i])
            param.append(index[i])

        param = [int(i) for i in param]

        # print(param)
        param = tuple(param)
        cursor.execute(query, param)
        records = cursor.fetchall()

        # print(result)
        result = result.to_frame()
        # print(result['Weight'])
        index = []
        for i in np.arange(0, len(records)):
            prob = records[i]['title']
            index.append(prob)

        ret = result.reindex()
        ret['Movie'] = index
        ret = ret[['Movie', 'Weight']]
        # print(ret)

        # 7. 커서와 커넥션 닫기
        ret = ret.to_json(orient='records')

        cursor.close()
        connection.close()

        # 8. 클라이언트에 response 하기
        return {'recommand': ret}, HTTPStatus.OK
Esempio n. 26
0
from flask import Flask
from flask_restful import Api
from db.db import get_mysql_connection
from config.config import Config
from resources.Racipe import RecipeListResource, RecipeResource, RecipePublishResource
from resources.user import User_List, UserResource, jwt_blocklist, UserLogoutResource

##JWT용 라이브러리
from flask_jwt_extended import JWTManager

import mysql.connector

app = Flask(__name__)

get_mysql_connection()
# 1. 환경변수 설정
app.config.from_object(Config)
## 1-1. JWT 환경 설정
jwt = JWTManager(app)


## 로그인/로그아웃 관리를 위한 jwt설정
@jwt.token_in_blocklist_loader
def check_if_token_is_revoked(jwt_header, jwt_payload):
    jti = jwt_payload['jti']
    return jti in jwt_blocklist


# 2. API설정

api = Api(app)