왕현성
코딩발자취
왕현성
전체 방문자
오늘
어제
  • 코딩 (277)
    • Python (71)
    • Java (16)
    • MySQL (34)
    • 인공지능 (48)
      • 머신러닝 (16)
      • 딥러닝 (32)
    • 영상처리 (4)
    • Rest API (21)
    • Android Studio (25)
    • streamlit (13)
    • DevOps (22)
      • AWS (9)
      • PuTTY (5)
      • Git (4)
      • Serverless (2)
      • Docker (2)
    • IT 기술 용어 (6)
    • 디버깅 ( 오류 해결 과정 ) (17)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 딥러닝
  • ComputerVision
  • imageprocessing
  • PYTHON
  • 영상처리
  • tune()
  • pytorch
  • UnboundLocalError
  • alibidetect
  • 영상기술
  • OpenCV
  • 컴퓨터비전
  • pip install labelme
  • 기상탐사
  • yolov8
  • maskimage
  • PIL
  • 의료이미징
  • labelme
  • get_long_description
  • unsupervised
  • encoding='utf-8'
  • numpy
  • TensorFlow
  • 영상처리역사
  • matplotlib
  • alibi-detection
  • ckpt_file
  • labelme UnocodeDecodeError
  • 비지도학습

최근 댓글

최근 글

티스토리

250x250
hELLO · Designed By 정상우.
왕현성

코딩발자취

Rest API

API 서버 - 로그인한 회원과 비회원 구분하여 시스템 개발하기 // jwt_required(optional= )

2023. 1. 10. 13:13
728x90
  • 해당 기능만을 서술한 포스팅으로, 전체 기능에 대한 소스 코드 확인은 깃허브에서 확인 가능합니다.
    https://github.com/hyunsungKR/movie_api_server
 

GitHub - hyunsungKR/movie_api_server

Contribute to hyunsungKR/movie_api_server development by creating an account on GitHub.

github.com

 

from flask import request
from flask_restful import Resource

from mysql_connection import get_connection
from mysql.connector import Error
from flask_jwt_extended import jwt_required
from flask_jwt_extended import get_jwt_identity

class MovieListResource(Resource) :
    # 비회원과 회원을 구분 ->> optional= 
    # 헤더가 있으면 유저아이디를 가져오고
    # 헤더가 없으면 None로 가져온다.
    @jwt_required(optional=True)
    def get(self) :
        user_id = get_jwt_identity()

        print("유저 아이디")
        print(user_id)


        order=request.args.get('order')
        offset=request.args.get('offset')
        limit=request.args.get('limit')

        try :
            connection = get_connection()
			# if 문으로 유저 아이디가 None이면 아래 코드로 그렇지 않으면 else: 아래의 코드로 실행
            if user_id is None :

                query = '''select m.id,m.title,ifnull(count(r.movie_id),0) as cnt,ifnull(avg(r.rating) , 0) as avg
                        from movie m
                        left join rating r
                        on r.movie_id = m.id
                        group by m.id
                        order by '''+order+''' desc
                        limit '''+offset+''','''+limit+''';'''

                cursor = connection.cursor(dictionary=True)

                cursor.execute(query)
            else :
            	# where를 사용하지 않고 join의 아래에 on의 뒤에 and f.user_id = %s로 변수처리를 해준다
                # where를 사용하면 DB에서 변수가 들어있는 데이터만 가져오지만 아래와같이 코드를 작성하면
                # user_id가 변수가 아닌 것은 null로 가져온다.
                query = '''select m.id,m.title,ifnull(count(r.movie_id),0) as cnt,
                        ifnull(avg(r.rating) , 0) as avg,if(f.user_id is null,0,1) as is_favorite
                        from movie m
                        left join rating r
                        on r.movie_id = m.id
                        left join favorite f
                        on m.id = f.movie_id and f.user_id = %s
                        group by m.id
                        order by '''+order+''' desc
                        limit '''+offset+''','''+limit+''';'''
                
                record = (user_id,)

                cursor = connection.cursor(dictionary=True)

                cursor.execute(query,record)


            result_list=cursor.fetchall()

            i = 0
            for row in result_list :
                result_list[i]['avg'] = float(row['avg'])
                i = i+1

            print(result_list)
            

            cursor.close()
            connection.close()
        except Error as e :
            print(e)
            cursor.close()
            connection.close()
            return{"result":"fail","error":str(e)}, 500
        


        return {"result" : 'seccess','items':result_list,'count':len(result_list)}, 200

'Rest API' 카테고리의 다른 글

AmazonRekognition을 사용하여 객체탐지(Object detection) / 자동 태그 API 개발  (0) 2023.01.13
AmazonRekognition을 사용하여 객체탐지(Object detection) API 개발  (0) 2023.01.12
API서버 - 실시간 추천 기능 구현  (0) 2023.01.10
API 서버 - 구글 코랩으로 추천기능 개발 이후 영화 추천하는 API 개발 ( 배포 )  (0) 2023.01.09
API 서버 - query string 페이징 처리  (0) 2023.01.06
    'Rest API' 카테고리의 다른 글
    • AmazonRekognition을 사용하여 객체탐지(Object detection) / 자동 태그 API 개발
    • AmazonRekognition을 사용하여 객체탐지(Object detection) API 개발
    • API서버 - 실시간 추천 기능 구현
    • API 서버 - 구글 코랩으로 추천기능 개발 이후 영화 추천하는 API 개발 ( 배포 )
    왕현성
    왕현성
    AI 머신비전 학습일지

    티스토리툴바