Exemple #1
0
class HelloWorldService(DefinitionBase):
    max = 5000  # adjust to your taste

    @rpc(String, Integer, _returns=Array(String))
    def say_hello(self, name, times):
        results = []
        for i in range(0, times):
            results.append('Hello, %s' % name)
        return results

    @rpc(SOAPRequest, _returns=Array(ReturnObject))
    def get_integers(self, req):
        if req == None:
            raise Exception('invalid request: request object is null')

        else:
            if req.startrow < 0:
                raise Exception('invalid request: startrow < 0')

        retval = []
        for i in range(req.startrow, req.startrow + 50):
            retelt = ReturnObject()
            retelt.byone = i
            retelt.bytwo = i * 2
            retelt.bythree = i * 3
            retelt.byfour = i * 4
            retelt.byfive = i * 5

            retval.append(retelt)

        return retval

    @rpc(SOAPRequest, _returns=Integer)
    def get_integers_count(self, req):
        return self.max

    @rpc(_returns=String)
    def name(self):
        return self.__class__.__name__

    @rpc(NestedObject, _returns=NestedObject)
    def get_nested(self, complex):
        retval = NestedObject()
        retval.date_time = datetime.now()

        retval.ro = ReturnObject()
        i = 5
        retval.ro.byone = i
        retval.ro.bytwo = i * 2
        retval.ro.bythree = i * 3
        retval.ro.byfour = i * 4
        retval.ro.byfive = i * 5
        retval.arr = ['asd097n09a', 'askdj0n3t']

        return retval
Exemple #2
0
    def test_class_nested_array(self):
        peeps = []
        names = ['bob', 'jim', 'peabody', 'mumblesleves']

        for name in names:
            a = Person()
            a.name = name
            a.birthdate = datetime.datetime(1979, 1, 1)
            a.age = 27
            a.addresses = []

            for i in range(0, 25):
                addr = Address()
                addr.street = '555 downtown'
                addr.city = 'funkytown'
                a.addresses.append(addr)
            peeps.append(a)

        serializer = Array(Person)
        serializer.resolve_namespace(serializer,__name__)
        element = etree.Element('test')
        serializer.to_xml(peeps, ns_test, element)
        element = element[0]

        self.assertEquals(4, len(element.getchildren()))

        peeps2 = serializer.from_xml(element)
        for peep in peeps2:
            self.assertEquals(27, peep.age)
            self.assertEquals(25, len(peep.addresses))
            self.assertEquals('funkytown', peep.addresses[18].city)
class SAPIntegrationServer(SoapListener.BasicSoapServer):
    """
    This class defines the SOAP actions that should be available to
    clients. All those actions are decorated as a rpc, defining what
    parameters the methods accept, types and what is returned.
    """
    @rpc(String, String, _returns=Array(String))
    def get_person_data(self, id_type, ext_id):
        """
        Based on id-type and the id, identify a person in Cerebrum and
        return name of primary account and primary email address.

        If person exist but doesn't have any accounts return an empty
        list. If no person match id_type, my_id, throw a ...Exception.
        """
        # Allow any type of exception? Does SOAP handle that?
        return CISutils.get_person_data(id_type, ext_id)

    @rpc(Person, _returns=Boolean)
    def update_person(self, Ansatt):
        """
        get sap_person object from client. Convert sap_person from xml
        to object and update Cerebrum.
        """
        ret = False
        xml_person = etree.Element('test')
        Person.to_xml(Ansatt, ns_test, xml_person)
        xml_person = xml_person[0]
        print "xml_person:", etree.tostring(xml_person, pretty_print=True)

        p = SAPXMLPerson2Cerebrum(xml_person)
        #ret = p.update()
        return True

    def on_method_exception_object(self, environ, exc):
        '''
        Called BEFORE the exception is serialized, when an error occurs durring
        execution
        @param the wsgi environment
        @param the exception object
        '''
        print "on_method_exception_object", environ, exc

    def on_method_exception_xml(self, environ, fault_xml):
        '''
        Called AFTER the exception is serialized, when an error occurs durring
        execution
        @param the wsgi environment
        @param the xml element containing the exception object serialized to a
        soap fault
        '''
        print "on_method_exception_xml", environ, fault_xml
Exemple #4
0
class HelloWorldService(DefinitionBase):
    @rpc(String, Integer, _returns=Array(String))
    def say_hello(self, name, times):
        '''
        Docstrings for service methods appear as documentation in the wsdl
        <b>what fun</b>
        @param name the name to say hello to
        @param the number of times to say hello
        @return the completed array
        '''
        results = []
        for i in range(0, times):
            results.append('Hello, %s' % name)
        return results
Exemple #5
0
    def test_array_empty(self):
        serializer = Array(String)
        serializer.resolve_namespace(serializer,"zbank")

        values = []

        element = etree.Element('test')
        serializer.to_xml(values, ns_test, element)
        element = element[0]

        self.assertEquals(len(values), len(element.getchildren()))

        values2 = serializer.from_xml(element)
        self.assertEquals(len(values2), 0)
Exemple #6
0
    def test_class_array(self):
        peeps = []
        names = ['bob', 'jim', 'peabody', 'mumblesleves']
        for name in names:
            a = Person()
            a.name = name
            a.birthdate = datetime.datetime(1979, 1, 1)
            a.age = 27
            peeps.append(a)

        serializer = Array(Person)
        serializer.resolve_namespace(serializer,__name__)

        element = etree.Element('test')
        serializer.to_xml(peeps, ns_test, element)
        element = element[0]

        self.assertEquals(4, len(element.getchildren()))

        peeps2 = serializer.from_xml(element)
        for i in range(0, 4):
            self.assertEquals(peeps2[i].name, names[i])
            self.assertEquals(peeps2[i].birthdate,
                datetime.datetime(1979, 1, 1))
Exemple #7
0
class SW_Usuarios(DefinitionBase):
    @rpc(_returns=Array(Array(primitive.String)))
    def getContratos(self, ):
        m = []
        r = contrato.objects.filter(finalVigencia__gte=datetime.date.today())
        for cont in r:
            m.append([cont.num, cont.zonas])
        return m

    @rpc(primitive.String,
         primitive.String,
         primitive.String,
         _returns=Array(primitive.String))
    def login(self, u, p, c):
        error = []
        user = authenticate(username=u, password=p)
        if user is not None:
            if user.is_active:
                if user.sesion_sico:
                    error = ["El Usuario especificado ya esta en uso."]
                else:
                    try:
                        print c
                        u = usuarioSico.objects.get(user=user, contrato=c)
                    except:
                        u = False
                    if isinstance(u, usuarioSico):
                        if integracion(u.nombre, u.clave, user):
                            error = [
                                'True',
                                str(user.id),
                                str(user.username),
                                str(user.sesion_sico),
                                ('%s %s' % (user.first_name,
                                            user.last_name)).encode('utf-8')
                            ]
                        else:
                            error = [
                                'El Sistema Comercial(Sico Cnel) no esta disponible por el momento, '
                                'intentelo nuevamente mas tarde...'
                            ]
                            user.sesion_sico = ''
                            user.save()
                    else:
                        error = [
                            'El Usuario Especificado no cuenta con permisos necesarios para acceder al contarto'
                        ]

        elif u and p:
            error = [
                "Su Usuario o Contraseña no son correctos, Intentelo nuevamente."
            ]
        return error

    @rpc(primitive.Integer,
         primitive.String,
         primitive.String,
         _returns=primitive.Boolean)
    def logout(self, id, u, s):
        user = User.objects.get(id=id, username=u, sesion_sico=s)
        if user:
            cerrarSico(s)
            user.sesion_sico = ''
            user.save()
            return True
        return False
