Пример #1
0
 def __init__(self, login, password):
     self._login = login
     self._password = password
     self._settings = Settings(strict=False)
     self._client = zeep.Client(self.WSDL_URL, settings=self._settings)
Пример #2
0
import zeep

client = zeep.Client('http://localhost:1771/QueryDataService.asmx?wsdl')
print(client.service.IsRuning())

rfc_emisor   = "EKU9003173C9"
rfc_receptor = "EKU9003173C9"
uuid = "66C2B0C5-B67C-4EF8-8D2E-E6625361B059"
total = "7261.60"

file_cer_pem = open("./Certificados/EKU9003173C9.cer.pem", "r").read()
file_key_pem = open("./Certificados/EKU9003173C9.key.pem", "r").read()

# A(Aceptar la solicitud), R(Rechazar la solicitud)
respuesta_solicitud = 'A'

respuestas = {
"folios_respuestas": {
	"uuid" : uuid, 
	"rfc_emisor" : rfc_emisor, 
	"total" : total,
	"respuesta" : respuesta_solicitud
	} 
}


# Crear un cliente para hacer la petición al WS.
cliente = zeep.Client(wsdl = wsdl_url)

try:
  # Llamar el metodo procesar_respuesta
  respuesta = cliente.service.procesar_respuesta(usuario, contrasena, rfc_receptor, respuestas, file_cer_pem, file_key_pem)
  print(respuesta)
except Exception as exception:
  # Imprimir los datos de la excepcion
  print("Message: %s" % exception)
Пример #4
0
    def _l10n_es_edi_call_web_service_sign(self, invoices, info_list):
        company = invoices.company_id

        # All are sharing the same value, see '_get_batch_key'.
        csv_number = invoices.mapped('l10n_es_edi_csv')[0]

        # Set registration date
        invoices.filtered(lambda inv: not inv.l10n_es_registration_date).write({
            'l10n_es_registration_date': fields.Date.context_today(self),
        })

        # === Call the web service ===

        # Get connection data.
        l10n_es_edi_tax_agency = company.mapped('l10n_es_edi_tax_agency')[0]
        connection_vals = getattr(self, f'_l10n_es_edi_web_service_{l10n_es_edi_tax_agency}_vals')(invoices)

        header = {
            'IDVersionSii': '1.1',
            'Titular': {
                'NombreRazon': company.name[:120],
                'NIF': company.vat[2:],
            },
            'TipoComunicacion': 'A1' if csv_number else 'A0',
        }

        session = requests.Session()
        session.cert = company.l10n_es_edi_certificate_id
        session.mount('https://', PatchedHTTPAdapter())

        transport = Transport(operation_timeout=60, timeout=60, session=session)
        client = zeep.Client(connection_vals['url'], transport=transport)

        if invoices[0].is_sale_document():
            service_name = 'SuministroFactEmitidas'
        else:
            service_name = 'SuministroFactRecibidas'
        if company.l10n_es_edi_test_env and not connection_vals.get('test_url'):
            service_name += 'Pruebas'

        # Establish the connection.
        serv = client.bind('siiService', service_name)
        if company.l10n_es_edi_test_env and connection_vals.get('test_url'):
            serv._binding_options['address'] = connection_vals['test_url']

        error_msg = None
        try:
            if invoices[0].is_sale_document():
                res = serv.SuministroLRFacturasEmitidas(header, info_list)
            else:
                res = serv.SuministroLRFacturasRecibidas(header, info_list)
        except requests.exceptions.SSLError as error:
            error_msg = _("The SSL certificate could not be validated.")
        except zeep.exceptions.Error as error:
            error_msg = _("Networking error:\n%s", error)
        except Exception as error:
            error_msg = str(error)

        if error_msg:
            return {inv: {
                'error': error_msg,
                'blocking_level': 'warning',
            } for inv in invoices}

        # Process response.

        if not res or not res.RespuestaLinea:
            return {inv: {
                'error': _("The web service is not responding"),
                'blocking_level': 'warning',
            } for inv in invoices}

        resp_state = res["EstadoEnvio"]
        l10n_es_edi_csv = res['CSV']

        if resp_state == 'Correcto':
            invoices.write({'l10n_es_edi_csv': l10n_es_edi_csv})
            return {inv: {'success': True} for inv in invoices}

        results = {}
        for respl in res.RespuestaLinea:
            invoice_number = respl.IDFactura.NumSerieFacturaEmisor

            # Retrieve the corresponding invoice.
            # Note: ref can be the same for different partners but there is no enough information on the response
            # to match the partner.

            # Note: Invoices are batched per move_type.
            if invoices[0].is_sale_document():
                inv = invoices.filtered(lambda x: x.name[:60] == invoice_number)
            else:
                # 'ref' can be the same for different partners.
                candidates = invoices.filtered(lambda x: x.ref[:60] == invoice_number)
                if len(candidates) >= 1:
                    respl_partner_info = respl.IDFactura.IDEmisorFactura
                    inv = None
                    for candidate in candidates:
                        partner_info = self._l10n_es_edi_get_partner_info(candidate.commercial_partner_id)
                        if partner_info.get('NIF') and partner_info['NIF'] == respl_partner_info.NIF:
                            inv = candidate
                            break
                        if partner_info.get('IDOtro') and all(getattr(respl_partner_info.IDOtro, k) == v
                                                              for k, v in partner_info['IDOtro'].items()):
                            inv = candidate
                            break

                    if not inv:
                        # This case shouldn't happen and means there is something wrong in this code. However, we can't
                        # raise anything since the document has already been approved by the government. The result
                        # will only be a badly logged message into the chatter so, not a big deal.
                        inv = candidates[0]
                else:
                    inv = candidates

            resp_line_state = respl.EstadoRegistro
            if resp_line_state in ('Correcto', 'AceptadoConErrores'):
                inv.l10n_es_edi_csv = l10n_es_edi_csv
                results[inv] = {'success': True}
                if resp_line_state == 'AceptadoConErrores':
                    inv.message_post(body=_("This was accepted with errors: ") + html_escape(respl.DescripcionErrorRegistro))
            elif respl.RegistroDuplicado:
                results[inv] = {'success': True}
                inv.message_post(body=_("We saw that this invoice was sent correctly before, but we did not treat "
                                        "the response.  Make sure it is not because of a wrong configuration."))
            else:
                results[inv] = {
                    'error': _("[%s] %s", respl.CodigoErrorRegistro, respl.DescripcionErrorRegistro),
                    'blocking_level': 'error',
                }

        return results
