123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389 |
- from flask import Flask, render_template, request, redirect, jsonify
-
- from flask_sqlalchemy import SQLAlchemy
-
- import datetime
- import json
- import urllib.request
- import os
- import csv
- import sys
-
- app = Flask(__name__)
-
-
- connect = 'mysql+pymysql://root@localhost/restaurante'
-
- app.config['SQLALCHEMY_DATABASE_URI'] = connect
-
- db = SQLAlchemy(app)
-
- path_to_upload = os.getcwd() + '/static'
-
- if os.path.isdir(path_to_upload):
- app.config['UPLOAD_FOLDER'] = path_to_upload
- else:
- os.mkdir(path_to_upload)
- app.config['UPLOAD_FOLDER'] = path_to_upload
-
-
- class ordenes(db.Model):
- id = db.Column(db.Integer, autoincrement=True, primary_key=True)
- nombre_cliente = db.Column(db.String(60))
- fecha = db.Column((db.DateTime), default=datetime.datetime.utcnow)
- num_celular = db.Column(db.String(14))
-
-
- class comida(db.Model):
- id = db.Column(db.Integer, autoincrement=True, primary_key=True)
- categoria = db.Column(db.String(20))
- path_a_imagen = db.Column(db.String(50))
- nombre = db.Column(db.String(50))
- precio = db.Column(db.Float)
- descripcion = db.Column(db.Text)
- comida_bebida = db.Column(db.Integer)
-
-
- class orden_comida(db.Model):
- orden_id = db.Column(db.Integer, db.ForeignKey(ordenes.id))
- comida_id = db.Column(db.Integer, db.ForeignKey(comida.id))
- id = db.Column(db.Integer, autoincrement=True, primary_key=True)
- peticion = db.Column(db.Text, default=None)
-
-
- class orden_servidas(db.Model):
- orden_id = db.Column(db.Integer, db.ForeignKey(
- ordenes.id), primary_key=True)
-
-
- @app.route('/')
- def menu():
- return render_template('home.html', descripcion='Restaurante Ejemplo')
-
-
- @app.route('/ElMenuCategorizado')
- def ElMenuCategorizado():
- categorias = db.engine.execute(
- 'SELECT DISTINCT categoria from comida where comida_bebida =0')
- return render_template('ElMenuCategorizado.html', descripcion='El Menú', categorias=categorias)
-
-
- @app.route('/view/<string:categoriaStr>', methods=['POST', 'GET'])
- def viewItem(categoriaStr):
- if request.method == 'POST':
-
- files = request.files['imagen']
- if files:
- filename = (files.filename)
- files.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
-
- post_nombre = request.form['nombre']
- post_descripcion = request.form['descripcion']
- post_precio = float(request.form['Precio'])
- try:
- post_categoria = request.form['selectCat']
- if post_categoria == '0':
- post_categoria = request.form['nuevaCategoria']
- except KeyError:
- post_categoria = categoriaStr
-
- post_id = request.form['idItem']
-
- if files:
- db.engine.execute(
- 'update comida set nombre ="{}", descripcion ="{}", precio ={}, categoria ="{}", path_a_imagen ="{}" where id = {}'.format(post_nombre, post_descripcion, post_precio, post_categoria, files.filename, post_id))
- else:
- db.engine.execute(
- 'update comida set nombre ="{}", descripcion ="{}", precio ={}, categoria ="{}" where id = {}'.format(post_nombre, post_descripcion, post_precio, post_categoria, post_id))
-
- db.session.commit()
- return redirect('/view/'+categoriaStr)
- else:
-
- items = comida.query.filter_by(categoria=categoriaStr).all()
- categorias = db.engine.execute(
- 'SELECT DISTINCT categoria from comida where comida_bebida=0')
- return render_template('verComida.html', link='view', descripcion=categoriaStr, items=items, categorias=categorias)
-
-
- @app.route('/deleteItem/<string:categoriaStr>/<int:itemId>')
- def deleteItem(categoriaStr, itemId):
- item = comida.query.filter_by(id=itemId).first()
- db.session.delete(item)
- db.session.commit()
-
- return redirect('/view/'+categoriaStr)
-
-
- @app.route('/csvMenu', methods=['POST', 'GET'])
- def csvMenu():
- if request.method == 'POST':
-
- files = request.files['CSV_file']
- if files:
- filename = (files.filename)
- files.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
-
- with open(os.getcwd() + '/static/'+filename) as csv_file:
- csv_reader = csv.reader(csv_file, delimiter=',')
-
- for row in csv_reader:
-
- try:
-
- post_nombre = row[0]
-
- post_descripcion = row[1]
-
- post_precio = float(row[2])
- post_categoria = row[3]
- post_nombreImagen = row[4]
- post_comidaBebida = int(row[5])
-
- db.session.add(comida(nombre=row[0], descripcion=row[1], precio=float(row[2]),
- path_a_imagen=row[4], comida_bebida=row[5], categoria=row[3]))
- db.session.commit()
-
- except ValueError:
- continue
- return redirect('/')
-
- else:
- return render_template('csvMenu.html', descripcion='Subir CSV')
-
-
- @app.route('/addItem', methods=['POST', 'GET'])
- def addItem():
-
- if request.method == 'POST':
- files = request.files['imagen']
- if files:
- filename = (files.filename)
- files.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
-
- post_nombre = request.form['nombre']
- post_descripcion = request.form['descripcion']
- post_precio = float(request.form['Precio'])
- post_categoria = request.form['categoria']
-
- if post_categoria == '0':
-
- post_categoria = request.form['nuevaCategoria']
- post_tipo = request.form['tipoDeItem']
-
- db.session.add(comida(nombre=post_nombre, categoria=post_categoria, descripcion=post_descripcion,
- precio=post_precio, path_a_imagen=files.filename, comida_bebida=post_tipo))
- db.session.commit()
- return redirect('/addItem')
- else:
- categorias = db.engine.execute(
- 'SELECT DISTINCT categoria from comida where comida_bebida =0')
- return render_template('addItem.html', descripcion='Añadir item al menú', categorias=categorias)
-
-
- @app.route('/viewBebidas')
- def viewBebidas():
- categorias = db.engine.execute(
- 'SELECT DISTINCT categoria from comida where comida_bebida =1')
- return render_template('LasBebidas.html', descripcion='El Menú', categorias=categorias)
-
-
- last_entry = 0
-
-
- @app.route('/ordenes', methods=['POST', 'GET'])
- def ordenesFun():
- if request.method == 'POST':
- post_order = int(request.get_json()['order'])
- db.engine.execute(
- 'delete from `ordenes` where id = {}'.format(post_order))
- db.engine.execute(
- 'delete from `orden_comida` where orden_id ={}'.format(post_order))
- db.session.commit()
- return redirect('/ordenes')
-
- else:
- global last_entry
- ordenesJson = {}
- ordenesCompletas = ordenes.query.all()
- for orden in ordenesCompletas:
- print(orden.id, file=sys.stderr)
- query2 = db.engine.execute(
- 'SELECT comida_id, peticion, categoria, nombre, precio, comida_bebida FROM `ordenes`, `orden_comida`, comida where comida.id=orden_comida.comida_id and ordenes.id = orden_comida.orden_id and orden_comida.orden_id = {} ORDER BY ordenes.id '.format(orden.id))
-
- ordenFull = []
- for comida in query2:
- ordenesDict = {}
- ordenesDict['comida_id'] = comida.comida_id
- ordenesDict['peticion'] = comida.peticion
- ordenesDict['nombre'] = comida.nombre
- ordenesDict['categoria'] = comida.categoria
- ordenesDict['precio'] = comida.precio
- ordenesDict['comida_bebida'] = comida.comida_bebida
-
- ordenFull.append(ordenesDict)
-
- print(ordenFull, file=sys.stderr)
- ordenesJson.setdefault(orden.id, {})['ordenCompleta'] = ordenFull
- ordenesJson[orden.id]['nombre'] = orden.nombre_cliente
- ordenesJson[orden.id]['num_celular'] = orden.num_celular
- ordenesJson[orden.id]['fecha'] = orden.fecha
- last_entry = orden.id
- return render_template('ordenes.html', ordenes=ordenesJson, descripcion='Ordenes Pendientes')
-
-
- @app.route('/retrieveMenu', methods=['POST', 'GET'])
- def retrieveMenu():
- if request.method == "GET":
- categoriasDeComida = db.engine.execute(
- "select categoria from comida where comida_bebida =0")
- comidaDict = {}
- for categoria in categoriasDeComida:
-
- query = db.engine.execute(
- "select * from comida where categoria ='{}'".format(categoria['categoria']))
- comidaDict[categoria['categoria']] = {}
- for item in query:
-
- comidaDict[categoria['categoria']][item['id']] = {}
- comidaDict[categoria['categoria']
- ][item['id']]['nombre'] = item['nombre']
- comidaDict[categoria['categoria']
- ][item['id']]["precio"] = item["precio"]
- comidaDict[categoria['categoria']
- ][item['id']]["descripcion"] = item["descripcion"]
- comidaDict[categoria['categoria']
- ][item['id']]["path_a_imagen"] = item["path_a_imagen"]
-
- categoriasDeBebidas = db.engine.execute(
- "select categoria from comida where comida_bebida=1")
- bebidaDict = {}
- for categoria in categoriasDeBebidas:
-
- query = db.engine.execute(
- "select * from comida where categoria ='{}'".format(categoria['categoria']))
- bebidaDict[categoria['categoria']] = {}
- for item in query:
-
- bebidaDict[categoria['categoria']][item['id']] = {}
- bebidaDict[categoria['categoria']
- ][item['id']]['id'] = item['id']
- bebidaDict[categoria['categoria']
- ][item['id']]['nombre'] = item['nombre']
- bebidaDict[categoria['categoria']
- ][item['id']]["precio"] = item["precio"]
- bebidaDict[categoria['categoria']
- ][item['id']]["descripcion"] = item["descripcion"]
- bebidaDict[categoria['categoria']
- ][item['id']]["path_a_imagen"] = item["path_a_imagen"]
-
- wholeDict = {"comidas": comidaDict, "bebidas": bebidaDict}
- print(wholeDict)
-
- return jsonify(wholeDict)
-
-
- @app.route('/papelonDeComida', methods=['POST', 'GET'])
- def papelonDeComida():
- global last_entry
- if request.method == 'GET':
- ordenesJson = {}
- ordenesCompletas = ordenes.query.filter(
- ordenes.id > last_entry).all()
- for orden in ordenesCompletas:
-
- query2 = db.engine.execute(
- 'SELECT comida_id, peticion, categoria, nombre, precio, comida_bebida FROM `ordenes`, `orden_comida`, comida where comida.id=orden_comida.comida_id and ordenes.id = orden_comida.orden_id and orden_comida.orden_id = {} ORDER BY ordenes.id '.format(orden.id))
-
- ordenFull = []
- for comida in query2:
- ordenesDict = {}
- ordenesDict['comida_id'] = comida.comida_id
- ordenesDict['peticion'] = comida.peticion
- ordenesDict['nombre'] = comida.nombre
- ordenesDict['categoria'] = comida.categoria
- ordenesDict['precio'] = comida.precio
- ordenesDict['comida_bebida'] = comida.comida_bebida
-
- ordenFull.append(ordenesDict)
-
- print(ordenFull, file=sys.stderr)
- ordenesJson.setdefault(orden.id, {})['ordenCompleta'] = ordenFull
- ordenesJson[orden.id]['nombre'] = orden.nombre_cliente
- ordenesJson[orden.id]['num_celular'] = orden.num_celular
- ordenesJson[orden.id]['fecha'] = orden.fecha
- last_entry = orden.id
- return jsonify(ordenesJson)
- else:
- print('vamos a insertar', file=sys.stderr)
- post_nombre = request.get_json()[0]['nombre']
- post_num = request.get_json()[0]['celular']
- post_order = []
- post_order.append(request.get_json()[0]['ordenCompleta'])
- post_order.append(request.get_json()[0]['peticiones'])
-
- print(post_order, file=sys.stderr)
-
- db.session.add(
- ordenes(nombre_cliente=post_nombre, num_celular=post_num))
- db.session.commit()
- last_id = ordenes.query.order_by(ordenes.id.desc()).first().id
- print(last_id, file=sys.stderr)
- for order in post_order[0]:
- try:
- print(order, file=sys.stderr)
- post_peti = post_order[1][order]
- except KeyError as k:
- post_peti = ""
-
- db.session.add(orden_comida(orden_id=last_id,
- comida_id=post_order[0][order], peticion=post_peti))
-
- print("Insertando", file=sys.stderr)
- db.session.commit()
-
- return "YOU DID IT"
-
-
- @app.route('/viewBebidas/<string:categoriaStr>', methods=['POST', 'GET'])
- def viewBebida(categoriaStr):
- if request.method == 'POST':
-
- files = request.files['imagen']
- if files:
- filename = (files.filename)
- files.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
-
- post_nombre = request.form['nombre']
- post_descripcion = request.form['descripcion']
- post_precio = float(request.form['Precio'])
- try:
- post_categoria = request.form['selectCat']
- print(post_categoria)
- if post_categoria == '0':
- print('im here')
- post_categoria = request.form['nuevaCategoria']
- except KeyError:
- post_categoria = categoriaStr
-
- post_id = request.form['idItem']
-
- if files:
- db.engine.execute(
- 'update comida set nombre ="{}", descripcion ="{}", precio ={}, categoria ="{}", path_a_imagen ="{}" where id = {}'.format(post_nombre, post_descripcion, post_precio, post_categoria, files.filename, post_id))
- else:
- db.engine.execute(
- 'update comida set nombre ="{}", descripcion ="{}", precio ={}, categoria ="{}" where id = {}'.format(post_nombre, post_descripcion, post_precio, post_categoria, post_id))
-
- db.session.commit()
- return redirect('/viewBebidas/'+categoriaStr)
- else:
-
- items = comida.query.filter_by(categoria=categoriaStr).all()
- categorias = db.engine.execute(
- 'SELECT DISTINCT categoria from comida where comida_bebida =1')
- return render_template('verComida.html', link='viewBebidas', descripcion=categoriaStr, items=items, categorias=categorias)
-
-
- if __name__ == "__main__":
- app.run(debug=True, threaded=True,)
|