Example #1
0
    def create(self):
        data = get_object_as_dict(self)
        distribuidor = None
        cnpj = data.get('StrCnpj')
        guias = data.pop('guias', [])
        data.pop('IntSeqenv', None)
        data.pop('IntTotVol', None)

        try:
            distribuidor = Terceirizada.objects.get(cnpj=cnpj,
                                                    eh_distribuidor=True)
            data['distribuidor'] = distribuidor
        except exceptions.ObjectDoesNotExist:
            raise exceptions.ObjectDoesNotExist(
                'Não existe distribuidor cadastrado com esse cnpj')

        try:
            solicitacao = SolicitacaoRemessa.objects.create_solicitacao(**data)

        except IntegrityError as e:
            if 'unique constraint' in str(e):
                error = str(e)
                msg = error.split('Key')
                raise IntegrityError('Solicitação duplicada:' + msg[1])
            raise IntegrityError('Erro ao salvar Solicitação.')

        Guia().create_many(guias, solicitacao)

        return solicitacao
Example #2
0
    def test_the(self):
        class C(ComplexModel):
            __namespace__ = "tns"
            i = Integer
            s = Unicode
            a = Array(DateTime)

            def __eq__(self, other):
                print("Yaaay!")
                return  self.i == other.i and \
                        self.s == other.s and \
                        self.a == other.a

        c = C(i=5, s="x", a=[datetime(2011, 12, 22, tzinfo=pytz.utc)])

        for iw, ca in ((False, dict), (True, dict), (False, list), (True,
                                                                    list)):
            print()
            print('complex_as:', ca)
            d = get_object_as_dict(c, C, complex_as=ca)
            print(d)
            o = get_dict_as_object(d, C, complex_as=ca)
            print(o)
            print(c)
            assert o == c
Example #3
0
    def test_self_referential_array_workaround(self):
        from spyne.util.dictdoc import get_object_as_dict

        class Category(ComplexModel):
            id = Integer(min_occurs=1, max_occurs=1, nillable=False)

        Category._type_info['children'] = Array(Category)

        parent = Category()
        parent.children = [Category(id=0), Category(id=1)]

        d = get_object_as_dict(parent, Category)
        pprint(d)
        assert d['children'][0]['id'] == 0
        assert d['children'][1]['id'] == 1

        class SoapService(ServiceBase):
            @rpc(_returns=Category)
            def view_categories(ctx):
                pass

        Application([SoapService],
                    'service.soap',
                    in_protocol=ProtocolBase(),
                    out_protocol=ProtocolBase())
Example #4
0
    def cancel(self, user):
        cancelamento_dict = get_object_as_dict(self)
        num_solicitacao = cancelamento_dict.get('StrNumSol')
        guias = cancelamento_dict.get('guias')

        if isinstance(guias, list):
            guias_payload = [x['StrNumGui'] for x in guias]
        else:
            guias_payload = [x['StrNumGui'] for x in guias.values()]

        try:
            solicitacao = SolicitacaoRemessa.objects.get(
                numero_solicitacao=num_solicitacao)

        except exceptions.ObjectDoesNotExist:
            raise exceptions.ObjectDoesNotExist('Solicitacão não encontrada.')

        solicitacao.guias.filter(numero_guia__in=guias_payload).update(
            status=SolicitacaoRemessaWorkFlow.PAPA_CANCELA)

        guias_existentes = list(
            solicitacao.guias.values_list('numero_guia', flat=True))
        existe_guia_nao_cancelada = solicitacao.guias.exclude(
            status=GuiaModel.STATUS_CANCELADA).exists()

        if set(guias_existentes) == set(
                guias_payload) or not existe_guia_nao_cancelada:
            solicitacao.cancela_solicitacao(user=user)
        else:
            solicitacao.salvar_log_transicao(
                status_evento=LogSolicitacoesUsuario.PAPA_CANCELA_SOLICITACAO,
                usuario=user,
                justificativa=f'Guias canceladas: {guias_payload}')
