teslariu

server

Sep 16th, 2022
971
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.43 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # instalar previamente Flask con pip install Flask
  5. #
  6. # Servidor web que aloja una lista de alumnos con ID, nombre y cursos
  7. """
  8. alumnos = [
  9.        {"id":1, "nombre":"Ale", "cursos":6},
  10.        {"id":2, "nombre":"Juan", "cursos":1},
  11.        {"id":3, "nombre":"Ana", "cursos":3},
  12.    ]
  13. """
  14.  
  15. from flask import Flask, jsonify, request
  16.  
  17. alumnos = []
  18. formulario = """
  19. <!DOCTYPE html>
  20.    <html>
  21.    <head><meta charset='utf-8'></head>
  22.    <body>
  23.        <form method="POST">
  24.            Nombre:<br>
  25.            <input type="text" name="nombre"><br>
  26.            
  27.            Cursos:<br>
  28.            <input type="number" name="cursos"><br>
  29.            
  30.            <br><br>
  31.            <input type="submit" value="Enviar">
  32.        </form>
  33.    </body>
  34. </html>
  35. """
  36.  
  37. def enviado(texto):
  38.     return f"""
  39.    <!DOCTYPE html>
  40.    <html>
  41.        <head>
  42.            <meta charset='utf-8'>
  43.            <title>Enviado</title>
  44.            <meta http-equiv="refresh" content="3"; URL="http://localhost:5000/form">
  45.        </head>    
  46.        <body>
  47.            {texto}
  48.        </body>
  49.    </html>
  50.    """
  51.  
  52.  
  53. # creo la webpage
  54. app = Flask(__name__)
  55.  
  56. # creo el 'index.html' con decoradores
  57. @app.route("/")
  58. def index():
  59.     return """
  60.    <html>
  61.    <h1><strong>Hola <em>desde HOME</em></strong>
  62.    </h1>
  63.    </html>
  64.    """
  65.    
  66. @app.route("/alumno", methods=['GET','POST','PUT','DELETE'])
  67. def alumno():
  68.     if request.method == "GET":
  69.         return jsonify({"alumnos":alumnos})
  70.        
  71.     elif request.method == "POST":
  72.         if not alumnos:
  73.             id_alumno = 1
  74.         else:
  75.             id_alumno = alumnos[-1]['id'] + 1
  76.         alumno = {
  77.                 'id': id_alumno,
  78.                 'nombre': request.json['nombre'],
  79.                 'cursos': request.json['cursos'],
  80.         }
  81.         alumnos.append(alumno)
  82.         return jsonify("Alumno añadido")
  83.        
  84.        
  85.     elif request.method == "PUT":
  86.         id_alumno = request.json['id']
  87.         for alumno in alumnos:
  88.             if id_alumno == alumno.get('id'):
  89.                 if request.json['nombre'] is not None:
  90.                     alumno['nombre'] = request.json['nombre']
  91.                 if request.json['cursos'] is not None:
  92.                     alumno['cursos'] = request.json['cursos']
  93.                 return jsonify("Datos modificados")
  94.         return jsonify(f"Alumno con id {id_alumno} no hallado")
  95.        
  96.        
  97.     elif request.method == "DELETE":
  98.         id_alumno = request.json['id']
  99.         for alumno in alumnos:
  100.             if id_alumno == alumno.get('id'):
  101.                 alumnos.remove(alumno)
  102.                 return jsonify("Alumno borrado")
  103.         return jsonify(f"Alumno con id {id_alumno} no hallado")
  104.        
  105. @app.route("/alumno/<int:i>")
  106. def get_alumno(i):
  107.     try:
  108.         return jsonify({"alumno":alumnos[i-1]})
  109.     except IndexError:
  110.         return jsonify(f"Alumno con id {i} no hallado")
  111.        
  112.  
  113. @app.route("/form", methods=['GET','POST'])
  114. def tomar_formulario():
  115.     if request.method == "GET":
  116.         return formulario.encode('utf-8')
  117.        
  118.     elif request.method == "POST":
  119.         try:
  120.             body = dict(request.form)
  121.             if body['nombre'] and body['cursos']:
  122.                 print(f"""
  123.                -------------------------------------------------------
  124.                Nombre: {body['nombre']} - Cursos: {body['cursos']}
  125.                -------------------------------------------------------
  126.                """)
  127.                
  128.                 # guardo los datos
  129.                 if not alumnos:
  130.                     id_alumno = 1
  131.                 else:
  132.                     id_alumno = alumnos[-1]['id'] + 1
  133.                 alumno = {
  134.                     'id': id_alumno,
  135.                     'nombre': body['nombre'],
  136.                     'cursos': body['cursos'],
  137.                 }
  138.                 alumnos.append(alumno)
  139.                
  140.                 salida = enviado("Mensaje enviado")
  141.             else:
  142.                 salida = enviado("Faltan datos")
  143.             return salida.encode('utf-8')
  144.            
  145.         except Exception:
  146.             salida = enviado("Hubo un error")
  147.             return salida.encode('utf-8')
  148.        
  149.  
  150.  
  151. if __name__ == "__main__":
  152.     app.run(debug=True)
  153.    
  154. """
  155. LINUX:
  156. export FLASK_APP=server.py
  157. flask run
  158.  
  159. WINDOWS:
  160. set FLASK_APP=server.py
  161. python -m flask run
  162. """
  163.  
Advertisement
Add Comment
Please, Sign In to add comment