Advertisement
teslariu

webserver con formulario

Jul 13th, 2023
1,141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.45 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. """
  9. alumnos = [
  10.     {'id':1, 'nombre':'Juan Carlos', 'cursos':5},
  11.     {'id':2, 'nombre':'Ana', 'cursos':3},
  12. ]
  13. """
  14. alumnos = []
  15.  
  16. # creo un formulario en html para subir datos
  17. formulario_html = """
  18. <!DOCTYPE html>
  19. <head><meta charset='utf-8'></head>
  20. <body>
  21.     <form method='POST'>
  22.         Nombre:
  23.         <input type='text' name='nombre'><br><br>
  24.         Cursos:
  25.         <input type='number' name='cursos' min="1"><br>
  26.         <br><br>
  27.         <input type='submit' value='Enviar'>
  28.     </form>
  29. </body>
  30. </html>
  31. """
  32.  
  33. def salida_html(mensaje):
  34.     return f"""
  35.     <!doctype html>
  36.     <head>
  37.         <title>Enviado</title>
  38.         <meta http-equiv="refresh" content="3";URL="http://localhost:5000/form">
  39.     </head>
  40.     <body>{mensaje}</body>
  41.     </html>
  42.     """
  43.  
  44.  
  45. @app.route('/')
  46. def home():
  47.     return "HOME"
  48.    
  49. @app.route('/alumnos', methods=['GET','POST','PUT','DELETE'])
  50. def alumno():
  51.    
  52.     if request.method == "GET":
  53.         return jsonify({'alumnos':alumnos})
  54.        
  55.     elif request.method == "POST":
  56.         if not alumnos:
  57.             id_alumno = 1
  58.         else:
  59.             id_alumno = alumnos[-1]['id'] + 1
  60.         alumno = {
  61.             'id': id_alumno,
  62.             'nombre': request.json['nombre'],
  63.             'cursos': request.json['cursos']
  64.         }
  65.         alumnos.append(alumno)
  66.         return jsonify("Alumno añadido")
  67.        
  68.     elif request.method == "PUT":
  69.         id_alumno = request.json['id']
  70.         for alumno in alumnos:
  71.             if id_alumno == alumno.get('id'):
  72.                 if request.json['nombre'] is not None:
  73.                     alumno['nombre'] = request.json['nombre']
  74.                 if request.json['cursos'] is not None:
  75.                     alumno['cursos'] = request.json['cursos']
  76.                 return jsonify("Datos modificados...")
  77.         return jsonify(f"No se encontró alumno con id: {id_alumno}")
  78.        
  79.     elif request.method == "DELETE":
  80.         id_alumno = request.json['id']
  81.         for alumno in alumnos:
  82.             if id_alumno == alumno.get('id'):
  83.                 alumnos.remove(alumno)
  84.                 return jsonify("Alumno eliminado")
  85.         return jsonify(f"No se encontró alumno con id: {id_alumno}")
  86.        
  87. @app.route("/alumnos/<int:i>")
  88. def get_alumno(i):
  89.     try:
  90.         return jsonify({"alumno":alumnos[i-1]})
  91.     except IndexError:
  92.         return jsonify("Alumno inexistente")
  93.        
  94. @app.route('/instructor')
  95. def get_instructor():
  96.     return "Sección de instructores"
  97.    
  98. @app.route('/administrativo')
  99. def get_administrativo():
  100.     return "<html><h1>EN CONSTRUCCION ...</h1></html>"
  101.  
  102. @app.route('/form', methods=['GET','POST'])
  103. def formulario():
  104.     if request.method == "GET":
  105.         return formulario_html.encode('utf-8')
  106.    
  107.     elif request.method == "POST":
  108.         try:
  109.             body = dict(request.form) # los datos del formulario
  110.         except Exception:
  111.             mensaje = "Datos erróneos"
  112.         else:
  113.             if body['nombre'] and body['cursos']:
  114.                 if not alumnos:
  115.                     id_alumno = 1
  116.                 else:
  117.                     id_alumno = alumnos[-1]['id'] + 1
  118.                 print(f"""
  119.                 Datos del alumno añadido
  120.                 ------------------------
  121.                 ID: {id_alumno}
  122.                 Nombre: {body['nombre']}
  123.                 Cursos: {body['cursos']}
  124.                 ------------------------
  125.                 """
  126.                 )
  127.                 # guardo los datos
  128.                 alumno = {
  129.                     'id': id_alumno,
  130.                     'nombre': body['nombre'],
  131.                     'cursos': body['cursos'],
  132.                 }
  133.                 alumnos.append(alumno)
  134.                 mensaje = "Datos guardados"
  135.             else:
  136.                 mensaje = "Datos incompletos"
  137.                
  138.         finally:
  139.             return salida_html(mensaje).encode('utf-8')
  140.            
  141.  
  142.  
  143.    
  144. if __name__ == "__main__":
  145.     app.run(debug=True)
  146.    
  147. # LINUX
  148. # export FLASK_APP=webserver.py
  149. # flask run
  150.  
  151. # WINDOWS
  152. # set FLASK_APP=webserver.py
  153. # python -m flask run
  154.        
  155.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement