Advertisement
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':'Juan Carlos', 'cursos':5},
- {'id':2, 'nombre':'Ana', 'cursos':3},
- ]
- """
- alumnos = []
- # creo un formulario en html para subir datos
- formulario_html = """
- <!DOCTYPE html>
- <head><meta charset='utf-8'></head>
- <body>
- <form method='POST'>
- Nombre:
- <input type='text' name='nombre'><br><br>
- Cursos:
- <input type='number' name='cursos' min="1"><br>
- <br><br>
- <input type='submit' value='Enviar'>
- </form>
- </body>
- </html>
- """
- def salida_html(mensaje):
- return f"""
- <!doctype html>
- <head>
- <title>Enviado</title>
- <meta http-equiv="refresh" content="3";URL="http://localhost:5000/form">
- </head>
- <body>{mensaje}</body>
- </html>
- """
- @app.route('/')
- def home():
- return "HOME"
- @app.route('/alumnos', 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"No se encontró alumno con id: {id_alumno}")
- 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 eliminado")
- return jsonify(f"No se encontró alumno con id: {id_alumno}")
- @app.route("/alumnos/<int:i>")
- def get_alumno(i):
- try:
- return jsonify({"alumno":alumnos[i-1]})
- except IndexError:
- return jsonify("Alumno inexistente")
- @app.route('/instructor')
- def get_instructor():
- return "Sección de instructores"
- @app.route('/administrativo')
- def get_administrativo():
- return "<html><h1>EN CONSTRUCCION ...</h1></html>"
- @app.route('/form', methods=['GET','POST'])
- def formulario():
- if request.method == "GET":
- return formulario_html.encode('utf-8')
- elif request.method == "POST":
- try:
- body = dict(request.form) # los datos del formulario
- except Exception:
- mensaje = "Datos erróneos"
- 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')
- if __name__ == "__main__":
- app.run(debug=True)
- # LINUX
- # export FLASK_APP=webserver.py
- # flask run
- # WINDOWS
- # set FLASK_APP=webserver.py
- # python -m flask run
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement