Example #1
0
 def crear_cliente_academica():
     """
     Metodo generico para crear una conexion con el webservice SGA - académico
     ejem datos de carreras,matriculas,ofertas...
     :return: cliente de conexion tipo suds.client.Client
     """
     from app.configuracion.models import DetalleParametrizacion
     url = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS',
         codigo='sgaws_url_academica').first()
     location = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS',
         codigo='sgaws_location_academica').first()
     port = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS',
         codigo='sgaws_port_academica').first()
     user = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS', codigo='sgaws_usuario').first()
     passwd = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS', codigo='sgaws_password').first()
     client = Client(url=url.valor,
                     username=user.valor,
                     password=passwd.valor,
                     location=location.valor)
     client.set_options(port=port.valor)
     return client
Example #2
0
 def crear_cliente_personal():
     """
     Metodo generico para crear una conexion con el webservice SGA - personal
     Ejem datos de estudiantes,docente,usuario
     :return: cliente de conexion tipo suds.client.Client
     """
     from app.configuracion.models import DetalleParametrizacion
     url = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS',
         codigo='sgaws_url_personal').first()
     location = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS',
         codigo='sgaws_location_personal').first()
     port = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS',
         codigo='sgaws_port_personal').first()
     user = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS', codigo='sgaws_usuario').first()
     passwd = DetalleParametrizacion.objects.filter(
         parametrizacion__codigo='SGA_WS', codigo='sgaws_password').first()
     client = Client(url=url.valor,
                     username=user.valor,
                     password=passwd.valor,
                     location=location.valor)
     client.set_options(port=port.valor)
     return client
Example #3
0
 def submit_observation(self, observation_payload):
     if (LT_SETTINGS['DEBUG']):
         payload = etree.fromstring(observation_payload)
         f = open("created.rtml", "w")
         f.write(
             etree.tostring(payload, encoding="unicode", pretty_print=True))
         f.close()
         return [0]
     else:
         headers = {
             'Username': LT_SETTINGS['username'],
             'Password': LT_SETTINGS['password']
         }
         url = '{0}://{1}:{2}/node_agent2/node_agent?wsdl'.format(
             'http', LT_SETTINGS['LT_HOST'], LT_SETTINGS['LT_PORT'])
         client = Client(url=url, headers=headers)
         # Send payload, and receive response string, removing the encoding tag which causes issue with lxml parsing
         response = client.service.handle_rtml(observation_payload).replace(
             'encoding="ISO-8859-1"', '')
         response_rtml = etree.fromstring(response)
         mode = response_rtml.get('mode')
         if mode == 'reject':
             self.dump_request_response(observation_payload, response_rtml)
         obs_id = response_rtml.get('uid')
         return [obs_id]
Example #4
0
    def get(self):
        is_wsdl = self.get_query_argument('wsdl', None)
        if self.request.uri in ["/api/requestgroups/", "/api/triggers/ztf"]:
            cache = get_cache_file_static()
        else:
            cache = get_cache_file()
        with my_vcr.use_cassette(cache, record_mode="new_episodes") as cass:
            base_route = self.request.uri.split("?")[0]

            real_host = None
            for route in cfg["test_server.redirects"].keys():
                if re.match(route, base_route):
                    real_host = cfg["test_server.redirects"][route]

            if real_host is not None:
                url = real_host + self.request.uri

                # Convert Tornado HTTPHeaders object to a regular dict
                headers = {}
                for k, v in self.request.headers.get_all():
                    # Multiple values for a header should be in a comma-separated list
                    if k in headers:
                        headers[k] += f",{v}"
                    else:
                        headers[k] = str(v)

                if is_wsdl is not None:
                    log(f"Forwarding WSDL call {url}")
                    Client(url=url, headers=headers, cache=None)
                else:
                    log(f"Forwarding GET call: {url}")
                    requests.get(url, headers=headers)

                # Get recorded document and pass it back
                response = cass.responses_of(
                    vcr.request.Request("GET", url, "", headers))[0]
                self.set_status(response["status"]["code"],
                                response["status"]["message"])
                for k, v in response["headers"].items():
                    # Content Length may change (for the SOAP call) as we overwrite the host
                    # in the response WSDL. Similarly, the response from this test server
                    # will not be chunked even if the real response was.
                    if k != "Content-Length" and not (k == "Transfer-Encoding"
                                                      and "chunked" in v):
                        self.set_header(k, v[0])

                if is_wsdl is not None:
                    # Override service location in the service definition
                    # so we can intercept the followup POST call
                    response_body = (
                        response["body"]["string"].decode("utf-8").replace(
                            real_host,
                            f"http://localhost:{cfg['test_server.port']}"))
                else:
                    response_body = response["body"]["string"]
                self.write(response_body)

            else:
                self.set_status(500)
                self.write("Could not find test route redirect")
