teslariu

web server

Dec 2nd, 2022
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.64 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # python -m pip install Flask
  5. #
  6. # Servidor web que aloja una lista de alumnos con su ID, nombre y
  7. # cantidad de cursos
  8. #
  9. """
  10. alumnos = [
  11.    {'id':1, 'nombre':'Juan', 'cursos':4},
  12.    {'id':2, 'nombre':'Emilia', 'cursos':1},
  13.    {'id':3, 'nombre':'Ana', 'cursos':6},
  14.    {'id':4, 'nombre':'Oscar', 'cursos':3},
  15. ]
  16. """
  17. from flask import Flask, jsonify, request
  18.  
  19. alumnos = []
  20. pagina = "<h1><strong><em>HOME</em></strong></h1>"
  21.  
  22. formulario_html = """
  23. <DOCTYPE html>
  24.    <html>
  25.    <head><meta charset="utf-8"></head>
  26.    <body>
  27.        <form method="POST">
  28.            Nombre: <br>
  29.            <input type="text" name="nombre"><br>
  30.            Cursos: <br>
  31.            <input type="text" name="cursos"><br>
  32.            <br><br>
  33.            <input type="submit" value="Enviar">
  34.        </form>
  35.    </body>
  36.    </html>
  37. """
  38.  
  39. def salida_html(texto):
  40.     return f"""
  41.    <DOCTYPE html>
  42.        <html>
  43.            <head>
  44.                <meta charset="utf-8">
  45.                <title>Enviado</title>
  46.                <meta http-equiv="refresh" content="3"; URL="http://localhost:5000/form">
  47.            </head>
  48.            <body>
  49.                {texto}
  50.            </body>
  51.        </html>
  52.    """
  53.  
  54.  
  55.  
  56. # creo la pagina web
  57. app = Flask(__name__)
  58.  
  59.  
  60.  
  61. # creo la pagina index con decoradores
  62. @app.route('/')
  63. def index():
  64.     return pagina
  65.    
  66.  
  67.  
  68. @app.route('/instructor')
  69. def instructor():
  70.     return "<p>En construcción</p>"
  71.  
  72.  
  73. # creo una vista para trabajar con los datos de los alumnos
  74. @app.route('/alumnos', methods=['GET', 'POST', 'PUT', 'DELETE'])
  75. def alumno():
  76.     if request.method == 'GET':
  77.         return jsonify({'alumnos':alumnos})
  78.        
  79.     elif request.method == 'POST':
  80.         if not alumnos:
  81.             id_alumno = 1
  82.         else:
  83.             id_alumno = alumnos[-1]['id'] + 1
  84.         alumno = {
  85.             'id': id_alumno,
  86.             'nombre': request.json['nombre'],
  87.             'cursos': request.json['cursos'],
  88.         }
  89.         alumnos.append(alumno)
  90.         return jsonify("Alumno añadido")
  91.  
  92.  
  93.     elif request.method == 'PUT':
  94.         id_alumno = request.json['id']
  95.         for alumno in alumnos:
  96.             if id_alumno == alumno.get('id'):
  97.                 if request.json['nombre']:
  98.                     alumno['nombre'] = request.json['nombre']
  99.                 if request.json['cursos']:
  100.                     alumno['cursos'] = request.json['cursos']
  101.                 return jsonify("Datos modificados")
  102.         return jsonify(f"Alumno id={id_alumno} no hallado")
  103.        
  104.        
  105.     elif request.method == 'DELETE':
  106.         id_alumno = request.json['id']
  107.         for alumno in alumnos:
  108.             if id_alumno == alumno.get('id'):
  109.                 alumnos.remove(alumno)
  110.                 return jsonify("Alumno borrado")
  111.         return jsonify(f"Alumno id={id_alumno} no hallado")
  112.  
  113.     else:
  114.         return jsonify(f"Método no soportado")
  115.  
  116.  
  117. @app.route('/alumnos/<int:i>')
  118. def get_alumno(i):
  119.     try:
  120.         return jsonify({"alumno": alumnos[i-1]})
  121.     except IndexError:
  122.         return jsonify(f"Alumno con id={i} no hallado")
  123.  
  124.  
  125.  
  126. @app.route('/form', methods=["GET","POST"])
  127. def formulario():
  128.     if request.method == "GET":
  129.         return formulario_html.encode('utf-8')
  130.        
  131.     elif request.method == "POST":
  132.         try:
  133.             body = dict(request.form)
  134.         except Exception:
  135.             mensaje = "Campos vacíos, o hay algún error"
  136.             return salida_html.encode('utf-8')
  137.         else:
  138.             if body["nombre"] and body["cursos"]:
  139.                 if not alumnos:
  140.                     id_alumno = 1
  141.                 else:
  142.                     id_alumno = alumnos[-1]['id'] + 1
  143.                 print(f"""
  144.                -------------------------------------
  145.                ID: {id_alumno}
  146.                Nombre: {body["nombre"]}
  147.                Cursos: {body["cursos"]}
  148.                -------------------------------------
  149.                """)
  150.                 # guardo los datos
  151.                 alumno = {
  152.                     'id': id_alumno,
  153.                     'nombre': body['nombre'],
  154.                     'cursos': body['cursos'],
  155.                     }
  156.                 alumnos.append(alumno)
  157.                
  158.                 mensaje = "Datos guardados"
  159.             else:
  160.                 mensaje = "Campos vacíos, o hay algún error"
  161.             return salida_html(mensaje).encode("utf-8")
  162.  
  163.  
  164.  
  165.  
  166.    
  167. if __name__ == "__main__":
  168.     app.run(debug=True)
  169.    
  170. # LINUX
  171. # export FLASK_APP=wbserver.py
  172. # flask run
  173.  
  174. # WINDOWS
  175. # set FLASK_APP=wbserver.py
  176. # flask run
  177.  
  178.  
  179.  
  180.    
  181.  
Add Comment
Please, Sign In to add comment