티스토리 뷰

Mission 1. My New Assistant

한국형 자비스, 빅수비를 만들어보자.

 

Python Flask 프레임워크를 이용하여 구현

from flask import Flask, jsonify, request
from typing import List, Dict

app = Flask(__name__)

weapons: List[Dict] = []

@app.route('/weapon', methods=['POST'])
def create_weapon():
    data = request.json
    weapon = {
        'id': str(len(weapons) + 1),
        'name': data['name'],
        'stock': data['stock']
    }
    weapons.append(weapon)
    return jsonify(weapon), 201

@app.route('/weapon', methods=['GET'])
def get_weapons():
    return jsonify({'weapons': weapons})

@app.route('/weapon/<weapon_id>', methods=['GET'])
def get_weapon(weapon_id):
    weapon = next((w for w in weapons if w['id'] == weapon_id), None)
    if weapon:
        return jsonify(weapon)
    else:
        return jsonify({'message': 'Weapon not found'}), 404

@app.route('/weapon/<weapon_id>', methods=['PUT'])
def update_weapon(weapon_id):
    data = request.json
    weapon = next((w for w in weapons if w['id'] == weapon_id), None)
    if weapon:
        weapon['name'] = data.get('name', weapon['name'])
        weapon['stock'] = data.get('stock', weapon['stock'])
        return jsonify(weapon)
    else:
        return jsonify({'message': 'Weapon not found'}), 404

@app.route('/weapon/<weapon_id>', methods=['DELETE'])
def delete_weapon(weapon_id):
    global weapons
    weapons = [w for w in weapons if w['id'] != weapon_id]
    return '', 204

if __name__ == '__main__':
    app.run(debug=True)
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
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
글 보관함