Example #5
0
 def update_unit(ctx, unit):
     """Update an existing unit added to the custom unit collection. Please
     not that units built in to the library can not be updated.
     """
     unitdict = get_object_as_dict(unit, Unit)
     result = units.update_unit(unitdict, **ctx.in_header.__dict__)
     return result
Example #6
0
    def add_unit(ctx, unit):
        """Add a physical unit to the servers list of units. The Hydra server
        provides a complex model ``Unit`` which should be used to add a unit.

        A minimal example:

        .. code-block:: python

            from HydraLib import PluginLib

            cli = PluginLib.connect()

            new_unit = cli.factory.create('hyd:Unit')
            new_unit.name = 'Teaspoons per second'
            new_unit.abbr = 'tsp s^-1'
            new_unit.cf = 0               # Constant conversion factor
            new_unit.lf = 1.47867648e-05  # Linear conversion factor
            new_unit.dimension = 'Volumetric flow rate'
            new_unit.info = 'A flow of one teaspoon per second.'

            cli.service.add_unit(new_unit)
        """
        # Convert the complex model into a dict
        unitdict = get_object_as_dict(unit, Unit)
        units.add_unit(unitdict, **ctx.in_header.__dict__)
        return True
Example #7
0
        def test_file_value(self):
            dbe = _DictDocumentChild.default_binary_encoding
            beh = binary_encoding_handlers[dbe]

            # Prepare data
            v = File.Value(
                name='some_file.bin',
                type='application/octet-stream',
            )
            file_data = bytes(bytearray(range(0xff)))
            v.data = (file_data, )
            beh([file_data])
            if _DictDocumentChild.text_based:
                test_data = beh(v.data).decode('latin1')
            else:
                test_data = beh(v.data)

            print(repr(v.data))

            class SomeService(Service):
                @srpc(File, _returns=File)
                def some_call(p):
                    print(p)
                    print(type(p))
                    assert isinstance(p, File.Value)
                    assert p.data == (file_data, )
                    assert p.type == v.type
                    assert p.name == v.name
                    return p

            d = get_object_as_dict(v,
                                   File,
                                   protocol=_DictDocumentChild,
                                   ignore_wrappers=False)
            ctx = _dry_me([SomeService], {"some_call": {'p': d}})
            s = b''.join(ctx.out_string)
            d = self.dumps({
                "some_callResponse": {
                    "some_callResult": {
                        'name': v.name,
                        'type': v.type,
                        'data': test_data,
                    }
                }
            })

            print(self.loads(s))
            print(self.loads(d))
            print(v)
            assert self.loads(s) == self.loads(d)
Example #8
0
        def test_file_value(self):
            dbe = _DictDocumentChild.default_binary_encoding
            beh = binary_encoding_handlers[dbe]

            # Prepare data
            v = File.Value(
                name='some_file.bin',
                type='application/octet-stream',
            )
            file_data = ''.join([chr(x) for x in range(0xff)])
            v.data = beh(file_data)

            class SomeService(ServiceBase):
                @srpc(File, _returns=File)
                def some_call(p):
                    print(p)
                    print(type(p))
                    assert isinstance(p, File.Value)
                    assert p.data == [file_data]
                    assert p.type == v.type
                    assert p.name == v.name
                    return p

            d = get_object_as_dict(v, File, ignore_wrappers=False)
            assert d[File.get_type_name()]['name'] == v.name
            assert d[File.get_type_name()]['type'] == v.type
            assert d[File.get_type_name()]['data'] == v.data

            ctx = _dry_me([SomeService], {"some_call": {'p': d}})
            s = ''.join(ctx.out_string)
            d = serializer.dumps(
                {
                    "some_callResponse": {
                        "some_callResult": {
                            'name': v.name,
                            'type': v.type,
                            'data': v.data,
                        }
                    }
                }, **dumps_kwargs)

            print(serializer.loads(s))
            print(serializer.loads(d))
            print(v)
            assert serializer.loads(s) == serializer.loads(d)