Пример #5
0
import zeep
import zeep.wsse.username

WSDLFILE = 'https://uslugaterytws1test.stat.gov.pl/wsdl/terytws1.wsdl'
USERNAME = '******'
PASSWORD = '******'

client = zeep.Client(WSDLFILE,
                     wsse=zeep.wsse.username.UsernameToken(USERNAME, PASSWORD))

if not client.service.CzyZalogowany():
    raise RuntimeError('CzyZalogowany() == False')
Пример #6
0
def generic_search(mytoken, type, parameter):
    authTk = AccessToken.objects.filter(token=mytoken, active=True)
    res_msg = ""
    output = ""
    fuilfield = False
    message = 'success'
    if not authTk:
        return ({
            "data":
            None,
            "message":
            "Authentication failed! Either invalid or inactive token or cant reach the service. contact admin"
        })
    if type not in authTk[0].access_type:
        return ({
            "data":
            None,
            "message":
            "Authorization failed! you have no right to call that service. contact admin"
        })
    try:
        print("nnnnnnn")
        print(type not in authTk[0].access_type)
        # print(check_unit())

        auth = auth_api()
        if auth[0] != 'success':
            # print(auth)
            return {"data": None, 'message': auth[1]}

        # unit check

        if is_unit_available(authTk[0], type) == False:
            return {
                "data": None,
                'message': "unitError",
                'detail': "No unit available to service this request type"
            }

        i = 0
        client = zeep.Client(wsdl=auth[2])
        ix = None
        print(".............")
        print(auth[1])
        print(parameter)
        if type == 'nin':
            ix = client.service.searchByNIN(auth[1], parameter)
        elif type == "phone":
            ix = client.service.searchByDemoPhone(auth[1], parameter)
        elif type == "doc":
            ix = client.service.searchByDocumentNumber(auth[1], parameter)
        elif type == "demo":
            # {dateOfBirth:"",firstname:"",lastname:"",gender:""}
            ix = client.service.searchByDemo(auth[1], parameter)
        elif type == "finger":
            # {dateOfBirth:"",firstname:"",lastname:"",gender:""}

            ix = client.service.searchByFinger(auth[1], parameter['data'],
                                               parameter['pos'])
        elif type == "fingerV":
            ix = client.service.verifyFingerWithData(auth[1], parameter['nin'],
                                                     parameter['data'],
                                                     parameter['pos'])
        elif type == "photoV":
            ix = client.service.verifyPhotoWithData(auth[1], parameter)
        # print(ix.data)
        demo = Demo()
        list = []
        c = 0
        for d in ix.data:
            if c == 0:
                output = d.centralID
            else:
                output = output + "," + d.centralID

            list.append(demo.getDemo(d))

        if (len(list) < 1):
            return {
                'data': None,
                'message': 'success',
                'detail': 'No matching record found'
            }

        frozen = jsonpickle.encode(list[0])
        # print(list)

        fuilfield = True

        return {'data': list, 'message': 'success'}
        # serialized_obj
    except Exception as e:
        print("err " + str(e))
        traceback.print_exc()

        message = str(e)
        fuilfield = False
        # return str(e)
        output = "None"
        return {"data": None, "message": str(e)}
    finally:
        if type == 'finger' or type == 'fingerV' or type == 'photoV':
            parameter = "biometrics"
        log(authTk[0].user.email, type, parameter, output, fuilfield, message)

    return {"data": None, "message": "verification error"}
Пример #7
0
def call_soap2():
    wsdl = 'http://www.soapclient.com/xml/soapresponder.wsdl'
    client = zeep.Client(wsdl=wsdl)
    print("how are you")
    return "Thanks you"
Пример #8
0
#!/usr/bin/env python3

import zeep
import json
from datetime import datetime
import pathlib

#--- WSDL Parameters ---#
#my_json = { "&seznam_vsech_bounced_emailu": ["*****@*****.**", "*****@*****.**", "*****@*****.**"] }
# for test
wsdl_test = 'http://192.168.221.145/EmailySluzba/Emaily.svc?wsdl'
client_test = zeep.Client(wsdl=wsdl_test)
# for EU
wsdl_eu = 'http://192.168.221.124/EmailySluzba/Emaily.svc?wsdl'
client_eu = zeep.Client(wsdl=wsdl_eu)
# for LATAM
wsdl_latam = 'http://192.168.221.126/EmailySluzba/Emaily.svc?wsdl'
client_latam = zeep.Client(wsdl=wsdl_latam)

sender_list = [
    '*****@*****.**', '*****@*****.**', '*****@*****.**',
    '*****@*****.**', '*****@*****.**',
    '*****@*****.**', '*****@*****.**',
    '*****@*****.**', '*****@*****.**',
    '*****@*****.**', '*****@*****.**',
    '*****@*****.**', '*****@*****.**', '*****@*****.**',
    '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'
]
bounced_treshold = 4
current_time = datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S.%f')[:-7]
backup_dir = '/etc/rc-local/skripty/python/mail_stat/backup/'
Пример #9
0
 def post(self, *args, **kwargs):
     client = zeep.Client(*args)
     return client.service.trataPeticion(kwargs.get('data', {}))
Пример #10
0
from __future__ import print_function
import zeep

client = zeep.Client(wsdl='http://www.webservicex.net/barcode.asmx?WSDL')
response = client.service.Code39('1234', 20, ShowCodeString=True, Title='ZEEP')
print(repr(response))
Пример #11
0
# Exploring the Training.gov.au Web Services
# Author: Marcus Wynwood (@MarcusTeachUs)
#
# Finds all the units in a qual

import zeep
from zeep.wsse.username import UsernameToken
import urllib
import xmltodict

wsdl = 'https://ws.sandbox.training.gov.au/Deewr.Tga.Webservices/TrainingComponentServiceV7.svc?wsdl'
username = "******"
password = "******"
client = zeep.Client(wsdl=wsdl, wsse=UsernameToken(username, password))
base_url_for_xml_files = 'http://training.gov.au/TrainingComponentFiles/'



#########################################
# xml_url_to_dict(xml_url)
# Give this bad boy a URL to an XML file, and it'll
# give you a dictionary populated form that XML file.
# xmltodict doesn't seem to make it that nice...
def xml_url_to_dict(xml_url):
    file = urllib.request.urlopen(xml_url)
    data = file.read()
    file.close()
    data = xmltodict.parse(data)
    return data