Exemple #8
0
class SW_Ingresos(DefinitionBase):
    @rpc(primitive.String,
         primitive.String,
         _returns=Array(Array(primitive.String)))
    def realizados(self, idUsuario, contrato):
        rel = posicion.objects.filter(
            actividad__detalledeactividad__rubro__contrato=contrato).filter(
                usuario_id=int(idUsuario),
                fechaHora__gte='%s-%s-%s 00:00:00' %
                (str(datetime.datetime.today().year),
                 str(datetime.datetime.today().month),
                 str(datetime.datetime.today().day))).distinct(
                     'actividad').exclude(actividad=None)

        ret = []

        for r in rel:
            act = r.actividad
            try:
                med = str(
                    act.medidor_set.filter(contrato=None).first().fabrica)
            except:
                med = 'Sin Medidor Desc.'
            ret.append([
                str(act.id),
                str(act.cliente.cuenta),
                str(act.cliente.nombre),
                str(act.tipoDeSolicitud.descripcion), med,
                str(act.tipoDeSolicitud.id),
                str(act.observaciones)
            ])
        print ret
        return ret

    @rpc(_returns=Array(Array(primitive.String)))
    def ingresoActividadInstalador(self, ):
        return [[str(v) for v in empleado.objects.all()],
                [str(v) for v in cuadrilla.objects.all()],
                [str(v) for v in tipoDeSolicitud.objects.all()]]

    @rpc(primitive.String, _returns=Array(primitive.String))
    def ingresoActividadInstaladorActividadSeleccionada(self, ide):
        act = actividad.objects.get(id=int(ide))
        return [
            str(act.instalador.nombre),
            str(act.instalador.cuadrilla),
            str(act.tipoDeSolicitud),
            str(act.fechaDeActividad),
            str(act.horaDeActividad)
        ]

    @rpc(primitive.String, _returns=Array(primitive.String))
    def ingresoDatosAbonadoSeleccionado(self, ide):
        act = actividad.objects.get(id=int(ide))
        m = act.medidor_set.all().filter(contrato=None)

        if m.count() <= 0:
            return [
                str(act.cliente.cuenta),
                str(act.cliente.ci_ruc),
                str(act.cliente.nombre),
                str(act.cliente.estado),
                str(act.cliente.telefono),
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                str(act.cliente.id),
            ]

        else:
            return [
                str(act.cliente.cuenta),
                str(act.cliente.ci_ruc),
                str(act.cliente.nombre),
                str(act.cliente.estado),
                str(act.cliente.telefono),
                str(act.cliente.ubicacionGeografica.parroquia.descripcion),
                str(act.cliente.ubicacionGeografica.calle.descripcion1),
                str(act.cliente.geocodigo),
                str(m.first().fabrica),
                str(m.first().serie),
                str(m.first().marca),
                str(m.first().lectura),
                str(act.cliente.id)
            ]

    @rpc(_returns=Array(Array(primitive.String)))
    def ingresoDetalleInstalacion(self, ):
        return [[str(v) for v in materialDeLaRed.objects.all()],
                [str(v) for v in formaDeConexion.objects.all()],
                [str(v) for v in estadoDeUnaInstalacion.objects.all()],
                [str(v) for v in tipoDeConstruccion.objects.all()],
                [str(v) for v in ubicacionDelMedidor.objects.all()],
                [str(v) for v in tipoDeAcometidaRed.objects.all()],
                [str(v) for v in calibreDeLaRed.objects.all()],
                [str(v) for v in usoDeEnergia.objects.all()],
                [str(v) for v in claseRed.objects.all()],
                [str(v) for v in tipoDeServicio.objects.all()],
                [str(v) for v in usoEspecificoDelInmueble.objects.all()],
                [str(v) for v in demanda.objects.all()],
                [str(v) for v in nivelSocieconomico.objects.all()]]

    @rpc(primitive.String, _returns=Array(primitive.String))
    def ingresoDetalleInstalacionSeleccionada(self, ide):
        act = actividad.objects.get(id=int(ide))

        r = [
            str(act.materialDeLaRed),
            str(act.formaDeConexion),
            str(act.estadoDeLaInstalacion),
            str(act.tipoDeConstruccion),
            str(act.ubicacionDelMedidor),
            str(act.tipoDeAcometidaRed),
            str(act.calibreDeLaRed),
            str(act.usoDeEnergia),
            str(act.claseRed),
            str(act.tipoDeServicio),
            str(act.usoEspecificoDelInmueble),
            str(act.demanda),
            str(act.nivelSocieconomico)
        ]
        print r
        return r

    @rpc(primitive.String, _returns=Array(Array(primitive.String)))
    def ingresoMateriales(self, contrato):
        return [
            [
                str(v) for v in detalleMaterialContrato.objects.filter(
                    contrato=contrato).exclude(
                        material__tipoDeMaterial__material__descripcion='KIT ')
            ],
            [
                str(v) for v in sello.objects.filter(
                    detalleMaterialContrato__contrato=contrato, utilizado=None)
            ], ['Caja', 'Bornera', 'Panel', 'N/A']
        ]

    @rpc(primitive.String,
         primitive.String,
         _returns=Array(Array(primitive.String)))
    def ingresoMaterialesSeleccionados(self, ide, cont):
        act = actividad.objects.get(id=int(ide))
        deta = act.detalledeactividad_set.all()
        mat = act.materialdeactividad_set.all()
        sell = act.sello_set.all()

        print act.cliente.cuenta
        print cont

        try:
            if len(
                    list(
                        deta.filter(actividad=act,
                                    rubro=detalleRubro.objects.get(
                                        servicio__id=3, rubro__id=1)))) > 0:
                reubicacion = True
            else:
                reubicacion = False
        except:
            reubicacion = False

        try:
            if len(
                    list(
                        deta.filter(actividad=act,
                                    rubro=detalleRubro.objects.get(
                                        servicio__id=4, rubro__id=4)))) > 0:
                contrastacion = True
            else:
                contrastacion = False
        except:
            contrastacion = False

        try:
            if len(
                    list(
                        deta.filter(actividad=act,
                                    rubro=detalleRubro.objects.get(
                                        servicio__id=6, rubro__id=2)))) > 0:
                directo = True
            else:
                directo = False
        except:
            directo = False

        b = [[str(reubicacion), ""], [str(contrastacion), ""],
             [str(directo), ""], [str(v.cantidad) for v in mat],
             [str(v.material) for v in mat], [str(v) for v in sell],
             [str(v.ubicacion) for v in sell]]
        print b
        return b

    @rpc(primitive.String, _returns=Array(primitive.String))
    def ingresoMedidorInstalado(self, contrato):
        return [
            str(v) for v in medidor.objects.filter(
                contrato__contrato=contrato, est=True, actividad=None)
        ]

    @rpc(primitive.String,
         primitive.String,
         primitive.String,
         _returns=Array(primitive.String))
    def ingresoMedidorInstaladoSel(self, contrato, med, ide):
        medidores = medidor.objects.filter(contrato__contrato=contrato,
                                           est=True,
                                           actividad=None).order_by('fabrica')
        print ide
        print med
        if ide:
            medidores = medidor.objects.filter(
                contrato__contrato=contrato,
                actividad=actividad.objects.get(id=int(ide)))

        for m in medidores:
            if med == str(m.__unicode__()):
                return [
                    str(m.id),
                    str(m.fabrica),
                    str(m.serie),
                    str(m.marca),
                    str(m.tipo),
                    str(m.lectura)
                ]

        return []

    @rpc(primitive.String, primitive.String, _returns=Array(primitive.String))
    def ingresoMedidorInstaladoSeleccionado(self, contrato, ide):
        medidores = medidor.objects.filter(
            contrato__contrato=contrato,
            actividad=actividad.objects.get(id=int(ide)))
        print ide
        if medidores.first():
            m = medidores.first()
            return [str(m)]

        return []

    @rpc(primitive.String, _returns=Array(primitive.String))
    def ingresosReferenciaSeleccionada(self, ide):
        act = actividad.objects.get(id=int(ide))
        deta = detalleClienteReferencia.objects.get(cliente=act.cliente)
        medidores = deta.referencia.detalleclientemedidor_set.all()
        actual = None
        for m in medidores:
            if m.fecha_desinstalacion == None or \
                            m.fecha_desinstalacion == '' or \
                            m.fecha_desinstalacion == '00/00/0000' or \
                            m.fecha_desinstalacion == '0/00/0000':
                actual = m.medidor
                break

        if actual:
            return [
                str(actual.fabrica),
                str(actual.serie),
                str(actual.marca),
                str(deta.referencia.cuenta),
                str(deta.referencia.id)
            ]
        else:
            return [
                '', '', '',
                str(deta.referencia.cuenta),
                str(deta.referencia.id)
            ]

    @rpc(Array(Array(primitive.String)),
         _returns=Array(Array(primitive.String)))
    def prueba_array(self, arr):
        print arr
        return arr

    @rpc(_returns=Array(Array(primitive.String)))
    def ubicacion(self, ):
        rel = posicion.objects.filter(
            fechaHora__gte='%s-%s-%s 00:00:00' %
            (str(datetime.datetime.today().year),
             str(datetime.datetime.today().month),
             str(datetime.datetime.today().day))).order_by(
                 '-fechaHora').distinct('fechaHora')

        ret = []

        for r in rel:
            ret.append([
                '%s %s' % (r.usuario.first_name, r.usuario.last_name),
                str((timezone.localtime(r.fechaHora).time()))[:8],
                str(r.latitud),
                str(r.longitud),
            ])
        print ret
        return ret

    @rpc(primitive.String,
         primitive.String,
         primitive.String,
         primitive.String,
         _returns=primitive.Boolean)
    def guardarUbicacion(self, idUsuario, fechahora, latitud, longitud):
        rel = posicion(fechaHora=fechahora,
                       latitud=latitud,
                       longitud=longitud,
                       usuario=User.objects.get(id=int(idUsuario)))

        if isinstance(rel.save(), posicion):
            return True
        else:
            return False

    @rpc(Array(Array(primitive.String)), _returns=Array(primitive.String))
    def guardarActividad(self, datas):

        data = datas[0]
        ts = '%d' % tipoDeSolicitud.objects.get(id=data[0][:2]).id

        try:
            cli = cliente.objects.get(id=int(data[1]))
            med = cli.detalleclientemedidor_set.all().filter(
                medidor__fabrica=str(data[9]),
                medidor__serie=str(data[32]),
                fecha_desinstalacion=None).first().medidor
        except:
            cli = None
            med = None

        try:
            idact = int(data[2])
        except:
            idact = 0

        if idact != 0:
            act = actividad.objects.get(id=int(idact))
            cli = act.cliente
            print 'Se obtuvo el id del cliente nuevo a actualizar'
            try:
                med = medidor.objects.get(actividad=act, contrato=None)
                med.lectura = str(data[3])
                print 'medidor revisado'
            except:
                pass

        t = 'N'
        if cli:
            if len(str(data[4])) == 13:
                t = 'J'
                print u'Es persona jurídica'
            else:
                t = 'N'
                print u'Es persona natural'
            cli.ci_ruc = data[4]
            cli.nombre = data[5]
            cli.tipo = t
            cli.telefono = data[6]
            print 'se generó el cliente nuevo'
        cliref = None
        medref = None
        try:
            if ts == '1':
                if not cli:
                    cli = cliente(ci_ruc=data[4],
                                  nombre=data[5],
                                  telefono=data[6])
                cliref = cliente.objects.get(id=data[7])
                #cliref.ubicacionGeografica.calle.descripcion1 = form.data['direccionRef']
                medref = cliref.detalleclientemedidor_set.all().filter(
                    medidor__fabrica=str(data[8]),
                    fecha_desinstalacion=None).first()
                print 'es s/N (1)'
            else:
                cli.tipo = t
                cli.telefono = data[6]
                #med = request.session['medidor']
                med.lectura = str(data[3])
                print 'NO es s/N'

        except:
            try:
                #en caso de ser actualizacion
                cli = cliente.objects.get(id=cli.id,
                                          cuenta=(data[10]).strip(),
                                          ci_ruc=(data[4]).strip())
                cli.nombre = data[5]
                cli.tipo = t
                cli.telefono = data[6]
                print 'cliente a actualizar'
                cli.save(force_update=True)

                if ts != '1':
                    med.save(force_update=True)

                    enlace = detalleClienteMedidor.objects.get(cliente=cli,
                                                               medidor=med)
                    print enlace

                else:
                    if med.id > 0:
                        med.delete()

                    ref = detalleClienteReferencia.objects.get(
                        cliente=cli).referencia
                    call = ref.ubicacionGeografica.calle
                    #call.descripcion1 = form.data['direccionRef']
                    call.save(force_update=True)

                    #actualizar
                id = formSave(data[11], datas, cliente=cli)
                #dajax.script("newUrl('/ingreso/" + str(id) + "');")
                if id > 0:
                    msj = 'Actividad modificada Correctamente'
                else:
                    msj = 'Error al guardar la actividad...'
                return [str(id), msj]

            except:
                #dajax = mostraError(dajax, {'Error': 'Datos invalidos para guardar...'}, '#err')
                return ['0', 'Error al actualizar la actividad...']

        #guardar por primera vez
        cli.save()

        if ts == '1':
            #cliref.save()
            #medref.instance.save()
            #fi = formatFechas(medref.fields['fi'].initial)
            #fd = formatFechas(medref.fields['fd'].initial)
            #d = detalleClienteMedidor(
            #    cliente=cliref,
            #    medidor=medref,
            #    lectura_instalacion=float(medref.fields['li'].initial),
            #    lectura_desinstalacion=float(medref.fields['ld'].initial),
            #    fecha_instalacion=fi,
            #    fecha_desinstalacion=fd,
            #)
            #d.save()
            dcr = detalleClienteReferencia(
                cliente=cli,
                referencia=cliref,
                medidorDeReferencia=str(data[8]),
                ubicacion=cliref.ubicacionGeografica)

            dcr.save()
            if med:
                med.delete()
        else:
            med.save()

            #fi = formatFechas(med.fields['fi'].initial)
            #fd = formatFechas(med.fields['fd'].initial)
            #
            #d = detalleClienteMedidor(
            #    cliente=cli,
            #    medidor=med.instance,
            #    lectura_instalacion=float(med.fields['li'].initial),
            #    lectura_desinstalacion=float(med.fields['ld'].initial),
            #    fecha_instalacion=fi,
            #    fecha_desinstalacion=fd,
            #)
            #d.save()

        print 'Correcto...'

        id = formSave(data[11], datas, cliente=cli)
        #dajax.script("newUrl('/ingreso/" + str(id) + "');")
        msj1 = ''
        if id > 0:
            msj = 'Actividad guardada Correctamente'
            print msj
            rel = posicion(fechaHora=data[40],
                           latitud=Decimal(data[41]),
                           longitud=Decimal(data[42]),
                           usuario=User.objects.get(id=int(data[39])),
                           actividad=actividad.objects.get(id=id))
            if isinstance(rel.save(), posicion):
                msj1 = 'Posicion Guardada'
                print msj1
            else:
                msj1 = 'Posicion NO Guardada'
                print msj1
        else:
            msj = 'Error al guardar la actividad...'
            print msj

        return [str(id), msj, msj1]

    @rpc(primitive.String, _returns=Array(primitive.String))
    def eliminarActividad(self, pk):

        try:
            act = actividad.objects.get(id=int(pk))
            #borrando detalles de existir
            #de medidores...
            for m in list(medidor.objects.filter(actividad__id=act.id)):
                try:
                    m.actividad = None
                    m.save(force_update=True)
                except:
                    pass

                    #de sellos
            for s in list(sello.objects.filter(utilizado__id=act.id)):
                try:
                    s.utilizado = None
                    s.ubicacion = 'N/A'
                    s.save(force_update=True)
                except:
                    pass

                    #de rubros
            for r in list(
                    detalleDeActividad.objects.filter(actividad__id=act.id)):
                try:
                    r.delete()
                except:
                    pass

                    #de materiales
            for m in list(materialDeActividad.objects.filter(actividad=act)):
                #mat = detalleMaterialContrato.objects.get(id=m.material.id)
                #mat.stock += m.cantidad
                #mat.save(force_update=True)
                m.delete()

                #deFotos
            for fot in list(foto.objects.filter(actividad=act)):
                fot.delete()

            for p in act.posicion_set.all():
                p.actividad = None
                p.save(force_update=True)

            act.delete()

            return ['0', 'Actividad Eliminada Permanentemente...']
        except Exception:
            return [
                '1', 'Error, No se pudo eliminar correctamente la actividad...'
            ]

    @rpc(primitive.String,
         primitive.String,
         primitive.String,
         _returns=primitive.String)
    def guardarFoto(self, strFoto, pk, nombreFoto):

        try:

            # saving base string from post data
            base64_string = strFoto

            #filename = str(nombreFoto)
            filename = "(tomada-%s)-(subida-%s).png" % (
                str(nombreFoto).replace(
                    ':', '_'), str(timezone.localtime(timezone.now())).replace(
                        ':', '_').replace('.', '_'))
            print filename

            # decoding base string to image and saving in to your media root folder
            #fh = open(os.path.join(settings.MEDIA_ROOT, filename), "wb")
            #fh.write(base64_string.decode('base64'))
            #fh.close()

            # saving decoded image to database
            decoded_image = base64_string.decode('base64')

            newdoc = foto()
            newdoc.actividad = actividad.objects.get(id=int(pk))
            newdoc.foto = ContentFile(decoded_image, filename)
            newdoc.save()
            print 'Foto guardada...'
            # add blur effect to saved image and saving in to media root folder
            #im = Image.open(os.path.join(settings.MEDIA_ROOT, filename))
            #im_blur = im.filter(ImageFilter.EMBOSS)
            # save blur image to media root
            #new_filename="blur_"+filename
            #im_blur.save(os.path.join(settings.MEDIA_ROOT, new_filename))

            return 'Foto %s Guardada' % str(nombreFoto)

        except:
            return 'Foto %s NO Guardada' % str(nombreFoto)
