Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Frontend---------------------------------------------------------------------------
- # [...]
- {% for p in session['results'] %}
- <tr>
- <td>{{ p['id'] }}</td>
- <td>{{ p['nombre'] }}</td>
- <td>{{ p['descripcion'] }}</td>
- <td>{{ p['importe_unitario'] }}</td>
- <td>{{ p['unidad1'] }}</td>
- <td>
- # [...]
- # Controlador-----------------------------------------------------------------------
- from . import FLASH_MSG, db, forms, models
- from .models import *
- @main.route('/buscar', methods=['GET', 'POST'])
- def buscar():
- print("GET buscar")
- if request.method == "POST":
- # Inicializacion y obtencion de request
- session['results'] = ''
- text = request.get_json(force=True)
- if text == '':
- # si entra vacia obtiene todo
- results = db.session.query(Producto).all()
- else:
- # sino, busca una coincidencia
- results = Producto.query.filter(
- or_(Producto.nombre.like(text), Producto.descripcion.like(text)))\
- .first()
- if results:
- # si encontro coincidencia, trae todas las que coincidan
- results = Producto.query.filter(
- or_(Producto.nombre.like(text), Producto.descripcion.like(text)))\
- .all()
- else:
- # sino retorna que no hay nada
- flash("%s%s" % (FLASH_MSG.get("PRD_BSQ_FAIL"), text), "warning")
- # Mapea el resultado de acuerdo a la clase de SQLAlchemy correspondiente
- prod_schema = ProductoSchema(many=True)
- # funciona
- session['results'] = prod_schema.dump(results)
- # no detecta variable en frontend
- jsonResults = prod_schema.dump(results)
- return jsonify(dict(redirect=url_for('main.buscar'), results=jsonResults))
- else:
- return render_template('busqueda.html')
- # Modelo-----------------------------------------------------------------------
- # [...]
- from . import db, ma
- class Producto(db.Model, SerializerMixin):
- __tablename__ = 'producto'
- id = db.Column(Integer, primary_key=True)
- nombre = db.Column(String(45), nullable=False)
- descripcion = db.Column(String(256))
- importe_unitario = db.Column(Float(asdecimal=True), nullable=False)
- unidad = db.Column(ForeignKey('unidad.id',
- onupdate='CASCADE'), nullable=False, index=True)
- ingrediente = db.Column(ForeignKey(
- 'ingrediente.id', onupdate='CASCADE'), nullable=False, index=True)
- ingrediente1 = db.relationship('Ingrediente')
- unidad1 = db.relationship('Unidad')
- def __init__(self, nom, desc, imp_unitario, uni, ingred):
- self.nombre = nom
- self.descripcion = desc
- self.importe_unitario = imp_unitario
- self.unidad = uni
- self.ingrediente = ingred
- print('<Producto {}>:{}'.format(self.nombre, self.__dict__))
- def ver(self):
- return '<Product {}>'.format(self.nombre)
- class ProductoSchema(ma.ModelSchema):
- class Meta:
- model = Producto
- sqla_session = db.session
- # [...]
- # Init-----------------------------------------------------------------------
- # [...]
- from flask_marshmallow import Marshmallow
- ma = ''
- def create_app():
- """Crea el core de la aplicacion, inicializando el ORM y los dos controladores principales (auth y main)"""
- app = Flask(__name__)
- app.debug = True
- app.config['SECRET_KEY'] = 'C3rVew38bIrR4ru1e5'
- app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI.get('local2')
- app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
- db.init_app(app)
- with app.app_context():
- lm = LoginManager()
- lm.login_view = 'auth.login'
- lm.init_app(app)
- global ma
- ma = Marshmallow(app)
- # [...]
Advertisement
Add Comment
Please, Sign In to add comment