Example #5
0
 def __init__(self,
              barcode,
              login=os.environ['LOGIN'],
              password=os.environ['PASSWORD']):
     self.client = Client(self.url, headers=self.headers)
     self.login = login
     self.password = password
     self.barcode = barcode
Example #6
0
def generate_ku_qr(applicant, application, additional_payment, filename):
    KU_QR_SERVICE_URL = settings.KU_QR_SERVICE_URL
    KU_QR_CALLBACK_URL = settings.KU_QR_CALLBACK_URL

    amount = "{:08.2f}".format(additional_payment)

    admission_project = application.admission_project
    project_round = admission_project.get_project_round_for(
        application.admission_round)
    deadline = project_round.payment_deadline
    deadline_str = "%02d%02d%02d" % (deadline.day, deadline.month,
                                     deadline.year % 100)

    ref1 = str(
        application.admission_round.number) + '000' + applicant.national_id
    ref2 = "{:06d}".format(application.get_number())

    client = Client(KU_QR_SERVICE_URL)

    callback_url = KU_QR_CALLBACK_URL % (ref2, )

    retry = 0
    while True:
        result = client.service.getOeaQr(expireDate=deadline_str,
                                         appCode='01',
                                         transactionId=ref2,
                                         amount=amount,
                                         ref1Prefix=ref1,
                                         ref2Prefix=ref2,
                                         billerSuffix='87',
                                         callbackUrl=callback_url)
        if result.success:
            break
        retry += 1
        if retry > 2:
            break

    if result.success:
        img_base64 = result.qrResult.content[23:]

        import base64
        from PIL import Image
        from io import BytesIO

        im = Image.open(BytesIO(base64.b64decode(img_base64)))
        im = im.resize((390, 390))
        im = im.crop((30, 30, 360, 360))
        im.save(filename + '.png', 'PNG')
        return True
    else:
        LogItem.create('QR error: ' + str(result)[:180], applicant)
        return False
Example #7
0
def get_board(crs, token):
    """
        Get a live departure board from the LDBWS service.
        The data shows the next 20 trains currently scheduled
        to leave from that station. The data should match
        that shown on the real-life departure boards in the station
        and in mapping apps, etc.

         - crs: a three-letter token identifying a UK station.
                You can find out the CRS of a station at
                http://www.nationalrail.co.uk/stations_destinations/48541.aspx
         - token: An API access token.
    """
    client = Client(wsdl_url, location=service_url)

    access_token = client.factory.create("ns2:AccessToken")
    access_token.TokenValue = token
    client.set_options(soapheaders=access_token)

    service = client.service
    result = service.GetDepartureBoard(20, crs)
    return result
Example #8
0
    def submit(request):
        """Submit a follow-up request to LT's SPRAT.

        Parameters
        ----------
        request: skyportal.models.FollowupRequest
            The request to add to the queue and the SkyPortal database.
        """

        from ..models import DBSession, FacilityTransaction

        altdata = request.allocation.altdata
        if not altdata:
            raise ValueError('Missing allocation information.')

        ltreq = SPRATRequest(request)
        observation_payload = ltreq.observation_payload

        headers = {
            'Username': altdata["username"],
            'Password': altdata["password"],
        }
        url = f"http://{cfg['app.lt_host']}:{cfg['app.lt_port']}/node_agent2/node_agent?wsdl"
        client = Client(url=url, headers=headers)
        full_payload = etree.tostring(observation_payload,
                                      encoding="unicode",
                                      pretty_print=True)
        # Send payload, and receive response string, removing the encoding tag which causes issue with lxml parsing
        response = client.service.handle_rtml(full_payload).replace(
            'encoding="ISO-8859-1"', '')
        response_rtml = etree.fromstring(response)
        mode = response_rtml.get('mode')

        if mode == 'confirm':
            request.status = 'submitted'
        else:
            error = list(
                response_rtml.iter('{http://www.rtml.org/v3.1a}Error'))[0].text
            request.status = f'rejected: {error}'

        transaction = FacilityTransaction(
            request=http.serialize_requests_request_xml(full_payload),
            response=http.serialize_requests_response_xml(response),
            followup_request=request,
            initiator_id=request.last_modified_by_id,
        )

        DBSession().add(transaction)
Example #9
0
    def login(self, username, token, domain=None):
        from suds import Client
        WSDL_URL = settings.OPENOTP_WSDL_URL  # noqa
        WEBSERVICE_URL = settings.OPENOTP_WEBSERVICE_URL  # noqa
        DEFAULT_DOMAIN = settings.OPENOTP_DEFAULT_DOMAIN  # noqa

        if domain is None:
            domain = DEFAULT_DOMAIN

        try:
            client = Client(WSDL_URL, location=WEBSERVICE_URL)
            reply = client.service.openotpLogin(username, domain, None, token)
        except Exception as e:
            logger.error('Error in communication with the OpenOTP server')
            logger.exception(e)
            return False
        return (reply['code'] == 1)
