Pra3t0r5

busqueda

Oct 28th, 2019
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.89 KB | None | 0 0
  1. #Frontend---------------------------------------------------------------------------
  2. # [...]
  3.  {% for p in session['results'] %}
  4.         <tr>
  5.             <td>{{ p['id'] }}</td>
  6.             <td>{{ p['nombre'] }}</td>
  7.             <td>{{ p['descripcion'] }}</td>
  8.             <td>{{ p['importe_unitario'] }}</td>
  9.             <td>{{ p['unidad1'] }}</td>
  10.             <td>
  11. # [...]
  12.  
  13. # Controlador-----------------------------------------------------------------------
  14. from . import FLASH_MSG, db, forms, models
  15. from .models import *
  16.  
  17. @main.route('/buscar', methods=['GET', 'POST'])
  18. def buscar():
  19.     print("GET buscar")
  20.  
  21.     if request.method == "POST":
  22.         # Inicializacion y obtencion de request
  23.         session['results'] = ''
  24.         text = request.get_json(force=True)
  25.         if text == '':
  26.             # si entra vacia obtiene todo
  27.             results = db.session.query(Producto).all()
  28.         else:
  29.             # sino, busca una coincidencia
  30.             results = Producto.query.filter(
  31.                 or_(Producto.nombre.like(text), Producto.descripcion.like(text)))\
  32.                 .first()
  33.  
  34.             if results:
  35.                 # si encontro coincidencia, trae todas las que coincidan
  36.                 results = Producto.query.filter(
  37.                     or_(Producto.nombre.like(text), Producto.descripcion.like(text)))\
  38.                     .all()
  39.             else:
  40.                 # sino retorna que no hay nada
  41.                 flash("%s%s" % (FLASH_MSG.get("PRD_BSQ_FAIL"), text), "warning")
  42.  
  43.         # Mapea el resultado de acuerdo a la clase de SQLAlchemy correspondiente
  44.         prod_schema = ProductoSchema(many=True)
  45.         # funciona
  46.         session['results'] = prod_schema.dump(results)
  47.         # no detecta variable en frontend
  48.         jsonResults = prod_schema.dump(results)
  49.  
  50.         return jsonify(dict(redirect=url_for('main.buscar'), results=jsonResults))
  51.     else:
  52.         return render_template('busqueda.html')
  53.  
  54. # Modelo-----------------------------------------------------------------------
  55. # [...]
  56. from . import db, ma
  57.  
  58. class Producto(db.Model, SerializerMixin):
  59.     __tablename__ = 'producto'
  60.  
  61.     id = db.Column(Integer, primary_key=True)
  62.     nombre = db.Column(String(45), nullable=False)
  63.     descripcion = db.Column(String(256))
  64.     importe_unitario = db.Column(Float(asdecimal=True), nullable=False)
  65.     unidad = db.Column(ForeignKey('unidad.id',
  66.                                   onupdate='CASCADE'), nullable=False, index=True)
  67.     ingrediente = db.Column(ForeignKey(
  68.         'ingrediente.id', onupdate='CASCADE'), nullable=False, index=True)
  69.  
  70.     ingrediente1 = db.relationship('Ingrediente')
  71.     unidad1 = db.relationship('Unidad')
  72.  
  73.     def __init__(self, nom, desc, imp_unitario, uni, ingred):
  74.         self.nombre = nom
  75.         self.descripcion = desc
  76.         self.importe_unitario = imp_unitario
  77.         self.unidad = uni
  78.         self.ingrediente = ingred
  79.         print('<Producto {}>:{}'.format(self.nombre, self.__dict__))
  80.  
  81.     def ver(self):
  82.         return '<Product {}>'.format(self.nombre)
  83.  
  84. class ProductoSchema(ma.ModelSchema):
  85.     class Meta:
  86.         model = Producto
  87.         sqla_session = db.session
  88. # [...]
  89.  
  90. # Init-----------------------------------------------------------------------
  91. # [...]
  92. from flask_marshmallow import Marshmallow
  93.  
  94. ma = ''
  95. def create_app():
  96.     """Crea el core de la aplicacion, inicializando el ORM y los dos controladores principales (auth y main)"""
  97.  
  98.     app = Flask(__name__)
  99.  
  100.     app.debug = True
  101.     app.config['SECRET_KEY'] = 'C3rVew38bIrR4ru1e5'
  102.     app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI.get('local2')
  103.     app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
  104.    
  105.  
  106.    
  107.     db.init_app(app)
  108.     with app.app_context():
  109.         lm = LoginManager()
  110.         lm.login_view = 'auth.login'
  111.         lm.init_app(app)
  112.        
  113.         global ma
  114.         ma = Marshmallow(app)
  115. # [...]
Advertisement
Add Comment
Please, Sign In to add comment