Exemple #9
0
class SW_Busquedas(DefinitionBase):
    @rpc(primitive.Integer,
         primitive.String,
         primitive.Integer,
         primitive.String,
         primitive.Boolean,
         _returns=Array(Array(primitive.String)))
    def buscarDjango(self, idUsuario, sesion, tipo, dato, esIngreso):
        client = None
        busc = vitacoraBusquedas(tipoBusq=str(tipo),
                                 consulta=dato,
                                 usuario=User.objects.get(id=idUsuario,
                                                          sesion_sico=sesion),
                                 estadoRetorno=True)
        b = buscar(sesion)
        operaciones = {
            '1': b.porCuenta,
            '2': b.porMedidor,
            '3': b.porNombre,
            '4': b.porGeocodigo
        }
        res = operaciones[str(tipo)](dato)

        coincidencias = []
        cli = []
        medidores = []

        #print res

        if res:
            busc.save()

            for c in res['cClientes']:

                if tipo == 1:
                    coincidencias.append(c.cuenta)
                    coincidencias.append(c.nombre)
                    coincidencias.append(
                        c.ubicacionGeografica.calle.descripcion1)
                    coincidencias.append(str(c.deuda))
                    coincidencias.append(str(c.meses))
                elif tipo == 2:
                    coincidencias.append(
                        c.ubicacionGeografica.urbanizacion.descripcion)
                    coincidencias.append(c.estado)
                    coincidencias.append(c.cuenta)
                    coincidencias.append(c.nombre)
                    coincidencias.append(
                        c.ubicacionGeografica.calle.descripcion1)
                elif tipo == 3:
                    coincidencias.append(c.nombre)
                    coincidencias.append(
                        c.ubicacionGeografica.calle.descripcion1)
                    coincidencias.append(c.cuenta)
                    coincidencias.append(str(c.deuda))
                    coincidencias.append(str(c.meses))
                elif tipo == 4:
                    coincidencias.append(
                        c.ubicacionGeografica.interseccion.descripcion1)
                    coincidencias.append(c.cuenta)
                    coincidencias.append(c.nombre)
                    coincidencias.append(
                        c.ubicacionGeografica.calle.descripcion1)
                    coincidencias.append(
                        c.ubicacionGeografica.urbanizacion.descripcion)
                    coincidencias.append(str(c.deuda))

            c = res['formCliente']

            cli.append(c.instance.ci_ruc)
            cli.append(c.instance.cuenta)
            cli.append(c.instance.nombre)
            cli.append(c.fields['direccion'].initial)
            cli.append(c.fields['interseccion'].initial)
            cli.append(c.fields['urbanizacion'].initial)
            cli.append(c.instance.estado)
            cli.append(c.fields['geo'].initial)
            #cli.append(c.fields['nparr'].initial)
            #cli.append(c.fields['parroquia'].initial)
            cli.append(str(c.instance.meses))
            cli.append(str(c.instance.deuda))

            client = c.instance
            if esIngreso:
                client.save()

            for c in res['cMedidores']:

                medidores.append(c.fields['marc'].initial)
                medidores.append(c.fields['tecnologia'].initial)
                medidores.append(c.fields['tension'].initial)
                medidores.append(c.fields['amperaje'].initial)
                medidores.append(c.fields['fi'].initial)
                medidores.append(c.fields['fd'].initial)
                medidores.append(c.fields['li'].initial)
                medidores.append(c.fields['ld'].initial)
                medidores.append(c.instance.fabrica)
                medidores.append(str(c.instance.serie))
                medidores.append(str(c.instance.tipo))
                medidores.append(str(c.instance.digitos))
                medidores.append(str(c.instance.fases))
                medidores.append(str(c.instance.hilos))
                med = c.instance

                if esIngreso:
                    med.save()
                    try:
                        li = Decimal((str(c.fields['li'].initial).strip()))
                    except:
                        li = Decimal('0000')

                    try:
                        ld = Decimal((str(c.fields['ld'].initial).strip()))
                    except:
                        ld = Decimal('0000')

                    try:
                        fi = datetime.datetime.strptime(
                            (str(c.fields['fi'].initial).strip()),
                            "%d/%m/%Y").date()
                    except:
                        fi = datetime.datetime.strptime(
                            '1/01/1900', "%d/%m/%Y").date()

                    try:
                        fd = datetime.datetime.strptime(
                            (str(c.fields['fd'].initial).strip()),
                            "%d/%m/%Y").date()
                    except:
                        fd = None
                    print 'guardar detalle'
                    d = detalleClienteMedidor(lectura_instalacion=li,
                                              lectura_desinstalacion=ld,
                                              fecha_instalacion=fi,
                                              fecha_desinstalacion=fd,
                                              medidor=med,
                                              cliente=client)
                    d.save()

        if esIngreso:
            return [
                coincidencias,
                cli,
                medidores,
                [str(client.id)],
            ]

        return [coincidencias, cli, medidores]

    @rpc(primitive.String,
         primitive.String,
         primitive.String,
         primitive.String,
         _returns=Array(Array(primitive.String)))
    def buscarMovil(self, idUsuario, sesion, tipo, dato):
        busc = vitacoraBusquedas(tipoBusq=str(tipo),
                                 consulta=dato,
                                 usuario=User.objects.get(id=int(idUsuario),
                                                          sesion_sico=sesion),
                                 estadoRetorno=True)
        print 'buscando por %s , %s' % (str(tipo), str(dato))
        movilBusqueda = SW_buscar(sesion)
        if movilBusqueda:
            busc.save()
            return movilBusqueda.busquedaIntegrada(tipo, dato)
        return None
