728x90
전체적인 방식은 비슷하다. 다른점이 있으면 select 문은 cursor를 가져올때 파라미터에 dictionary=True를 넣어준다.
**** DB에서 셋팅한 timestamp는 파이썬에서 datetime으로 변환되지만 우리는 json을 이용해서 클라이언트에 데이터를 보내준다. datetime은 json으로 보낼 수 없기 때문에 시간을 문자열로 변환해서 보내준다.****
## 레시피 리스트 가져오는 함수
def get(self) :
# 1. 클라이언트로부터 데이터를 받아온다.
# 없다.
# 2. db에 저장된 데이터를 가져온다.
try :
connection = get_connection()
query = '''select * from recipe;'''
## 중요!!!! select 문은
## 커서를 가져올 때 dictionary = True로 해준다
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
result_list=cursor.fetchall()
print(result_list)
# 중요! DB에서 가져온 timestamp는
# 파이썬에서 datetime으로 자동 변환된다.
# 그런데 문제는 우리는 json으로
# 클라이언트한테 데이터를 보내줘야 하는데
# datetime은 json으로 보낼 수 없다.
# 따라서, 시간을 문자열로 변환해서 보내준다.
i = 0
for row in result_list :
result_list[i]['created_at'] = row['created_at'].isoformat()
result_list[i]['updated_at'] = row['updated_at'].isoformat()
i = i+1
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
728x90
'API 서버' 카테고리의 다른 글
API 서버 - python MySQL Connector를 이용해 delete 하는 방법 (0) | 2023.01.04 |
---|---|
API 서버 - python MySQL Connector를 이용해 update 하는 방법 (0) | 2023.01.04 |
API 서버 - python MySQL Connector를 이용해 insert 하는 방법 (1) | 2023.01.04 |
API 서버 - mysql과 서버 연동하기(connection) (0) | 2023.01.04 |
API 서버 - resource 만들기(class 사용) (0) | 2023.01.04 |