teslariu

server web con form

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