Пример #12
0
 def __init__(self, username, password):
     self.username = username
     self.password = password
     self.client = zeep.Client(self.WSDL)
     self.session = None
     self._login()
Пример #13
0
def signXML(self, id):

    if id:
        retry = self.request.retries
        try:
            request = Request.objects.using('req').get(id=id)
        except Request.DoesNotExist as exc:
            log.error('Error in get request from database id- %s' % (id))
            return False
        file_name = request.notsignfilename
        full_file_name = os.path.join(out_xml_dir, file_name)
        log.info('Read and sign XML file - %s ' % full_file_name)

        # filename = "C:\\Python34\\ergul\\logs\out_XML\\a608bb0c-994b-4df3-9abf-0a515631b485.xml"
        try:
            obj_xml = open(full_file_name, 'rb').read()
        except IOError as exc:
            log.error('Error read XML file %s ' % full_file_name)
            if retry < MAX_RETRIES:
                raise self.retry(exc=exc)
            else:
                request.code = '97'
                request.save(using='req')
                return False

        try:
            client_for_sign = zeep.Client(url)
            resp = client_for_sign.service.SignXml(xmlData=obj_xml, wsuId=wsuId)
            log.info('Sign created XML file %s' % full_file_name)
        except RequestException as exc:
            log.error('Error sign XML file %s' % full_file_name)
            if retry < MAX_RETRIES:
                raise self.retry(exc=exc, countdown=countdowns[retry])
            else:
                request.code = '97'
                request.save(using='req')
                return False
        sign_xml = resp['SignedXml']

        #(patch, name) = os.path.split(str(file_name))
        sign_file_name = "sig-" + file_name
        sign_full_file_name = os.path.join(out_xml_dir, sign_file_name)
        #print(sign_XMLfile_name)
        #log.error('created name for sign XML file %s' % sign_XMLfile_name)
        try:
            with open(sign_full_file_name, "wb") as xml_writer:
                xml_writer.write(sign_xml)
                xml_writer.close()
                log.info('Save signed XML file %s' % sign_full_file_name)
        except IOError as exc:
            log.error('Error save signed XML file %s ' % sign_full_file_name)
            if retry < MAX_RETRIES:
                raise self.retry(exc=exc)
            else:
                request.code = '97'
                request.save(using='req')
                return False
        request.reqfilename = sign_file_name
        request.save(using='req')
        return id
    else:
        log.error('Not id in signXML params ')
        return False
Пример #14
0
#!/usr/bin/env python3

import zeep
import re
import os

TOKEN = os.environ["NRE_TOKEN"]
WSDL = 'https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2017-10-01'

client = zeep.Client(wsdl=WSDL)
data = client.service.GetDepBoardWithDetails(
    numRows=50, crs="CBG", _soapheaders={"AccessToken": TOKEN}, timeOffset=30)

#print(data)

#print("Train departures for {0} (updated {1})".format(
#    data["locationName"],
#    data["generatedAt"].strftime("%H:%M")))
#print()

#if data["nrccMessages"]:
#    for message in data["nrccMessages"]["message"]:
#        for key in message:
#            text = message[key]
#            text = re.sub(r'<A.*?>(.*?)</A>',r'\1',text)
#            text = re.sub(r'<P>','\n',text)
#            print(text)
#    print()

for service in data["trainServices"]["service"]:
Пример #15
0
import zeep
wsdl = 'http://mykris.sqlview.com:8080/KRIS/services/krislitews?wsdl'
client = zeep.Client(wsdl=wsdl, strict=False)
logintoken = client.service.login('fong', '[email protected]', 'web', 'web')
list = client.service.findAllFileRefs('fong')
filereferencelist = []
for i in list:
    fileRefTitle = ''
    documentCount = ''
    securityGrading = ''
    fileRefNo = ''
    compartment = i['compartment']
    caseRefs = i['caseRefs']

    #   print ('List element: ', i,)
    for rowelement in i['_raw_elements']:
        # 	print (rowelement.tag,":",rowelement.text, "   ",)

        if rowelement.tag == 'fileRefTitle':
            fileRefTitle = rowelement.text
        if rowelement.tag == 'documentCount':
            documentCount = rowelement.text
        if rowelement.tag == 'securityGrading':
            securityGrading = rowelement.text
        if rowelement.tag == 'fileRefNo':
            fileRefNo = rowelement.text

    print('compartment:', compartment, 'fileRefTitle:', fileRefTitle,
          'fileRefNo:', fileRefNo, 'documentCount:', documentCount,
          'securityGrading:', securityGrading, 'caseRefs:', caseRefs)
Пример #16
0
def checkvat(countrycode, vat):
    wsdl = 'http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl'
    client = zeep.Client(wsdl=wsdl)
    return client.service.checkVat(countrycode, vat)
Пример #17
0
def xml_zeep(request):
    wsdl = 'http://www.soapclient.com/xml/soapresponder.wsdl'
    client = zeep.Client(wsdl=wsdl)
    print(client.service.Method1('Zeep', 'is cool'))
    print(client)
    return HttpResponse("success")
Пример #18
0
def request_json(tfrom="admin:fr:75056",
                 tto="admin:fr:69123",
                 tdatetime="20200216T095127",
                 tcurrency='EUR',
                 tfromlat="0",
                 tfromlon="0",
                 ttolat="0",
                 ttolon="0"):
    """
    #DEBUG
    printer('tfrom = ' + tfrom)
    printer('tfromlat = ' + tfromlat)
    printer('tto = ' + tto)
    printer('tdatetime = ' + tdatetime)
    """

    # On effectue une requete a l'api sncf afin de recuperer les trajets associés aux 2 stop point et la date
    r = requests.get('https://api.sncf.com/v1/coverage/sncf/journeys?from=' +
                     tfrom + '&to=' + tto +
                     '&datetime_represents=departure&datetime= ' + tdatetime,
                     auth=HTTPBasicAuth(apiKey, ''),
                     verify=True)
    data = r.json()
    totalduration = time.strftime("%H:%M",
                                  time.gmtime(data['journeys'][0]['duration']))
    """
    #DEBUG
    printer('durée totale du trajet : ' + str(totalduration))
    """

    route = []
    for i in range(0, len(data['journeys'][0]['sections'])):
        if (data['journeys'][0]['sections'][i]['type'] != 'crow_fly') and (
                data['journeys'][0]['sections'][i]['type'] != 'waiting') and (
                    data['journeys'][0]['sections'][i]['type'] != 'transfer'):
            """
            #DEBUG
            printer(data['journeys'][0]['sections'][i]['from']['name'])
            printer(data['journeys'][0]['sections'][i]['display_informations']['commercial_mode'])
            printer(data['journeys'][0]['sections'][i]['display_informations']['headsign'])
            printer(data['journeys'][0]['sections'][i]['to']['name'])
            """

            train_str = data['journeys'][0]['sections'][i][
                'display_informations']['commercial_mode'] + ' n°' + data[
                    'journeys'][0]['sections'][i]['display_informations'][
                        'headsign']
            dur = str(
                time.strftime(
                    "%H:%M",
                    time.gmtime(data['journeys'][0]['sections'][i]['duration'])
                ))  #On transforme la durée en secondes par une string en HH:mm
            """
            #DEBUG
            printer((data['journeys'][0]['sections'][i]['from']['name'], data['journeys'][0]['sections'][i]['to']['name'], train_str, dur, pdatetimetostr(data, i, 'departure_date_time'), pdatetimetostr(data, i, 'arrival_date_time')))
            """

            route.append(
                (data['journeys'][0]['sections'][i]['from']['name'],
                 data['journeys'][0]['sections'][i]['to']['name'], train_str,
                 dur, pdatetimetostr(data, i, 'departure_date_time'),
                 pdatetimetostr(data, i, 'arrival_date_time')))

        elif data['journeys'][0]['sections'][i]['type'] == 'waiting':
            """
            #DEBUG
            printer(data['journeys'][0]['sections'][i]['type'])
            """

            dur = str(
                time.strftime(
                    "%H:%M",
                    time.gmtime(data['journeys'][0]['sections'][i]['duration'])
                ))  #On transforme la durée en secondes par une string en HH:mm
            """
            #DEBUG
            printer((data['journeys'][0]['sections'][i]['type'], ' ' , ' ', dur, ' ', ' '))
            """

            route.append((data['journeys'][0]['sections'][i]['type'], ' ', ' ',
                          dur, ' ', ' '))

    # on instancie le client SOAP
    client = zeep.Client(
        'http://trouvetontrain.herokuapp.com/soapservice/Distance/soap/description'
    )
    distance = round(
        client.service.calcul_distance(tfromlat, ttolat, tfromlon, ttolon) /
        1000, 2)
    """
    #DEBUG
    printer('Distance issue de notre service SOAP :' + str(distance))
    """

    # On effectue une requete a notre api afin de recuperer le prix associé a la distance du trajet et la monnaie
    r1 = requests.get(
        'http://trouvetontrain.herokuapp.com/restservice/price/' + tcurrency +
        '/' + str(distance))
    data1 = r1.json()
    totalprice = round(data1['total'], 2)
    """
    #DEBUG
    printer('Prix issu de notre API REST  :  ' + str(totalprice))
    """
    """
    #DEBUG
    #affiche le json résultant de la requête a l'api SNCF (journeys)
    reponse = make_response(data)
    reponse.mimetype = "application/json"
    return reponse
    """

    return render_template('result.html',
                           la_distance=distance,
                           le_cout=totalprice,
                           la_monnaie=tcurrency,
                           la_duree_totale=totalduration,
                           trajet=route)