Example #10
0
class Api(object):
    client = Client('http://namazvakti.diyanet.gov.tr/wsNamazVakti.svc?wsdl')
    # client.service.GunlukNamazVakti(9541, "namazuser", "NamVak!14")
    service = client.service
    # ssnns = ('ssn', 'http://namespaces/sessionid')
    # ssn = Element('SOAP:Action', ns=ssnns).setText('123')
    # client.set_options(soapheaders=sn)
    auth = dict(username="******", password="******")

    def ulkeler(self):
        return self.service.Ulkeler(**self.auth)['Ulke']

    def sehirler(self, ulkeid):
        return self.service.Sehirler(ulkeid, **self.auth)['Sehir']

    def ilceler(self, sehirid):
        return self.service.Ilceler(sehirid, **self.auth)['Ilce']

    def aylik(self, ilceid):
        return self.service.AylikNamazVakti(ilceid, **self.auth)[0]

    def haftalik(self, ilceid):
        return self.service.HaftalikNamazVakti(ilceid, **self.auth)[0]

    def gunluk(self, ilceid):
        return self.service.GunlukNamazVakti(ilceid, **self.auth)[0][0]

    def gunluk_sehir(self, sehiradi):
        return self.service.GunlukNamazVakti_SehirAdinaGore(
            sehiradi, **self.auth)

    def bayram(self, ilceid):
        return dict(self.service.BayramNamaziVakti(ilceid, **self.auth))

    def bayram_tum(self, sehirid):
        result = self.service.BayramNamaziVaktiIlceListesi(
            sehirid, **self.auth)
        return result  # dict(result)

    def imsakiye(self, ilceid):
        return self.service.Imsakiye(ilceid, **self.auth)[0]

    def ilcedetay(self, ilceid):
        return self.service.IlceBilgisiDetay2(ilceid, **self.auth)[1]
Example #11
0
    def validate_observation(self, observation_payload):
        if (LT_SETTINGS['DEBUG']):
            return []
        else:
            headers = {
                'Username': LT_SETTINGS['username'],
                'Password': LT_SETTINGS['password']
            }
            url = '{0}://{1}:{2}/node_agent2/node_agent?wsdl'.format(
                'http', LT_SETTINGS['LT_HOST'], LT_SETTINGS['LT_PORT'])
            client = Client(url=url, headers=headers)
            validate_payload = etree.fromstring(observation_payload)
            # Change the payload to an inquiry mode document to test connectivity.
            validate_payload.set('mode', 'inquiry')
            # Send payload, and receive response string, removing the encoding tag which causes issue with lxml parsing
            print("Trying")
            try:
                response = client.service.handle_rtml(
                    validate_payload).replace('encoding="ISO-8859-1"', '')
            except:
                return [
                    'Error with connection to Liverpool Telescope',
                    'This could be due to incorrect credentials, or IP / Port settings',
                    'Occassionally, this could be due to the rebooting of systems at the Telescope Site',
                    'Please retry at another time.',
                    'If the problem persists please contact [email protected]'
                ]

            response_rtml = etree.fromstring(response)
            print("HERE", response)
            if response_rtml.get('mode') == 'offer':
                self.dump_request_response()(observation_payload, response)
                return []
            elif response_rtml.get('type') == 'reject':
                self.dump_request_response()(observation_payload, response)
                return [
                    'Error with RTML submission to Liverpool Telescope',
                    'This can occassionally happen due to systems rebooting at the Telescope Site',
                    'Please retry at another time.',
                    'If the problem persists please contact [email protected]'
                ]
Example #12
0
def check(s):
    url = 'http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl'
    d = Client(url)
    x = 1
    while x > 0:
        if s.isdigit():
            if int(s) < x:
                break
            if len(s) != 11:
                return ('手机号位数不对!请重新输入')
                continue
            else:
                r = d.service.getMobileCodeInfo(s)
                print(r)
                n = r.split()
                n1 = n[0].split(":")
                print(n)
                return (n)
                break
        else:
            return ('输入的不全是数字!')
            continue
