Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- MySQL
- sqlite
- IOS
- mssql
- Linux
- javascript
- 맛집
- tensorflow
- 날짜
- python
- flutter
- Excel
- node.js
- ASP
- 리눅스
- MS-SQL
- urllib
- PyQt
- 유니티
- port
- 라즈베리파이
- 다이어트
- swift
- PyQt5
- GIT
- ubuntu
- Unity
- 함수
- pandas
- PER
Archives
아미(아름다운미소)
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' 카테고리의 다른 글
pandas 날짜차이 분으로 환산 (0) | 2024.06.24 |
---|---|
fastapi mysql crud & javascript & flutter 예제 (0) | 2024.06.22 |
python mysql dbhelper (0) | 2024.06.22 |
pandas lamda 예제 (0) | 2024.06.22 |
람다 함수로 사용자함수에 여러개 파라미터 전달하는 방법은? (0) | 2024.06.22 |
Comments