Пример #19
0
def call_soap():
    wsdl = 'http://www.soapclient.com/xml/soapresponder.wsdl'
    client = zeep.Client(wsdl=wsdl)
    print("how are you")
    print(print(encryptPassword("abc12345")))
    return client.service.Method1('Zeep', 'is cool')
Пример #20
0
import zeep
import pandas as pd
import asyncio
import asyncio
import time

import zeep

from zeep.asyncio import AsyncTransport

wsdl = 'http://10.21.2.75:8080/service/LBEBusiness?wsdl'
transport = zeep.Transport(cache=None)
client = zeep.Client(wsdl=wsdl, transport=transport)
login_ans = client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", ""),
sessionId = login_ans[0].sessionId
result = []


def handle_future(future):
    result.extend(future.result())
    print('*' * 200)
    print(result)
    print('*' * 200)


# wsdl = 'http://10.21.2.75:8080/service/LBEBusiness?wsdl'
# client = zeep.Client(wsdl=wsdl)
# sessionId = client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", "")
# print(client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", ""))
# factory = client.type_factory('ns0')
Пример #21
0
from __future__ import print_function
import zeep

# display a title
print("Convert number to text/dollars")
print()

# get input from the user
dollar_number= float(input("Enter number of dollars\t\t"))

# obtain results
client = zeep.Client(
    wsdl='http://www.dataaccess.com/webservicesserver/numberconversion.wso?WSDL')

dollars = (client.service.NumberToDollars(dollar_number))

#print result
print (dollars)
Пример #22
0
def run():
    soap_client = zeep.Client(wsdl=_WSDL_LINK)
    db = db_utils.load_database()
    import ipdb; ipdb.set_trace()
    _update_player_table(db, soap_client)
    _update_matches_table(db, soap_client)
def test_hello_world():
    path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                        "hello_world_recursive.wsdl")
    client = zeep.Client(path)
    client.wsdl.dump()
Пример #24
0
def run_async():
    print("async example")
    print("=============")

    result = []

    def handle_future(future):
        result.extend(future.result())
        print(future.result())
        # [unicode(x.strip()) if x is not None else '' for x in row]
        record_list = []
        for row in result:
            if len(row.records) == 0:
                continue
            record_list.extend(row.records)
        record_list = [item.values for item in record_list]
        # record_list = [[record for record in row.records] for row in result]
        df = pd.DataFrame.from_records(record_list, columns=None,)
        df.to_csv('../output/crm_test.csv', encoding='gbk')
        asyncio.ensure_future(logout())




    loop = asyncio.get_event_loop()
    wsdl = 'http://10.21.2.75:8080/service/LBEBusiness?wsdl'
    cache = SqliteCache(path='./sqlite.db', timeout=3600)
    transport = AsyncTransport(loop, cache=cache)
    client = zeep.Client(wsdl, transport=transport)
    # login_ans = client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", ""),
    # sessionId = login_ans[0].sessionId
    async def login(future):
        result = await client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", ""),
        global sessionId
        sessionId = result[0].sessionId
        future.set_result(result[0].sessionId)
    async def logout():
        global sessionId
        result = await client.service.logout(sessionId)

        result = await transport.session.close()
        loop.stop()



    def send_quests(future):
        sessionId = future.result()
        df = pd.read_excel('./客户名单(服务器托管).xlsx')
        df = df.apply(pd.to_numeric, errors='ignore')
        user_ids = df['资金账号'].tolist()
        user_ids = user_ids[0:20]
        tasks = [
            setup_req(sessionId, str(user_id)) for user_id in user_ids
        ]

        future2 = asyncio.gather(*tasks, return_exceptions=True)
        future2.add_done_callback(handle_future)


    async def setup_req(sessionId, user_id,):
        lbParameter_type = client.get_type('ns0:lbParameter')
        queryOption_type = client.get_type('ns0:queryOption')

        par_dict = {"KSRQ": "2018-11-01", "JSRQ": "2018-11-10", "KHH": user_id}
        params = []
        for key in par_dict:
            val = par_dict[key]
            temp_lbParameter = lbParameter_type(name=key, value=val)
            params.append(temp_lbParameter)

        valueOption_type = client.get_type('ns0:valueOption')
        valueOption = valueOption_type('VALUE')
        batchNo = 1
        batchSize = 3000
        mqueryOption = queryOption_type(batchNo=batchNo, batchSize=batchSize,
                                        queryCount=True, valueOption=valueOption)
        #  waits 1 second
        # delay_seconds = random.randrange(5)
        # await asyncio.sleep(delay_seconds)
        # await asyncio.sleep(1)
        result = await client.service.query(sessionId, "cxSqlKHCJMX", params, "", mqueryOption)

        return result

    lbParameter_type = client.get_type('ns0:lbParameter')
    queryOption_type = client.get_type('ns0:queryOption')

    par_dict = {"KSRQ": "2018-11-01", "JSRQ": "2018-11-10", "KHH": "0000050067"}
    params = []
    for key in par_dict:
        val = par_dict[key]
        temp_lbParameter = lbParameter_type(name=key, value=val)
        params.append(temp_lbParameter)

    valueOption_type = client.get_type('ns0:valueOption')
    valueOption = valueOption_type('VALUE')
    batchNo = 1
    batchSize = 3000
    mqueryOption = queryOption_type(batchNo=batchNo, batchSize=batchSize, queryCount=True, valueOption=valueOption)



    # st = time.time()
    # loop.run_until_complete(future)
    # loop.run_until_complete(transport.session.close())
    # print("time: %.2f" % (time.time() - st))
    # print("result: %s" % result)
    # print("")
    # print("sessionId:{sessionId}".format(sessionId=sessionId))
    loop = asyncio.get_event_loop()
    future = asyncio.Future()
    asyncio.ensure_future(login(future))
    future.add_done_callback(send_quests)
    try:
        loop.run_forever()
    finally:
        loop.close()
    return result
Пример #25
0
import suds
import zeep

url = 'http://localhost:4545/RegisterUser?wsdl'
client = zeep.Client(wsdl=url)
#print client.wsdl.dump()

# To get key
client = suds.client.Client(url, cache=None)
print client.service.add('Harry')

url = 'http://localhost:4545/FetchTickers?wsdl'
client = zeep.Client(wsdl=url)
#print client.wsdl.dump()

key = 'USE_KEY'
ticker = 'C_USA_CHN'
field = 'EXPORT'
source = 'USDA'
print client.service.getData(ticker, field, source, key)
Пример #26
0
import zeep

client = zeep.Client(wsdl='http://localhost/TRRP_lab3/server.php?WSDL')
waybill = client.get_element('ns0:Waybill')


def create():
    obj = waybill(date=input('Дата: '),
                  region=input('Регион: '),
                  adress_from=input('Адрес от: '),
                  adress_to=input('Адрес до: '),
                  vehicles=input('ТС: '),
                  reg_number=input('Рег. номер ТС: '),
                  fuel=input('Топливо: '),
                  odometer=input('Показания одометра: '),
                  responsible=input('Ответственный: '),
                  phone=input('Номер телефона: '),
                  winter_highway=10,
                  winter_city=11,
                  summer_highway=9,
                  summer_city=10,
                  fuel_add=input('Заправлено: '),
                  fuel_start=input('Показания топлива при выезде: '),
                  fuel_end=input('Показания топлива при въезде: '),
                  odometer_start=input('Показания одометра при выезде: '),
                  odometer_end=input('Показания одометра при въезде: '),
                  is_city=0,
                  comment=input('Коментарий: '))
    print(client.service.AddWaybill(Waybill=obj))

Пример #27
0
import matplotlib.pyplot as plt
from skimage.transform.pyramids import pyramid_reduce
from skimage.feature import match_template
import cv2 as cv

MVTVSSR_folder_path = os.path.dirname(os.path.abspath(__file__))
input_folder = os.path.join(MVTVSSR_folder_path, "InputData")
output_folder = os.path.join(MVTVSSR_folder_path, "Output")
save_folder = os.path.join(MVTVSSR_folder_path, "SavedModels")

import zeep
import struct
import base64
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
client = zeep.Client(
    'http://turbulence.pha.jhu.edu/service/turbulence.asmx?WSDL')
ArrayOfFloat = client.get_type('ns0:ArrayOfFloat')
ArrayOfArrayOfFloat = client.get_type('ns0:ArrayOfArrayOfFloat')
SpatialInterpolation = client.get_type('ns0:SpatialInterpolation')
TemporalInterpolation = client.get_type('ns0:TemporalInterpolation')
token = "edu.osu.buckeyemail.wurster.18-92fb557b"  #replace with your own token


def get_frame(x_start, x_end, x_step, y_start, y_end, y_step, z_start, z_end,
              z_step, sim_name, timestep, field, num_components):
    #print(x_start)
    #print(x_end)
    #print(y_start)
    #print(y_end)
    #print(z_start)
    #print(z_end)
Пример #28
0
def requestSoapService(body):
    wsdl = 'http://localhost:8081/ws/rules.wsdl'
    client = zeep.Client(wsdl=wsdl)
    return client.service.GetRules(float(body['loanAmount']),
                                   int(body['loanDuration']),
                                   int(body['creditScore']))
Пример #29
0
import zeep

wsdl = 'http://localhost:8080/Calculator/soap/description'
client = zeep.Client(wsdl=wsdl)
print("Addition")
print(client.service.add(6.0,5.0))
print("Subtraction")
print(client.service.sub(6.0,5.0))
print("Multiplication")
print(client.service.mul(6.0,5.0))
print("Division")
print(client.service.div(6.0,5.0))
Пример #30
0
import zeep

my_client = zeep.Client(
    'http://apps.charitycommission.gov.uk/Showcharity/API/SearchCharitiesV1/SearchCharitiesV1.asmx?wsdl'
)
key = open('keyfile', 'r').read().splitlines()[0]
api_search_criteria = my_client.get_type('ns0:APISearchCriteria')()
api_search_criteria.SearchFor = 'OnlyRegisterCharities'
api_search_criteria.Keyword = 'MatchAnyWords'
api_search_criteria.SearchIn = 'All'
api_search_criteria.WhereOperates = {
    'EnglandAndWales': 'OnlySpecific',
    'Specific': 'B-19'
}
api_search_criteria.RegistrationDateFrom_Day = 0
api_search_criteria.RegistrationDateFrom_Month = 0
api_search_criteria.RegistrationDateFrom_Year = 0
api_search_criteria.RegistrationDateTo_Day = 0
api_search_criteria.RegistrationDateTo_Month = 0
api_search_criteria.RegistrationDateTo_Year = 0
api_search_criteria.RemovedDateFrom_Day = 0
api_search_criteria.RemovedDateFrom_Month = 0
api_search_criteria.RemovedDateFrom_Year = 0
api_search_criteria.RemovedDateTo_Day = 0
api_search_criteria.RemovedDateTo_Month = 0
api_search_criteria.RemovedDateTo_Year = 0
api_search_criteria.RegistrationDateFromIsSpecified = False
api_search_criteria.RegistrationDateToIsSpecified = False
api_search_criteria.RemovedDateFromIsSpecified = False
api_search_criteria.RemovedDateToIsSpecified = False
api_search_criteria.IncomeRangeFrom = 1