Example #13
0
    def __init__(self, username: str, password: str, tenant=None, host: str ='app.deepsecurity.trendmicro.com',\
                 port: int = "443", verify_ssl:str = False):
        kwargs = {}
        self._username = username
        self._password = password
        self._tenant = tenant
        self.host = host
        self.headers = {'Content-Type': 'application/json'}

        self.port = port
        self.verify_ssl = verify_ssl
        self.config = Config(self.host, self.port)
        url = self.config.soap_url()

        if verify_ssl == False:
            sslContext = create_ssl_context(False, None, None)
            kwargs['transport'] = HTTPSTransport(sslContext)

        self.client = Client(url, **kwargs)

        if tenant:
            self.session_id = self._authenticate_tenant()
        else:
            self.session_id = self.__authenticate()
Example #14
0
                    return redirect('saloons:payment', reserve.id,
                                    get_saloon.amount)
            else:
                print('not valid')
        else:
            messages.success(request, 'برای ثبت رزرو لطفا وارد حساب خود شوید',
                             'warning')
            return redirect('accounts:user_login')
    else:
        form = ReserveDatetime()
    context = {'saloon': get_saloon, 'images': images, 'form': form}
    return render(request, 'saloons/saloon_detail.html', context)


MERCHANT = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'
client = Client('https://sandbox.zarinpal.com/pg/services/WebGate/wsdl')
description = "توضیحات پرداخت"
mobile = '09123456789'
amount = None
CallbackURL = 'http://localhost:8000/payment/verify/'


@login_required
def payment(request, reserve_id, amount):
    request.session[f'{request.user}'] = {
        'user': {
            'reserve_id': reserve_id,
            'amount': amount + 1000
        },
    }
    result = client.service.PaymentRequest(MERCHANT, amount + 1000,
Example #15
0
                coupon = Coupon.objects.get(code=data["code"],
                                            start__lte=time,
                                            end__gte=time,
                                            active=True)
            except Coupon.DoesNotExist:
                messages.error(request, "code is invalid or it is expired",
                               "danger")
                return redirect(url)
            order = Order.objects.get(id=id)
            order.discount = coupon.discount
            order.save()
        return redirect(url)


MERCHANT = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
client = Client("https://www.zarinpal.com/pg/services/WebGate/wsdl")
description = "Description"  # Required
mobile = "09123456789"  # Optional
CallbackURL = (
    "http://*****:*****@login_required(login_url="account:sign_in")
def send_request(request, price, order_id):
    global amount, o_id
    amount = price
    o_id = order_id
    result = client.service.PaymentRequest(MERCHANT, amount, description,
                                           request.user.email, mobile,
                                           CallbackURL)
Example #16
0
    def delete(request):
        """Delete a follow-up request from LT queue (all instruments).

        Parameters
        ----------
        request: skyportal.models.FollowupRequest
            The request to delete from the queue and the SkyPortal database.
        """

        from ..models import DBSession, FollowupRequest, FacilityTransaction

        req = (DBSession().query(FollowupRequest).filter(
            FollowupRequest.id == request.id).one())

        altdata = request.allocation.altdata
        if not altdata:
            raise ValueError('Missing allocation information.')

        content = req.transactions[0].response["response"]
        response_rtml = etree.fromstring(content)
        uid = response_rtml.get('uid')

        headers = {
            'Username': altdata["username"],
            'Password': altdata["password"],
        }
        url = f"http://{cfg['app.lt_host']}:{cfg['app.lt_port']}/node_agent2/node_agent?wsdl"

        namespaces = {
            'xsi': LT_XSI_NS,
        }
        schemaLocation = etree.QName(LT_XSI_NS, 'schemaLocation')
        cancel_payload = etree.Element(
            'RTML',
            {schemaLocation: LT_SCHEMA_LOCATION},
            mode='abort',
            uid=format(str(uid)),
            version='3.1a',
            nsmap=namespaces,
        )
        project = etree.SubElement(cancel_payload,
                                   'Project',
                                   ProjectID=altdata["LT_proposalID"])
        contact = etree.SubElement(project, 'Contact')
        etree.SubElement(contact, 'Username').text = altdata["username"]
        etree.SubElement(contact, 'Name').text = altdata["username"]
        etree.SubElement(contact, 'Communication')
        cancel = etree.tostring(cancel_payload,
                                encoding='unicode',
                                pretty_print=True)

        client = Client(url=url, headers=headers)
        # Send cancel_payload, and receive response string, removing the encoding tag which causes issue with lxml parsing
        response = client.service.handle_rtml(cancel).replace(
            'encoding="ISO-8859-1"', '')
        response_rtml = etree.fromstring(response)
        mode = response_rtml.get('mode')
        uid = response_rtml.get('uid')
        if mode == 'confirm':

            request.status = "deleted"

            transaction = FacilityTransaction(
                request=http.serialize_requests_request_xml(cancel),
                response=http.serialize_requests_response_xml(response),
                followup_request=request,
                initiator_id=request.last_modified_by_id,
            )
            DBSession().add(transaction)