Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- #
- # instalar previamente Flask con pip install Flask
- #
- # Servidor web que aloja una lista de alumnos con ID, nombre y cursos
- """
- alumnos = [
- {"id":1, "nombre":"Ale", "cursos":6},
- {"id":2, "nombre":"Juan", "cursos":1},
- {"id":3, "nombre":"Ana", "cursos":3},
- ]
- """
- from flask import Flask, jsonify, request
- alumnos = []
- formulario = """
- <!DOCTYPE html>
- <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 enviado(texto):
- return f"""
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset='utf-8'>
- <title>Enviado</title>
- <meta http-equiv="refresh" content="3"; URL="http://localhost:5000/form">
- </head>
- <body>
- {texto}
- </body>
- </html>
- """
- # creo la webpage
- app = Flask(__name__)
- # creo el 'index.html' con decoradores
- @app.route("/")
- def index():
- return """
- <html>
- <h1><strong>Hola <em>desde HOME</em></strong>
- </h1>
- </html>
- """
- @app.route("/alumno", methods=['GET','POST','PUT','DELETE'])
- def alumno():
- if request.method == "GET":
- return jsonify({"alumnos":alumnos})
- elif request.method == "POST":
- if not alumnos:
- id_alumno = 1
- else:
- id_alumno = alumnos[-1]['id'] + 1
- alumno = {
- 'id': id_alumno,
- 'nombre': request.json['nombre'],
- 'cursos': request.json['cursos'],
- }
- alumnos.append(alumno)
- return jsonify("Alumno añadido")
- elif request.method == "PUT":
- id_alumno = request.json['id']
- for alumno in alumnos:
- if id_alumno == alumno.get('id'):
- 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"Alumno con id {id_alumno} no hallado")
- elif request.method == "DELETE":
- id_alumno = request.json['id']
- for alumno in alumnos:
- if id_alumno == alumno.get('id'):
- alumnos.remove(alumno)
- return jsonify("Alumno borrado")
- return jsonify(f"Alumno con id {id_alumno} no hallado")
- @app.route("/alumno/<int:i>")
- def get_alumno(i):
- try:
- return jsonify({"alumno":alumnos[i-1]})
- except IndexError:
- return jsonify(f"Alumno con id {i} no hallado")
- @app.route("/form", methods=['GET','POST'])
- def tomar_formulario():
- if request.method == "GET":
- return formulario.encode('utf-8')
- elif request.method == "POST":
- try:
- body = dict(request.form)
- if body['nombre'] and body['cursos']:
- print(f"""
- -------------------------------------------------------
- Nombre: {body['nombre']} - Cursos: {body['cursos']}
- -------------------------------------------------------
- """)
- # guardo los datos
- if not alumnos:
- id_alumno = 1
- else:
- id_alumno = alumnos[-1]['id'] + 1
- alumno = {
- 'id': id_alumno,
- 'nombre': body['nombre'],
- 'cursos': body['cursos'],
- }
- alumnos.append(alumno)
- salida = enviado("Mensaje enviado")
- else:
- salida = enviado("Faltan datos")
- return salida.encode('utf-8')
- except Exception:
- salida = enviado("Hubo un error")
- return salida.encode('utf-8')
- if __name__ == "__main__":
- app.run(debug=True)
- """
- LINUX:
- export FLASK_APP=server.py
- flask run
- WINDOWS:
- set FLASK_APP=server.py
- python -m flask run
- """
Advertisement
Add Comment
Please, Sign In to add comment