Example #9
0
        def test_file_value(self):
            dbe = _DictDocumentChild.default_binary_encoding
            beh = binary_encoding_handlers[dbe]

            # Prepare data
            v = File.Value(
                name='some_file.bin',
                type='application/octet-stream',
            )
            file_data = bytes(bytearray(range(0xff)))
            v.data = (file_data,)
            beh([file_data])
            if _DictDocumentChild.text_based:
                test_data = beh(v.data).decode('latin1')
            else:
                test_data = beh(v.data)

            print(repr(v.data))

            class SomeService(ServiceBase):
                @srpc(File, _returns=File)
                def some_call(p):
                    print(p)
                    print(type(p))
                    assert isinstance(p, File.Value)
                    assert p.data == (file_data,)
                    assert p.type == v.type
                    assert p.name == v.name
                    return p

            d = get_object_as_dict(v, File, protocol=_DictDocumentChild,
                                                          ignore_wrappers=False)
            ctx = _dry_me([SomeService], {"some_call": {'p': d}})
            s = b''.join(ctx.out_string)
            d = self.dumps({"some_callResponse": {"some_callResult": {
                'name': v.name,
                'type': v.type,
                'data': test_data,
            }}})

            print(self.loads(s))
            print(self.loads(d))
            print(v)
            assert self.loads(s) == self.loads(d)
Example #10
0
        def test_file_value(self):
            dbe = _DictDocumentChild.default_binary_encoding
            beh = binary_encoding_handlers[dbe]

            # Prepare data
            v = File.Value(
                name='some_file.bin',
                type='application/octet-stream',
            )
            file_data = ''.join([chr(x) for x in range(0xff)])
            v.data = beh(file_data)

            class SomeService(ServiceBase):
                @srpc(File, _returns=File)
                def some_call(p):
                    print(p)
                    print(type(p))
                    assert isinstance(p, File.Value)
                    assert p.data == [file_data]
                    assert p.type == v.type
                    assert p.name == v.name
                    return p

            d = get_object_as_dict(v, File)
            assert d['name'] == v.name
            assert d['type'] == v.type
            assert d['data'] == v.data

            ctx = _dry_me([SomeService], {"some_call": {'p': d}})
            s = ''.join(ctx.out_string)
            d = serializer.dumps({"some_callResponse": {"some_callResult": {
                'name': v.name,
                'type': v.type,
                'data': v.data,
            }}}, **dumps_kwargs)

            print(serializer.loads(s))
            print(serializer.loads(d))
            print(v)
            assert serializer.loads(s) == serializer.loads(d)
Example #11
0
    def test_self_referential_array_workaround(self):
        from spyne.util.dictdoc import get_object_as_dict

        class Category(ComplexModel):
            id = Integer(min_occurs=1, max_occurs=1, nillable=False)

        Category._type_info["children"] = Array(Category)

        parent = Category()
        parent.children = [Category(id=0), Category(id=1)]

        d = get_object_as_dict(parent, Category)
        pprint(d)
        assert d["children"][0]["id"] == 0
        assert d["children"][1]["id"] == 1

        class SoapService(ServiceBase):
            @rpc(_returns=Category)
            def view_categories(ctx):
                pass

        Application([SoapService], "service.soap", in_protocol=ProtocolBase(), out_protocol=ProtocolBase())
Example #12
0
    def test_the(self):
        class C(ComplexModel):
            __namespace__ = "tns"
            i = Integer
            s = Unicode
            a = Array(DateTime)

            def __eq__(self, other):
                print "Yaaay!"
                return self.i == other.i and self.s == other.s and self.a == other.a

        c = C(i=5, s="x", a=[datetime(2011, 12, 22)])

        for iw, ca in ((False, dict), (True, dict), (False, list), (True, list)):
            print
            print "complex_as:", ca
            d = get_object_as_dict(c, C, complex_as=ca)
            print d
            o = get_dict_as_object(d, C, complex_as=ca)
            print o
            print c
            assert o == c
