DAS_2024_1/alkin_ivan_lab_3/hero_service/main.py

52 lines
1.3 KiB
Python
Raw Normal View History

2024-12-12 22:44:53 +04:00
from flask import Flask, jsonify, request
import uuid
app = Flask(__name__)
heroes = {}
@app.route('/heroes', methods=['GET'])
def get_heroes():
return jsonify(list(heroes.values()))
@app.route('/heroes/<uuid:hero_uuid>', methods=['GET'])
def get_hero(hero_uuid):
hero = heroes.get(str(hero_uuid))
if hero:
return jsonify(hero)
return jsonify({'error': 'Not found'}), 404
@app.route('/heroes', methods=['POST'])
def create_hero():
data = request.get_json()
hero_uuid = str(uuid.uuid4())
hero = {
'uuid': hero_uuid,
'name': data['name'],
'role': data['role'],
'strength': data['strength']
}
heroes[hero_uuid] = hero
return jsonify(hero), 201
@app.route('/heroes/<uuid:hero_uuid>', methods=['PUT'])
def update_hero(hero_uuid):
hero = heroes.get(str(hero_uuid))
if not hero:
return jsonify({'error': 'Not found'}), 404
data = request.get_json()
hero['name'] = data['name']
hero['role'] = data['role']
hero['strength'] = data['strength']
return jsonify(hero)
@app.route('/heroes/<uuid:hero_uuid>', methods=['DELETE'])
def delete_hero(hero_uuid):
if str(hero_uuid) in heroes:
del heroes[str(hero_uuid)]
return '', 204
return jsonify({'error': 'Not found'}), 404
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)