@jwt_required()
def put(self, recipe_id):
# body에서 전달된 데이터를 처리
data = request.get_json()
user_id = get_jwt_identity()
# 디비 업데이트 실행코드
try:
# 데이터 업데이트
# 1. DB에 연결
connection = get_connection()
### 먼저 recipe_id에 들어있는 user_id가
### 이사람인지 먼저 확인한다.
query = '''select user_id
from recipe
where id = %s;'''
record = (recipe_id, )
cursor = connection.cursor(dictionary = True)
cursor.execute(query, record)
result_list = cursor.fetchall()
print(result_list)
if len(result_list) == 0:
cursor.close()
connection.close()
return {'error': '레시피 아이디가 잘못되었습니다'}, 400
recipe = result_list[0]
if recipe['user_id'] != user_id:
cursor.close()
connection.close()
return {'error':'남의 레시피를 수정할 수 없습니다.'}, 401
# 2. 쿼리문 만들기
query = '''update recipe
set name = %s, description = %s,
cook_time = %s,
directions = %s
where id = %s;'''
record = (data['name'], data['description'], data['cook_time'], data['directions'], recipe_id)
# 3. 커서를 가져온다.
cursor = connection.cursor()
# 4. 쿼리문을 커서를 이용해서 실행한다.
cursor.execute(query, record)
# 5. 커넥션을 커밋해줘야 한다 => 디비에 영구적으로 반영하라는 뜻
connection.commit()
# 6. 자원 해제
cursor.close()
connection.close()
except mysql.connector.Error as e:
print(e)
cursor.close()
connection.close()
return {'error':str(e)}, 503
return {'result':'sucess'}, 200
@jwt_required()를 함수 앞에 써주고 get_jwt_identity()를 통해 토큰을 받는다.
포스트맨에서 테스트해보려면
Header KEY에 Authoriztion을 넣고 VALUE에 Bearer 토큰 을 넣은다음 테스트하면 된다.
'REST API' 카테고리의 다른 글
Flask JWT 토큰 로그아웃 하기 (0) | 2022.06.21 |
---|---|
Flask 토큰 유효기간 만료 시키는 방법 (0) | 2022.06.20 |
Flask 회원가입/로그인 API에서, 토큰 생성해서 처리하는 방법 (0) | 2022.06.20 |
Flask에서 JWT 설치방법 (0) | 2022.06.20 |
포스트맨 사용법 (0) | 2022.06.17 |