Example #13
0
    def test_the(self):
        class C(ComplexModel):
            __namespace__ = "tns"
            i = Integer
            s = Unicode
            a = Array(DateTime)

            def __eq__(self, other):
                print("Yaaay!")
                return  self.i == other.i and \
                        self.s == other.s and \
                        self.a == other.a

        c = C(i=5, s="x", a=[datetime(2011,12,22, tzinfo=pytz.utc)])

        for iw, ca in ((False,dict), (True,dict), (False,list), (True, list)):
            print()
            print('complex_as:', ca)
            d = get_object_as_dict(c, C, complex_as=ca)
            print(d)
            o = get_dict_as_object(d, C, complex_as=ca)
            print(o)
            print(c)
            assert o == c
Example #14
0
from spyne.model.primitive import Boolean
from spyne.model.primitive import String
from spyne.model.complex import ComplexModel

from spyne.util.dictdoc import get_object_as_dict

class SomeMapping(ComplexModel):
    compact = Boolean
    solid = Boolean
    object_name = String
    attached = Boolean
    is_published = Boolean
    is_owner = Boolean
    can_delete = Boolean
    can_insert= Boolean
    can_update = Boolean

print list(get_object_as_dict(SomeMapping(
    compact=True,
    solid=True,
    object_name="Cat",
    attached=False,
    is_published=True,
    is_owner=False,
    can_delete=False,
    can_insert= True,
    can_update=True
), SomeMapping, ignore_wrappers=True, complex_as=list))

Example #15
0
 def delete_unit(ctx, unit):
     """Delete a unit from the custom unit collection.
     """
     unitdict = get_object_as_dict(unit, Unit)
     result = units.delete_unit(unitdict, **ctx.in_header.__dict__)
     return result
Example #16
0
    def cancel(self, user):
        cancelamento_dict = get_object_as_dict(self)
        num_solicitacao = cancelamento_dict.get('StrNumSol')
        seq_envio = cancelamento_dict.get('IntSeqenv')
        guias = cancelamento_dict.get('guias')

        if isinstance(guias, list):
            guias_payload = [x['StrNumGui'] for x in guias]
        else:
            guias_payload = [x['StrNumGui'] for x in guias.values()]
        try:
            solicitacao = SolicitacaoRemessa.objects.get(
                numero_solicitacao=num_solicitacao)

        except exceptions.ObjectDoesNotExist:
            raise exceptions.ObjectDoesNotExist(
                f'Solicitacão {num_solicitacao} não encontrada.')

        guias_existentes = list(
            solicitacao.guias.values_list('numero_guia', flat=True))
        # Não depende de confirmação do distribuidor no sigpae
        if solicitacao.status in (StatusReq.AGUARDANDO_ENVIO,
                                  StatusReq.DILOG_ENVIA,
                                  StatusReq.DILOG_ACEITA_ALTERACAO):
            solicitacao.guias.filter(numero_guia__in=guias_payload).update(
                status=GuiaStatus.CANCELADA)
            existe_guia_nao_cancelada = solicitacao.guias.exclude(
                status=GuiaStatus.CANCELADA).exists()

            if set(guias_existentes) == set(
                    guias_payload) or not existe_guia_nao_cancelada:
                solicitacao.cancela_solicitacao(user=user)
            else:
                solicitacao.salvar_log_transicao(
                    status_evento=LogSolicitacoesUsuario.
                    PAPA_CANCELA_SOLICITACAO,
                    usuario=user,
                    justificativa=f'Guias canceladas: {guias_payload}')
            # Envia confirmação para o papa
            if not settings.DEBUG:
                EOLPapaService.confirmacao_de_cancelamento(
                    cnpj=solicitacao.cnpj,
                    numero_solicitacao=solicitacao.numero_solicitacao,
                    sequencia_envio=seq_envio)

        # Depende de confirmação do distribuidor no sigpae
        elif solicitacao.status in (StatusReq.DISTRIBUIDOR_CONFIRMA,
                                    StatusReq.DISTRIBUIDOR_SOLICITA_ALTERACAO):
            solicitacao.guias.filter(numero_guia__in=guias_payload).update(
                status=GuiaStatus.AGUARDANDO_CANCELAMENTO)
            existe_guia_aguardando_cancelamento = solicitacao.guias.exclude(
                status=GuiaStatus.AGUARDANDO_CANCELAMENTO).exists()

            if set(guias_existentes) == set(
                    guias_payload) or not existe_guia_aguardando_cancelamento:
                solicitacao.aguarda_confirmacao_de_cancelamento(user=user)
            else:
                solicitacao.salvar_log_transicao(
                    status_evento=LogSolicitacoesUsuario.
                    PAPA_AGUARDA_CONFIRMACAO_CANCELAMENTO_SOLICITACAO,
                    usuario=user,
                    justificativa=f'Guias canceladas: {guias_payload}')
    bc.database_os = "Linux"
    bc.versus = "wsgi"
    bc.plaintext_url = "/plaintext"
    return bc


config = BenchmarkConfig(framework='spyne', tests=[])

keys = iter(['default', 'raw', 'py3orm', 'py3raw'])

for flav in ['CPython', 'Python3']:
    bc = add_common(gen_normal_test())
    bc.flavor = flav
    bc.key = next(keys)
    config.tests.append(bc)

    bc = add_common(gen_raw_test())
    bc.flavor = flav
    bc.key = next(keys)
    config.tests.append(bc)

data = get_object_as_dict(config, complex_as=dict)
data['tests'] = [{d['key']: d} for d in data['tests']]

data = json.dumps(data, indent=2, sort_keys=True, separators=(',', ': '))

open('benchmark_config.json', 'wb').write(data)


print(data)
Example #18
0
 def process(value):
     if value is not None:
         return json.dumps(get_object_as_dict(value, self.cls,
                                             skip_depth=self.skip_depth))
Example #19
0
class SomeMapping(ComplexModel):
    compact = Boolean
    solid = Boolean
    object_name = String
    attached = Boolean
    is_published = Boolean
    is_owner = Boolean
    can_delete = Boolean
    can_insert = Boolean
    can_update = Boolean


# You'll get a nice compact array. Experiment with different skip_depth
# vaules to understand its meaning.
print get_object_as_dict(
    SomeMapping(
        compact=True,
        solid=True,
        object_name="Cat",
        attached=False,
        is_published=True,
        is_owner=False,
        can_delete=False,
        can_insert=True,
        can_update=True,
    ),
    SomeMapping,
    skip_depth=4,
)
Example #20
0
    bc.database_os = "Linux"
    bc.versus = "wsgi"
    bc.plaintext_url = "/plaintext"
    return bc


config = BenchmarkConfig(framework="spyne", tests=[])

keys = iter(["default", "raw", "py3orm", "py3raw"])

for flav in ["CPython", "Python3"]:
    bc = add_common(gen_normal_test())
    bc.flavor = flav
    bc.key = next(keys)
    config.tests.append(bc)

    bc = add_common(gen_raw_test())
    bc.flavor = flav
    bc.key = next(keys)
    config.tests.append(bc)

data = get_object_as_dict(config, complex_as=dict)
data["tests"] = [{d["key"]: d} for d in data["tests"]]

data = json.dumps(data, indent=2, sort_keys=True, separators=(",", ": "))

open("benchmark_config.json", "wb").write(data)


print(data)
Example #21
0
from spyne.model.complex import ComplexModel

from spyne.util.dictdoc import get_object_as_dict


class SomeMapping(ComplexModel):
    compact = Boolean
    solid = Boolean
    object_name = String
    attached = Boolean
    is_published = Boolean
    is_owner = Boolean
    can_delete = Boolean
    can_insert = Boolean
    can_update = Boolean


print list(
    get_object_as_dict(SomeMapping(compact=True,
                                   solid=True,
                                   object_name="Cat",
                                   attached=False,
                                   is_published=True,
                                   is_owner=False,
                                   can_delete=False,
                                   can_insert=True,
                                   can_update=True),
                       SomeMapping,
                       ignore_wrappers=True,
                       complex_as=list))