pip install flask
pip install flask-restful
pip install mysql-connector-python
미리 설치할 라이브러리
use mysql;
create user 'recipe_user'@'%' identified by '1q2w3e4r';
grant all on recipe_db.* to 'recipe_user'@'%';
먼저 특정 유저만 DB에 접속할 수 있도록 새로운 계정을 만듬.
import mysql.connector
def get_connection():
connection = mysql.connector. connect(
host = 'host.ctttsro2er9u.ap-northeast-2.rds.amazonaws.com',
database = 'recipe_db',
user = 'recipe_user',
password = '1q2w3e4r'
)
return connection
다음 파이썬 환경에서 새로운 py 파일을 만들어 위와 같은 함수를 만들어 놓음
위에서 만든 계정을 통해 특정 DB만 접속하도록 만든 것임.
app = Flask(__name__)
api = Api(app)
# 경로와 리소스(API 코드)를 연결한다.
api.add_resource(RecipeListResource, '/recipes')
api.add_resource(RecipeResource, '/recipes/<int:recipe_id>')
if __name__=='__main__':
app.run()
다음 메인 파일에서 class로 상속받아 리소스를 추가해준다.
파이썬으로 데이터베이스에 데이터 select하기
상속해준 class가 있는 파일로 와서
def get(self):
# 쿼리 스트링(URL에서 ?뒤에 있는 부분)으로 나오는 데이터는 아래처럼 처리해준다.
offset = request.args.get('offset')
limit = request.args.get('limit')
# DB로부터 데이터를 받아서, 클라이언트에 받아준다.
try :
connection = get_connection()
query = '''select *
from recipe
limit '''+offset+''', '''+limit+''';'''
# select 문은 dictionary = True 해준다.
cursor = connection.cursor(dictionary = True)
cursor.execute(query)
# select 문은, 아래 함수를 이용해서, 데이터를 가져온다.
result_list = cursor.fetchall()
print(result_list)
# 중요! 디비에서 가져온 timestamp 는
# 파이썬의 datetime 으로 자동 변경된다.
# 문제는! 이데이터를 json 으로 바로 보낼수 없으므로,
# 문자열로 바꿔서 다시 저장해서 보낸다.
i = 0
for record in result_list :
result_list[i]['created_at'] = record['created_at'].isoformat()
result_list[i]['updated_at'] = record['updated_at'].isoformat()
i = i + 1
cursor.close()
connection.close()
except mysql.connector.Error as e:
print(e)
cursor.close()
connection.close()
return {"result" : "success", "count" : len(result_list), "reult_list" : result_list[0]} , 200
다음과 같은 순서로 코드를 작성한다.
오프셋과 리미트를 이용해 데이터를 불러오는 코드이다.
그 후 서버를 실행한 후 포스트맨에서 원하는 주소로 Send 하면 된다.
해당 코드로 작성했을 시 결과에 succes와 코드 200, 그리고 원하는 데이터가 출력되면 정상적으로 입력된 것이다.
'Python' 카테고리의 다른 글
Python MySQL Connector를 이용해 delete하기 - delete메소드 (0) | 2022.06.19 |
---|---|
Python MySQL Connector를 이용해 update하기 - put 메소드 (0) | 2022.06.19 |
Python MySQL Connector를 이용해 insert 하기 - port 메소드 (0) | 2022.06.19 |
Restful API에 대해 (0) | 2022.06.19 |
Python Flask에서, Resource 클래스를 이용한 API 서버 개발하기 (0) | 2022.06.17 |
댓글