Advertisement
teslariu

webserver con form

Aug 31st, 2022
829
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.36 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # pip install Flask
  5. #
  6. # Servidor web que aloja una lista de alumnos con su ID, nombre y
  7. # cantidad de cursos
  8. # EJ:
  9. """
  10. alumnos = [
  11.        {'id':1, 'nombre':'Juana', 'cursos':5},
  12.        {'id':2, 'nombre':'Ana', 'cursos':2},
  13.        {'id':3, 'nombre':'Oscar', 'cursos':6},
  14.        {'id':4, 'nombre':'Luis', 'cursos':4},
  15. ]
  16. """
  17. from flask import Flask, jsonify, request
  18.  
  19. alumnos = []
  20.  
  21. def enviado_html(texto):
  22.     return f"""
  23.    <!doctype html>
  24.        <html lang="es">
  25.            <head>
  26.                <meta charset="utf-8">
  27.                <title>Enviado</title>
  28.                <meta http-equiv="refresh" content="3";URL="http://localhost:5000/form">
  29.            </head>
  30.            <body>{texto}</body>
  31.        </html>
  32.    """
  33.    
  34. formulario_html = """
  35. <!DOCTYPE html>
  36.    <html>
  37.    <head><meta charset="utf-8"></head>
  38.    <body>
  39.        <form method="POST">
  40.            Nombre:<br>
  41.            <input type="text" name="nombre"><br>
  42.            
  43.            Cursos:<br>
  44.            <input type="number" name="cursos"><br>
  45.            
  46.            <br><br>
  47.            <input type="submit" value="Enviar">
  48.         </form>
  49.    </body>
  50. </html>
  51. """
  52.  
  53. # creo la pagina web
  54. app = Flask(__name__)
  55.  
  56. # creo el 'index.html' con decoradores
  57. @app.route("/")
  58. def index():
  59.     return "<h1><strong><em>HOME</em></strong></h1>"
  60.    
  61.    
  62. @app.route("/instructor")
  63. def instructor():
  64.     return "En construcción..."
  65.  
  66. # Habilito verbos web para modificar/ver datos de los alumnos
  67. @app.route("/alumno", methods=['GET','POST','PUT','DELETE'])
  68. def alumno():
  69.     if request.method == "GET":
  70.         return jsonify({'alumnos':alumnos})
  71.        
  72.        
  73.     elif request.method == "POST":
  74.         if not alumnos:
  75.             id_alumno = 1
  76.         else:
  77.             id_alumno = alumnos[-1]['id'] + 1
  78.         alumno = {
  79.             'id':id_alumno,
  80.             'nombre': request.json['nombre'],
  81.             'cursos': request.json['cursos']
  82.         }
  83.         alumnos.append(alumno)
  84.         return jsonify("Alumno añadido")
  85.        
  86.    
  87.     elif request.method == "PUT":
  88.         id_alumno = request.json['id']
  89.         for alumno in alumnos:
  90.             if id_alumno == alumno.get('id'):
  91.                 if request.json['nombre'] is not None:
  92.                     alumno['nombre'] = request.json['nombre']
  93.                 if request.json['cursos'] is not None:
  94.                     alumno['cursos'] = request.json['cursos']
  95.                 return jsonify("Datos modificados")
  96.         return jsonify(f"Alumno id={id_alumno} no encontrado")
  97.        
  98.        
  99.     elif request.method == 'DELETE':
  100.         id_alumno = request.json['id']
  101.         for alumno in alumnos:
  102.             if id_alumno == alumno.get('id'):
  103.                 alumnos.remove(alumno)
  104.                 return jsonify("Alumno borrado")
  105.         return jsonify(f"Alumno id={id_alumno} no encontrado")
  106.        
  107.        
  108. @app.route("/alumno/<int:i>")
  109. def get_alumno(i):
  110.     try:
  111.         return jsonify({"alumno":alumnos[i-1]})
  112.     except IndexError:
  113.         return jsonify(f"No existe el alumno con id={i}")
  114.        
  115.  
  116. @app.route("/form",  methods=["GET","POST"])
  117. def tomar_formulario():
  118.     if request.method == "GET":
  119.         return formulario_html.encode("utf-8")
  120.     elif request.method == "POST":
  121.         try:
  122.             body = dict(request.form)
  123.             if body["nombre"] and body["cursos"]:
  124.                 print("-"*20,"\n")
  125.                 print("Nombre:",body["nombre"],"\nCursos:",body["cursos"])
  126.                 print("\n","-"*20)
  127.                
  128.                 # guardo los datos:
  129.                 alumno = [body["nombre"], body["cursos"]]
  130.                 alumnos.append(alumno)
  131.                
  132.                 salida = enviado_html("Mensaje enviado")
  133.             else:
  134.                 salida = enviado_html("Campos Vacios, o hay un error")
  135.             return salida.encode("utf-8")
  136.        
  137.         except Exception:
  138.             salida = enviado_html("Campos Vacios, o hay un error")
  139.             return salida.encode("utf-8")
  140.     else:
  141.         salida = enviado_html("Campos Vacios, o hay un error")
  142.         return salida.encode("utf-8")
  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. # flask run
  154.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement