Advertisement
teslariu

server con formulario

Oct 28th, 2023
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.39 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":"Ana", "cursos":4},
  10.     {'id':2, "nombre":"Juan", "cursos":11},
  11. ]
  12.  
  13. """
  14. alumnos = []
  15.  
  16. formulario_html = """
  17. <html>
  18.     <head><meta charset='utf-8'></head>
  19.     <body>
  20.         <form method="POST">
  21.             Nombre:<br>
  22.             <input type="text" name="nombre"><br>
  23.             Cursos:<br>
  24.             <input type="number" name="cursos"><br>
  25.             <br><br>
  26.             <input type="submit" value="Enviar">
  27.         </form>
  28.     </body>
  29. </html>
  30. """
  31.  
  32. def salida_html(mensaje):
  33.     return f"""
  34.     <html>
  35.         <head>
  36.             <meta charset='utf-8'>
  37.             <meta http-equiv="refresh" content="3";URL="http://localhost:5000/form">
  38.         </head>
  39.         <body>{mensaje}</body>
  40.     </html>
  41.     """
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48. @app.route("/")
  49. def home():
  50.     return "HOME"
  51.    
  52. @app.route("/admin")
  53. def admin():
  54.     return "Dentro de la vista de admin"
  55.    
  56.  
  57. @app.route("/alumnos",methods=['GET','POST','PUT','DELETE'])
  58. def get_alumnos():
  59.     if request.method == "GET":
  60.         return jsonify({"alumnos":alumnos})
  61.        
  62.     elif request.method == "POST":
  63.         if not alumnos:
  64.             id_alumno = 1
  65.         else:
  66.             id_alumno = alumnos[-1]['id'] + 1
  67.         alumno = {
  68.             'id':id_alumno,
  69.             'nombre':request.json['nombre'],
  70.             'cursos':request.json['cursos']
  71.         }
  72.         alumnos.append(alumno)
  73.         return jsonify("Alumno añadido")
  74.        
  75.     elif request.method == "PUT":
  76.         id_alumno = request.json['id']
  77.         for alumno in alumnos:
  78.             if id_alumno == alumno.get('id'):
  79.                 if request.json['nombre'] is not None:
  80.                     alumno['nombre'] = request.json['nombre']
  81.                 if request.json['cursos'] is not None:
  82.                     alumno['cursos'] = request.json['cursos']
  83.                 return jsonify("Datos modificados")
  84.         return jsonify(f"Alumno id:{id_alumno} no encontrado")
  85.        
  86.        
  87.     elif request.method == "DELETE":
  88.         id_alumno = request.json['id']
  89.         for alumno in alumnos:
  90.             if id_alumno == alumno.get('id'):
  91.                 alumnos.remove(alumno)
  92.                 return jsonify("Alumno borrado")
  93.         return jsonify(f"Alumno id:{id_alumno} no encontrado")
  94.        
  95.        
  96. @app.route("/alumnos/<int:i>")
  97. def get_alumno(i):
  98.     try:
  99.         return jsonify({"alumno":alumnos[i-1]})
  100.     except IndexError:
  101.         return jsonify(f"Alumno id:{i} no encontrado")
  102.        
  103.            
  104. @app.route("/form", methods=['GET','POST'])
  105. def formulario():
  106.     if request.method == "GET":
  107.         return formulario_html.encode("utf-8")
  108.        
  109.     elif request.method == "POST":
  110.         try:
  111.             datos = dict(request.form)
  112.         except Exception:
  113.             pass
  114.         else:
  115.             if datos['nombre'] and datos['cursos']:
  116.                 if not alumnos:
  117.                     id_alumno = 1
  118.                 else:
  119.                     id_alumno = alumnos[-1]['id'] + 1
  120.                
  121.                 # guardo los datos
  122.                 alumno = {
  123.                     'id':id_alumno,
  124.                     'nombre':datos['nombre'],
  125.                     'cursos':datos['cursos']
  126.                 }
  127.                 alumnos.append(alumno)
  128.                
  129.                
  130.                 print(f"""
  131.                 Datos del alumno añadido
  132.                 -------------------------
  133.                 ID: {id_alumno}
  134.                 Nombre: {datos['nombre']}
  135.                 Cursos: {datos['cursos']}
  136.                 -------------------------
  137.                 """)
  138.                
  139.                
  140.                
  141.                 mensaje = "Datos guardados"
  142.                
  143.             else:
  144.                 mensaje = "Datos incompletos"
  145.                
  146.         return salida_html(mensaje).encode('utf-8')
  147.                
  148.     mensaje = "Error, posibles campos vacíos"     
  149.     return salida_html(mensaje).encode('utf-8')        
  150.                    
  151.        
  152.        
  153.        
  154.  
  155.  
  156.  
  157.  
  158.  
  159.  
  160.  
  161.  
  162.  
  163.    
  164. if __name__ == "__main__":
  165.     app.run(debug=True)
  166.    
  167. # Linux
  168. # export FLASK_APP=webserver.py
  169. # flask run
  170.  
  171. # WINDOWS
  172. # set FLASK_APP=webserver.py
  173. # python flask run
  174.  
  175.  
  176.  
  177.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement