Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- from flask import Flask, jsonify, request
- app = Flask(__name__)
- """
- alumnos = [
- {'id':1, 'nombre':"Ale", "cursos":3},
- {'id':2, "nombre": "Juana", "cursos":4}
- ]
- """
- alumnos = []
- # Código HTML para el formulario
- formulario_html = """
- <DOCTYPE html>
- <head><meta charset='utf-8'></head>
- <body>
- <form method='POST'>
- Nombre: <br>
- <input type="text" name="nombre"><br>
- Cursos: <br>
- <input type="number" name="cursos"><br>
- <br><br>
- <input type="submit" value="Enviar">
- </form>
- </body>
- </html>
- """
- def salida_html(mensaje):
- """Función que imprime una pàgina html
- al enviar el formulario. Muestra un mensaje
- durante 3 segundos y posteriormente vuelve a mostrar
- el formulario vacío"""
- return f"""
- <DOCTYPE html>
- <head>
- <meta charset='utf-8'>
- <meta http-equiv='refresh' content="3";URL='http://localhost:5000/form'>
- </head>
- <body>
- {mensaje}
- </body>
- </html>
- """
- @app.route("/")
- def home():
- return "<html><h1>En construcción</em></h1></html>"
- @app.route("/alumno", methods=['GET','POST','PUT','DELETE'])
- def alumno():
- if request.method == "GET":
- return jsonify({'alumnos':alumnos})
- if request.method == "POST":
- if not alumnos:
- codigo = 1
- else:
- codigo = alumnos[-1]['id'] + 1
- alumno = {
- 'id': codigo,
- 'nombre': request.json['nombre'],
- 'cursos': request.json['cursos']
- }
- alumnos.append(alumno)
- return jsonify("Alumno añadido")
- if request.method == "PUT":
- codigo = request.json['id']
- for alumno in alumnos:
- if alumno.get('id') == codigo:
- if request.json['nombre'] is not None:
- alumno['nombre'] = request.json['nombre']
- if request.json['cursos'] is not None:
- alumno['cursos'] = request.json['cursos']
- return jsonify("Datos modificados")
- return jsonify(f"No se halló al alumno con id {codigo}")
- if request.method == "DELETE":
- codigo = request.json['id']
- for alumno in alumnos:
- if alumno.get('id') == codigo:
- alumnos.remove(alumno)
- return jsonify("Alumno eliminado")
- return jsonify(f"No se halló al alumno con id {codigo}")
- @app.route("/alumno/<int:i>")
- def get_alumno(i):
- try:
- return jsonify({"alumno":alumnos[i-1]})
- except IndexError:
- return jsonify(f"No se halló al alumno con id {i}")
- # creo la función para mostrar el formulario y subir los datos al server
- @app.route("/form", methods=['GET', 'POST'])
- def formulario():
- if request.method == "GET":
- return formulario_html.encode('utf-8')
- if request.method == "POST":
- try:
- body = dict(request.form)
- except Exception:
- mensaje = "ERROR"
- else:
- if body['nombre'] and body['cursos']:
- if not alumnos:
- id_alumno = 1
- else:
- id_alumno = alumnos[-1]['id'] + 1
- print(f"""
- Datos del alumno añadido
- ------------------------
- ID: {id_alumno}
- Nombre: {body['nombre']}
- Cursos: {body['cursos']}
- -------------------------
- """)
- # guardo los datos:
- alumno = {
- 'id': id_alumno,
- 'nombre': body['nombre'],
- 'cursos': body['cursos']
- }
- alumnos.append(alumno)
- mensaje = "Datos guardados"
- else:
- mensaje = "Datos incompletos"
- finally:
- return salida_html(mensaje).encode('utf-8')
- @app.route("/instructor")
- def instructor():
- return "<html><h1>Muy pronto....</em></h1></html>"
- @app.route("/administrador")
- def admin():
- return "<html><h1>Hola <em>mundo</em></h1></html>"
- if __name__ == "__main__":
- app.run(debug=True)
- # Linux
- # export FLASK_APP=webserver.py
- # flask run
- # Windows
- # set FLASK_APP=webserver.py
- # flask run
Advertisement
Add Comment
Please, Sign In to add comment