def updateRegistered(self, **kw): print(kw) current_student = DBSession.query(Student).filter_by(student_id=kw["student_id"]).first() current_course = DBSession.query(Course).filter_by(code=kw["course_name"]).first() current_student.courses.append(current_course) DBSession.flush() return dict(total=200, page=1, records=500, rows=kw)
def alertPrestamo(self, **kw): usuario_id = kw["usuario_id"] book_id = kw["book_id"] error = "ok" books = [] # lista de libros usuario = DBSession.query(Usuario).filter_by( usuario_id=usuario_id).first() # Busca el Usuario print(usuario) count = 0 for item in usuario.book: # Busca los libros que ya tiene el usuario asignado books.append(item) # Agregalos a la lista count += 1 if count < 3: if usuario != None: # Si existe el usuario busca el libro book = DBSession.query(Book).filter_by( book_id=book_id).first() # Busca el libro if book != None: # Si existe el libro if book not in books: # Si el libro no lo tiene el usuario aun books.append(book) # Agrega el libro a la lista else: error = "Ya lo tiene asignado" usuario.book = books # Agrega a la lista de libros al usuario else: error = "Ya tiene 3 libros asignados. No puede sacar más libros" return dict(book=book)
def loadRegistered(self, **kw): registros = DBSession.query(student_course_table).all() relacion = [] for registro in registros: student = DBSession.query(Student).filter_by(student_id=registro.student_id).first() course = DBSession.query(Course).filter_by(course_id=registro.course_id).first() relacion.append({'student_id': student.student_id, 'course_id': course.course_id, 'student_name': student.name, 'course_name': course.name }) return dict(total=200, page=1, records=500, rows=relacion)
def DeleteRegistered(self, **kw): print(kw) student_id = kw["student_id"] course_id = kw["course_id"] print(student_id) print(course_id) current_student = DBSession.query(Student).filter_by(student_id=student_id).first() current_course = DBSession.query(Course).filter_by(course_id=course_id).first() current_student.courses.remove(current_course) DBSession.flush() return dict()
def saveFile(self, **kw): print(kw) name = kw["name"] age = kw["age"] phone = kw["phone"] email_address = kw["email_address"] if name == "" or age == "" or phone == "" or email_address == "": return dict(error="Campos obligatorios") if kw["usuario_id"] == "0": if kw["image"] == "undefined": return dict(error="Archivo obligatorio") handler = Usuario() i = 0 else: handler = DBSession.query(Usuario).filter_by( usuario_id=kw['usuario_id']).first() i = 1 if kw["image"] != "undefined": image = kw["image"] if image.file: fileName = image.filename if fileName.find(".png") > 0 or fileName.find( ".jpeg") > 0 or fileName.find( ".jpg") > 0 or fileName.find( ".doc") > 0 or fileName.find( ".PDF") > 0 or fileName.find(".pdf") > 0: ftyoe = "" if fileName.find(".png") > 0 or fileName.find( ".jpeg") > 0 or fileName.find(".jpg") > 0: ftyoe = "image" if fileName.find(".doc") > 0: ftyoe = "doc" if fileName.find(".pdf") > 0: ftyoe = "pdf" if fileName.find(".PDF") > 0: ftyoe = "pdf" handler.image = image.file.read() else: return dict( error="Archivo obligatorio de tipo PNG, JPEG, DOC, PDF" ) handler.name = name handler.age = age handler.phone = phone handler.email_address = email_address if i == 0: DBSession.add(handler) DBSession.flush() return dict(error="ok", usuario_id=handler.usuario_id)
def DeletePrestamo(self, **kw): print(kw) usuario_id = kw["usuario_id"] book_id = kw["book_id"] print(usuario_id) print(book_id) current_usuario = DBSession.query(Usuario).filter_by( usuario_id=usuario_id).first() current_book = DBSession.query(Book).filter_by(book_id=book_id).first() current_usuario.books.remove(current_book) DBSession.flush() return dict()
def addLoan(self, **kw): phone_id = kw["phone_id"] amount = kw["amount"] due_date = kw["due_date"] query = DBSession.query(PhoneBook).filter_by(id=phone_id).first() if query is not None: newLoan = Loans() newLoan.phone_id = phone_id newLoan.amount = amount newLoan.due_date = due_date query.loans.append(newLoan) DBSession.add(newLoan) DBSession.flush() return dict(ok="ok")
def get_query(self): ''' Returns query with all the objects :return: ''' if not self.query: if self.sord == "asc": self.query = DBSession.query(self.model_class).order_by( asc(self.sidx)) else: self.query = DBSession.query(self.model_class).order_by( desc(self.sidx)) #self.query = self.session.query(self.model_class) return self.query
def loadSubGridCursos(self, **kw): relacion = [] print(kw) current_student = DBSession.query(Student).filter_by(student_id=kw["student_id"]).first()# for item in current_student.courses: print(item.course_id) relacion.append({'course_id': item.course_id, 'code': item.code, 'name': item.name }) print(relacion) return dict(total=200, page=1, records=500, rows=relacion)
def openClose(self, **kw): handler_user = DBSession.query(prestamo_books_table).filter_by( usuario_id=kw['id']).all() kw['usuario'] = DBSession.query(Usuario).filter_by( usuario_id=kw['id']).first() kw['book'] = [] kw['image'] = "" for item in handler_user: handler_book = DBSession.query(Book).filter_by( book_id=item.book_id).first() if handler_book != None: kw['book'].append({'book_name': handler_book.book_name}) if kw['usuario'].image != None: kw['image'] = base64.b64encode(kw['usuario'].image) kw['image'] = str(kw['image']).replace("b'", "") kw['image'] = str(kw['image']).replace("'", "") dialogtemplate = render_template(kw, "mako", 'myproject.templates.libreria.hello') return dict(dialogtemplate=dialogtemplate)
def connection(self, **kw): tracker = DBSession.query(Tracker).all( ) #tracker recibe todos los elementos de la base de datos kw['tracker'] = [ ] #Declaramos una nueva lista dentro del diccionario kw que tiene por llave 'tracker' for item in tracker: #Iteramos cada elemento que este denro de trecker de la base de datos kw['tracker'].append({ 'id': item.id, 'imei': item.imei, 'ticket': item.ticket, 'name': item.name }) #agregr diccionarios a la lista kw 'tracker' return dict(page='connection', kw=kw)
def addUsuario(self, **kw): print(kw) if kw["usuario_id"] == "0": kw['handler'] = Usuario() print(kw) else: kw['handler'] = DBSession.query(Usuario).filter_by( usuario_id=kw['usuario_id']).first() print(kw) dialogagrega = render_template( kw, "mako", 'myproject.templates.libreria.agregausuario') print(kw) return dict(dialogagrega=dialogagrega)
def tablaBaseConec(self, **kw): prestamos = DBSession.query(prestamo_books_table).all( ) # prestamos recibe todos los elementos de la tabla prestamos relacion = [] # Se crea una nueva lista donde almacenaremos datos for prestamo in prestamos: # Recorremos los elementos de prestamos usuario = DBSession.query(Usuario).filter_by( usuario_id=prestamo.usuario_id ).first( ) # la variable usuario recibe elementos de la tabla Usuario donde usuario_id es igual a la misma posicion en prestamos libro = DBSession.query(Book).filter_by( book_id=prestamo.book_id ).first( ) # la variable libro recibe elementos de la tabla Book donde book_id es igual a la misma posicion en prestamos relacion.append( { 'usuario_id': usuario.name, 'book_id': libro.book_name } ) # Se regresa a relacion cada posicion recorrida en prestamos y se envia el nombre de las tablas Book y Usuario return dict( total=200, page=1, records=500, rows=relacion ) # Regresamos un Json con formato total, page, records, rows que es como lo requiere nuestro jqgrid
def setUp(self): """Setup test fixture for each model test method.""" try: new_attrs = {} new_attrs.update(self.attrs) new_attrs.update(self.do_get_dependencies()) self.obj = self.klass(**new_attrs) DBSession.add(self.obj) DBSession.flush() return self.obj except: DBSession.rollback() raise
def loadDetail(self): my_filters = {self.indexkey: self.kw['id']} query = DBSession.query(self.model) for attr, value in my_filters.items(): query = query.filter(getattr(self.model, attr) == value) window = query.all() records = [] fields = [] for rw in window: for column in rw.__table__.columns: #print(column.name) fields.append(getattr(rw, column.name)) records.append({ self.indexkey: str(getattr(rw, self.indexkey)), 'cell': fields }) fields = [] #print(records) return dict(rows=records)
def by_email_address(cls, email): """Return the user object whose email address is ``email``.""" return DBSession.query(cls).filter_by(email_address=email).first()
def by_user_name(cls, username): """Return the user object whose user name is ``username``.""" return DBSession.query(cls).filter_by(user_name=username).first()
def updateGrid(self): if "oper" in self.kw: if self.kw['oper'] == "edit": print("edit") # print("id:{}".format(self.kw['id'])) # for key, value in self.kw.iteritems(): # print "%s = %s" % (key, value) my_filters = {self.indexkey: self.kw['id']} query = DBSession.query(self.model) for attr, value in my_filters.items(): query = query.filter(getattr(self.model, attr) == value) item = query.first() if item is not None: #print("None Edit") for column in item.__table__.columns: if column.name != self.indexkey: if column.name in self.kw: if str(column.type) == "BOOLEAN": newvalue = True if self.kw[ column.name] == "True" else False else: newvalue = self.kw[column.name] #print("updating: {} to {} type:{}".format(column.name, self.kw[column.name],str(column.type))) setattr(item, column.name, newvalue) DBSession.flush() if self.kw['oper'] == "add": item = self.model() #print("add") for column in item.__table__.columns: if column.name in self.kw: #print("{}={}".format(str(column.name),str(self.kw[column.name]))) if (self.indexkey == column.name): pass else: setattr(item, column.name, self.kw[column.name]) DBSession.add(item) DBSession.flush() if self.kw['oper'] == "del": my_filters = {self.indexkey: self.kw['id']} query = DBSession.query(self.model) for attr, value in my_filters.items(): query = query.filter(getattr(self.model, attr) == value) item = query.first() if item is not None: DBSession.delete(item) DBSession.flush() return dict(error="")
def tearDown(self): """Tear down test fixture for each model test method.""" DBSession.rollback()
def test_query_obj(self): """Model objects can be queried""" obj = DBSession.query(self.klass).one() for key, value in self.attrs.items(): eq_(getattr(obj, key), value)