Notice
Recent Posts
Recent Comments
Link
아미(아름다운미소)
flask restapi mysql 예제 본문
from flask import Flask, jsonify, request
from dbhelper import DBHelper
app = Flask(__name__)
# DBHelper 인스턴스 생성
db = DBHelper(host='localhost', user='your_username', password='your_password', database='your_database')
db.connect()
# CRUD 엔드포인트
@app.route('/users', methods=['GET', 'POST'])
def users():
if request.method == 'GET':
# 사용자 목록 조회
users = db.read('users').fetchall()
return jsonify([dict(user) for user in users])
elif request.method == 'POST':
# 새 사용자 생성
data = request.get_json()
db.create('users', data)
return jsonify(data), 201
@app.route('/users/<int:user_id>', methods=['GET', 'PUT', 'DELETE'])
def user(user_id):
if request.method == 'GET':
# 특정 사용자 조회
user = db.read('users', {'id': user_id}).fetchone()
if user:
return jsonify(dict(user))
else:
return jsonify({'error': 'User not found'}), 404
elif request.method == 'PUT':
# 사용자 정보 업데이트
data = request.get_json()
db.update('users', data, {'id': user_id})
return jsonify(data)
elif request.method == 'DELETE':
# 사용자 삭제
db.delete('users', {'id': user_id})
return jsonify({'message': 'User deleted'}), 204
if __name__ == '__main__':
app.run(debug=True)
// 모든 사용자 목록 조회
fetch('/users')
.then(response => response.json())
.then(data => console.log(data));
// 새 사용자 생성
const newUser = { name: 'John Doe', email: 'john.doe@example.com' };
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
})
.then(response => response.json())
.then(data => console.log(data));
// 특정 사용자 정보 조회
const userId = 1;
fetch(`/users/${userId}`)
.then(response => response.json())
.then(data => console.log(data));
// 사용자 정보 업데이트
const updatedUser = { name: 'Jane Doe' };
fetch(`/users/${userId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(updatedUser)
})
.then(response => response.json())
.then(data => console.log(data));
// 사용자 삭제
fetch(`/users/${userId}`, {
method: 'DELETE'
})
.then(response => console.log(response.status));
'랭귀지 > python' 카테고리의 다른 글
HTTP v1 API를 사용하여 푸시 알림을 전송하는 샘플 코드 (0) | 2024.09.11 |
---|---|
미체결 날짜형식을 현재시간과 비교해서 1분 경과시 주문취소 (0) | 2024.08.25 |
python mysql dbhelper (0) | 2024.06.22 |
flake8 설정파일 (0) | 2024.06.14 |
CSRF란? (0) | 2022.10.15 |
Comments