mirror of
https://github.com/Anrab35/SAE410_TP2.git
synced 2024-10-21 21:26:09 +02:00
80 lines
2.3 KiB
Python
80 lines
2.3 KiB
Python
|
#!/usr/bin/env python
|
||
|
# encoding: utf-8
|
||
|
import os
|
||
|
import json
|
||
|
from flask import Flask, request, jsonify
|
||
|
|
||
|
file = 'data/'+os.path.splitext(os.path.basename(__file__))[0]+'.json'
|
||
|
|
||
|
|
||
|
with open(file, 'r') as f:
|
||
|
j = json.load(f)
|
||
|
|
||
|
def save_json(new_json):
|
||
|
with open(file, 'w') as f:
|
||
|
f.write(json.dumps(new_json, indent=4))
|
||
|
with open(file, 'r') as f:
|
||
|
j = json.load(f)
|
||
|
|
||
|
app = Flask(__name__)
|
||
|
|
||
|
@app.route('/healthcheck', methods=['GET'])
|
||
|
def ping():
|
||
|
return jsonify({"conatiner_status": "healthy"})
|
||
|
|
||
|
@app.route('/sports', methods=['GET'])
|
||
|
def list_sports():
|
||
|
return jsonify({"status": "success", "data": j})
|
||
|
|
||
|
@app.route('/sports', methods=['POST'])
|
||
|
def add_sport():
|
||
|
try:
|
||
|
new = json.loads(request.data)
|
||
|
next_id = j[-1]['id']+1
|
||
|
j.append({
|
||
|
"id": next_id,
|
||
|
"name": new['name'],
|
||
|
"place": new['place'],
|
||
|
"category": new['category'],
|
||
|
})
|
||
|
save_json(j)
|
||
|
return jsonify({"status": "success", "id": next_id})
|
||
|
except Exception as e:
|
||
|
print(e)
|
||
|
return jsonify({"status": "error", "message": "Please provide a valid JSON"}), 500
|
||
|
|
||
|
@app.route('/sports/<id>', methods=['GET'])
|
||
|
def get_sport(id):
|
||
|
for s in j:
|
||
|
if s['id'] == int(id):
|
||
|
return jsonify({"status": "success", "data": s})
|
||
|
return jsonify({"status": "error", "message": "Id not found"}), 404
|
||
|
|
||
|
@app.route('/sports/<id>', methods=['PATCH'])
|
||
|
def edit_sport(id):
|
||
|
try:
|
||
|
update = json.loads(request.data)
|
||
|
entries = ['name', 'place', 'category']
|
||
|
for i, s in enumerate(j):
|
||
|
if s['id'] == int(id):
|
||
|
for e in entries:
|
||
|
if update.get(e) is not None:
|
||
|
j[i][e] = update[e]
|
||
|
save_json(j)
|
||
|
return jsonify({"status": "success"})
|
||
|
return jsonify({"status": "error", "message": "Id not found"}), 404
|
||
|
except Exception as e:
|
||
|
print(e)
|
||
|
return jsonify({"status": "error", "message": "Please provide a valid JSON"}), 500
|
||
|
|
||
|
@app.route('/sports/<id>', methods=['DELETE'])
|
||
|
def rm_sport(id):
|
||
|
for i, s in enumerate(j):
|
||
|
if s['id'] == int(id):
|
||
|
j.pop(i)
|
||
|
save_json(j)
|
||
|
return jsonify({"status": "success"})
|
||
|
return jsonify({"status": "error", "message": "Id not found"}), 404
|
||
|
|
||
|
|
||
|
app.run(host="0.0.0.0", debug=False)
|