Exemple #10
0
class WeatherService(DefinitionBase):
    """
       Gives the weather details of the given city in a given country
       Depends on public web service GetWeather of http://www.webservicex.net
    """
    @rpc(String, String, _returns=String)
    def weather(self, city, country):

        hello_client = Client(
            'http://www.webservicex.net/globalweather.asmx?WSDL')
        result = hello_client.service.GetWeather(city, country)

        result = result.encode("utf-16")
        tree = etree.fromstring(result)
        r = tree.xpath('/CurrentWeather')
        root = tree.xpath('/CurrentWeather/Location')
        time = tree.xpath('/CurrentWeather/Time')
        Wind = tree.xpath('/CurrentWeather/Wind')
        visibility = tree.xpath('/CurrentWeather/Visibiltiy')
        Sky = tree.xpath('/CurrentWeather/SkyConditions')
        Temp = tree.xpath('/CurrentWeather/Temperature')
        Dew = tree.xpath('CurrentWeather/DewPoint')
        Humidity = tree.xpath('/CurrentWeather/RelativeHumidity')
        pressure = tree.xpath('/CurrentWeather/Pressure')
        ls = "Location=" + root[0].text + ", Time =" + time[
            0].text + ", Temp=" + Temp[0].text + ", Humidity= " + Humidity[
                0].text

        html = "<ul>"
        for a in range(len(r)):

            html += "<li>" + "Location :" + root[
                a].text + "</li><li> Time : " + time[
                    a].text + "</li><li> Temp : " + Temp[
                        a].text + "</li><li> Humidity : " + Humidity[
                            a].text + "</li>"
            """                
               a1="<li>"+"Location=" + root[a].text + "</li><li> Time =" + time[a].text +  "</li>"
               b="<li> Temp=" +Temp[a].text + "</li><li> Humidity= " + Humidity[a].text+"</li>"
               c="<li>Sky=" + Sky[a].text + "</li><li>Visibility =" + visibility[a].text + "</li>"
               d="<li>Dew = " + Dew[a].text + "</li><li>Wind =" + Wind[a].text + "</li><li>pressure="+pressure[a].text+"</li>"
               html+=a1+b+c+d"""

        html += "</ul>"
        return html

        #return ls

    """
       Retrieves headlines from the Guardian news based on the content search
       Depends on public rest api of Guardian 
    """

    @rpc(String, _returns=Array(Topic))
    def news(self, section):

        r = requests.get(
            'http://content.guardianapis.com/search?q={}&format=xml'.format(
                section))
        #r = r.encode("utf-16")
        tree = etree.fromstring(r.content)
        root1 = tree.xpath('/response/results/content')

        global news_database
        global topicid_seq

        for i in range(len(root1)):

            topic = Topic()

            topic.tid = topicid_seq
            topicid_seq = topicid_seq + 1
            news_database[topic.tid] = topic

            attributes = root1[i].attrib

            topic.sectionid = attributes.get("web-url")
            topic.webtitle = attributes.get("web-title")

        return [v for k, v in news_database.items()]

    """
       This service retrieves lastest 15 statuses of the user
       Depends on public rest api of Twitter Inc
    """

    @rpc(String, _returns=String)
    def tweetSearch(self, name):

        # Making rest call to the twitter rest api using requests
        r = requests.get(
            'https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&screen_name={}&count=15'
            .format(name))

        # parsing xml string from the response using lxml
        tree = etree.fromstring(r.content)
        root = tree.xpath('/statuses/status')
        seq = 1
        d = {}

        for i in range(len(root)):
            s = tree.xpath('/statuses/status/text')
            d[i] = s[i].text

        html = "<ul>"
        for a in d.keys():
            html += "<li>" + d[a] + "</li>"
        html += "</ul>"
        return html

    """
       Checks the user authentication by making the user provided data with the entries in database
       Uses WS-Security headers to get the user provided credentials
    """

    @rpc(_returns=String, _in_header=WSSecurityHeader)
    def userAuth(self):
        print "Username:"******"user.db")
        cur = conn.cursor()

        cur.execute("select * from  user where name = '{}'".format(
            user))  #checking user credentials with entries in database
        for row in cur.fetchall():
            if password == row[1]:
                return "ok"
        return "fail"

    """
       Makes an xmlrpc call to the get_events of the server running on port no 8000 to get the list of all events
    """

    @rpc(_returns=String)
    def getEvents(self):
        client = xmlrpclib.ServerProxy(
            "http://localhost:8000/")  #making an xmlrpc using xmlrpclib
        result = client.get_events()

        header = "<h1> Available Events </h1>"
        return "<html><body>" + header + str(result) + "</body></html>"
Exemple #11
0
class SoapListar(SimpleWSGISoapApp):
    """Class for webservice """
    @soapmethod(_returns=Array(String))
    def listarCantones(self):
        """ Method for webservice"""
        return ListarCantones()
Exemple #12
0
class FindProbesOutput(ClassSerializer):
    __namespace__ = "findprobesoutput"
    oligos = Array(ProbeOligo)
    alignment = Alignment
Exemple #13
0
class NestedObject(ClassSerializer):
    date_time = DateTime
    ro = ReturnObject
    arr = Array(String)