71 lines
1.7 KiB
Python
71 lines
1.7 KiB
Python
from flask import Flask, jsonify, request, render_template
|
|
import json
|
|
import os
|
|
|
|
compiti = []
|
|
id_counter = 0
|
|
|
|
def update_file():
|
|
with open('compiti.json', 'w') as f:
|
|
json.dump(compiti, f)
|
|
|
|
if os.path.isfile('compiti.json'):
|
|
with open('compiti.json', 'r') as f:
|
|
compiti = json.load(f)
|
|
id_counter = compiti[-1]["id"] + 1
|
|
else:
|
|
compiti = [
|
|
{"id": 1, "descrizione": "Compito matematica"},
|
|
{"id": 2, "descrizione": "Consegna TPSIT progetto API REST"},
|
|
{"id": 3, "descrizione": "Compito di sistemi"},
|
|
{"id": 4, "descrizione": "Compito di italiano"}
|
|
]
|
|
id_counter = 5
|
|
update_file()
|
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
@app.route("/", methods=["GET"])
|
|
def home():
|
|
html = "<h1>Home page API REST Compiti</h1><h2>ciao, 3cx merda</h2>"
|
|
html += "<a href=\"/doc\">Documentazione</a>"
|
|
return html, 200
|
|
|
|
@app.route("/doc", methods=["GET"])
|
|
def get_doc():
|
|
return render_template("doc.html"), 200
|
|
|
|
@app.route("/compiti", methods=["GET"])
|
|
def get_compiti():
|
|
return jsonify(compiti), 200
|
|
|
|
@app.route("/compiti/<int:id>", methods=["GET"])
|
|
def get_compito_by_id(id):
|
|
for ciscomerda in compiti:
|
|
if ciscomerda["id"] == id:
|
|
return jsonify(ciscomerda), 200
|
|
return jsonify([]), 404
|
|
|
|
@app.route("/compiti", methods=["POST"])
|
|
def create_compito():
|
|
global id_counter
|
|
j = request.get_json()
|
|
j["id"] = id_counter
|
|
id_counter += 1
|
|
compiti.append(j)
|
|
update_file()
|
|
return jsonify(j), 201
|
|
|
|
@app.route("/compiti/<int:id>", methods=["DELETE"])
|
|
def delete_compito(id):
|
|
for ciscomerda in compiti:
|
|
if ciscomerda["id"] == id:
|
|
compiti.remove(ciscomerda)
|
|
return jsonify(ciscomerda), 200
|
|
update_file()
|
|
return jsonify([]), 404
|
|
|
|
app.run("0.0.0.0")
|