Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- #
- # python -m pip install Flask
- #
- # Servidor web que almacene alumnos con id y cursos
- """
- alumnos = [
- {'id':1, 'nombre':'Pepe', 'cursos':34},
- {'id':2, 'nombre':'Ana', 'cursos':5},
- ]
- """
- from flask import Flask, jsonify, request
- # creo la lista para almacenar alumnos
- alumnos = []
- # creo la página web del formulario
- formulario_html = """
- <!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 salida_html(mensaje):
- return f"""
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset='utf-8'>
- <title>Formulario</title>
- <meta http-equiv="refresh" content="3";URL="http://localhost:5000/form"
- </head>
- <body>{mensaje}</body>
- </html>
- """
- # creo la página web
- app = Flask(__name__)
- # creo el 'index.html'
- @app.route('/')
- def index():
- return "<h1><strong><em>Hola</em> a todos</strong></h1>"
- # creo un formulario web para ingresar datos
- @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)
- except Exception:
- pass
- 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"
- return salida_html(mensaje).encode('utf-8')
- @app.route('/alumno', methods=['GET','POST','DELETE','PUT'])
- 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']:
- alumno['nombre'] = request.json['nombre']
- if request.json['cursos']:
- alumno['cursos'] = request.json['cursos']
- return jsonify(f"Datos del alumno id={id_alumno} modificado")
- return jsonify(f"Alumno id={id_alumno} no encontrado")
- elif request.method == "DELETE":
- id_alumno = request.json['id']
- for alumno in alumnos:
- if id_alumno == alumno.get('id'):
- alumnos.remove(alumno)
- return jsonify(f"Alumno id={id_alumno} borrado")
- return jsonify(f"Alumno id={id_alumno} no encontrado")
- @app.route('/alumno/<int:i>')
- def get_alumno(i):
- try:
- return jsonify({"alumno":alumnos[i-1]})
- except IndexError:
- return jsonify(f"Alumno id={i} no encontrado")
- @app.route('/admin')
- def admin():
- return "<h1><strong>En construcción</strong></h1>"
- 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