teslariu

servidor con formulario

Jun 6th, 2023
996
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.59 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from flask import Flask, jsonify, request
  5.  
  6. app = Flask(__name__)
  7. """
  8. alumnos = [
  9.    {'id':1, 'nombre':"Ale", "cursos":3},
  10.    {'id':2, "nombre": "Juana", "cursos":4}
  11. ]
  12. """
  13. alumnos = []
  14.  
  15. # Código HTML para el formulario
  16.  
  17. formulario_html = """
  18. <DOCTYPE html>
  19.    <head><meta charset='utf-8'></head>
  20.    <body>
  21.        <form method='POST'>
  22.        Nombre: <br>
  23.        <input type="text" name="nombre"><br>
  24.        Cursos: <br>
  25.        <input type="number" name="cursos"><br>
  26.        <br><br>
  27.        <input type="submit" value="Enviar">
  28.        </form>
  29.    </body>
  30. </html>
  31. """
  32.  
  33. def salida_html(mensaje):
  34.     """Función que imprime una pàgina html
  35.    al enviar el formulario. Muestra un mensaje
  36.    durante 3 segundos y posteriormente vuelve a mostrar
  37.    el formulario vacío"""
  38.    
  39.     return f"""
  40.    <DOCTYPE html>
  41.    <head>
  42.        <meta charset='utf-8'>
  43.        <meta http-equiv='refresh' content="3";URL='http://localhost:5000/form'>
  44.    </head>
  45.    <body>
  46.       {mensaje}
  47.    </body>
  48.    </html>
  49.    """
  50.    
  51.    
  52.  
  53. @app.route("/")
  54. def home():
  55.     return "<html><h1>En construcción</em></h1></html>"
  56.  
  57.  
  58. @app.route("/alumno", methods=['GET','POST','PUT','DELETE'])
  59. def alumno():
  60.     if request.method == "GET":
  61.         return jsonify({'alumnos':alumnos})
  62.        
  63.     if request.method == "POST":
  64.         if not alumnos:
  65.             codigo = 1
  66.         else:
  67.             codigo = alumnos[-1]['id'] + 1
  68.         alumno = {
  69.                 'id': codigo,
  70.                 'nombre': request.json['nombre'],
  71.                 'cursos': request.json['cursos']
  72.         }
  73.         alumnos.append(alumno)
  74.         return jsonify("Alumno añadido")
  75.        
  76.     if request.method == "PUT":
  77.         codigo = request.json['id']
  78.         for alumno in alumnos:
  79.             if alumno.get('id') == codigo:
  80.                 if request.json['nombre'] is not None:
  81.                     alumno['nombre'] = request.json['nombre']
  82.                 if request.json['cursos'] is not None:
  83.                     alumno['cursos'] = request.json['cursos']
  84.                 return jsonify("Datos modificados")
  85.         return jsonify(f"No se halló al alumno con id {codigo}")
  86.    
  87.    
  88.     if request.method == "DELETE":
  89.         codigo = request.json['id']
  90.         for alumno in alumnos:
  91.             if alumno.get('id') == codigo:
  92.                 alumnos.remove(alumno)
  93.                 return jsonify("Alumno eliminado")
  94.         return jsonify(f"No se halló al alumno con id {codigo}")
  95.  
  96. @app.route("/alumno/<int:i>")
  97. def get_alumno(i):
  98.     try:
  99.         return jsonify({"alumno":alumnos[i-1]})
  100.     except IndexError:
  101.         return jsonify(f"No se halló al alumno con id {i}")
  102.        
  103.  
  104. # creo la función para mostrar el formulario y subir los datos al server
  105. @app.route("/form", methods=['GET', 'POST'])
  106. def formulario():
  107.     if request.method == "GET":
  108.         return formulario_html.encode('utf-8')
  109.    
  110.     if request.method == "POST":
  111.         try:
  112.             body = dict(request.form)
  113.                    
  114.         except Exception:
  115.             mensaje = "ERROR"
  116.        
  117.         else:
  118.             if body['nombre'] and body['cursos']:
  119.                 if not alumnos:
  120.                     id_alumno = 1
  121.                 else:
  122.                     id_alumno = alumnos[-1]['id'] + 1
  123.                 print(f"""
  124.                Datos del alumno añadido
  125.                ------------------------
  126.                ID: {id_alumno}
  127.                Nombre: {body['nombre']}
  128.                Cursos: {body['cursos']}
  129.                -------------------------
  130.                """)
  131.                
  132.                 # guardo los datos:
  133.                 alumno = {
  134.                     'id': id_alumno,
  135.                     'nombre': body['nombre'],
  136.                     'cursos': body['cursos']
  137.                 }
  138.                 alumnos.append(alumno)
  139.                
  140.                 mensaje = "Datos guardados"
  141.             else:
  142.                 mensaje = "Datos incompletos"
  143.                
  144.         finally:
  145.             return salida_html(mensaje).encode('utf-8')
  146.        
  147.            
  148.        
  149.        
  150.            
  151.        
  152.  
  153.  
  154.  
  155.  
  156.    
  157. @app.route("/instructor")
  158. def instructor():
  159.     return "<html><h1>Muy pronto....</em></h1></html>"
  160.    
  161. @app.route("/administrador")
  162. def admin():
  163.     return "<html><h1>Hola <em>mundo</em></h1></html>"
  164.    
  165.    
  166. if __name__ == "__main__":
  167.     app.run(debug=True)
  168.    
  169. # Linux
  170. # export FLASK_APP=webserver.py
  171. # flask run
  172.  
  173. # Windows
  174. # set FLASK_APP=webserver.py
  175. # flask run
  176.  
  177.  
Advertisement
Add Comment
Please, Sign In to add comment