def get_http_request(url, payload, method='POST', headers=None, use_proxy=False, use_proxy_auth=False, trust_env=True): try: session = Session() session.trust_env = trust_env session.proxies = Util.get_proxies() if use_proxy else None session.auth = Util.get_proxy_auth() if use_proxy_auth else None request = Request( 'POST' if method not in ('GET', 'POST') else method, url, data=payload if method == 'POST' else None, params=payload if method == 'GET' else None, headers=headers ) prepped = request.prepare() response = session.send( prepped, timeout=app.config['HTTP_REQUESTS_TIMEOUT'] ) session.close() except Exception, e: response = Response() response.raise_for_status() return response, 'Error al realizar la consulta - Motivo: {}'.format(e.message)
def __init__(self, env, id_correios, password, cert=False, log_config=None, timeout=None): ''' Webservice initialization. Depending on the env get a different wsdl definition. New Correios SIGEP uses HTTPAuth to do requests. Args: env (str): Environment used to get the wsdl id_correios (str): IdCorreios given by correios website password (str): password vinculated to the IdCorreios log_config (dict): Dictionary configurations of logging ''' ''' Untrusted ssl certificate for homolog envs see more at: https://www.ssllabs.com/ssltest/analyze.html?d=apphom.correios.com.br ''' if cert is False: verify = False else: verify = certifi.where() self.timeout = timeout or 300 if log_config is not None and isinstance(log_config, dict): """ Example config from zeep documentation: { 'version': 1, 'formatters': { 'verbose': { 'format': '%(name)s: %(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'zeep.transports': { 'level': 'DEBUG', 'propagate': True, 'handlers': ['console'], }, } } """ logging.config.dictConfig(log_config) session = Session() session.timeout = self.timeout session.verify = verify session.auth=(id_correios, password) t = Transport(session=session); self.client = Client(wsdl=self.get_env(env), transport=t)
def __init__(self, userid, webhost, password=None): if not password: password = getpass.getpass() session = Session() session.auth = HTTPBasicAuth(userid, password) self.url = "https://{}/footprints/servicedesk/externalapisoap/ExternalApiServicePort?wsdl".format(webhost) self.client = Client(self.url, transport=Transport(session=session))
def create_session(self, alias, headers=None, auth=None, verify="False", cert=None): session = Session() if headers: session.headers.update(headers) if auth: session.auth = tuple(auth) session.verify = self._builtin.convert_to_boolean(verify) session.cert = cert self._cache.register(session, alias)
def github_request(method, endpoint, data=None): github_session = Session() github_session.auth = (env['GITHUB_API_KEY'], 'x-oauth-basic') base_url = 'https://api.github.com' method_func = getattr(github_session, method.lower()) response = method_func( base_url + endpoint, data=data ) return response
def connect(scheme='http', hostname='172.16.1.73', port=80, username='******', password='******'): """ Create new Session in _session_cache """ session = Session() session.auth = (username, password) url = device_url(scheme, hostname, port) session.cookies['device-url'] = url session.cookies['command-url'] = url + '/ins' response = session.get(url) response.raise_for_status() assert _nexus_authentication_cookie_name in response.cookies return session
def setup_api(): session = Session() session.headers.update({'Host': PRODUCTION_DOMAIN}) api_config = { 'base_url': '%s/api/v1/' % API_HOST, 'session': session, } if USER and PASS: log.debug("Using slumber with user %s, pointed at %s", USER, API_HOST) session.auth = (USER, PASS) else: log.warning("SLUMBER_USERNAME/PASSWORD settings are not set") return API(**api_config)
def _setup_session(self): s = Session() if 'verify' in self.settings: # default is True s.verify = self.settings['verify'] if 'trust_env' in self.settings: s.trust_env = self.settings['trust_env'] if self._auth is not None: s.auth = self._auth s.headers = merge_setting( # add our headers to requests' default set self._headers, s.headers, dict_class=CaseInsensitiveDict) return s
def execute_request(method, endpoint, **kwargs): url = "http://%s:%d%s" % (leader, MESOS_MASTER_PORT, endpoint) timeout = 15 s = Session() s.auth = (get_principal(), get_secret()) req = Request(method, url, **kwargs) prepared = s.prepare_request(req) try: resp = s.send( prepared, timeout=timeout, ) resp.raise_for_status() return resp except HTTPError: raise HTTPError("Error executing API request calling %s." % url)
def execute_request(method, endpoint, **kwargs): url = "http://%s:%d%s" % (leader, MESOS_MASTER_PORT, endpoint) timeout = 15 s = Session() s.auth = load_credentials() req = Request(method, url, **kwargs) prepared = s.prepare_request(req) try: resp = s.send( prepared, timeout=timeout, ) resp.raise_for_status() return resp except HTTPError as e: e.msg = "Error executing API request calling %s. Got error: %s" % (url, e.msg) raise
def __init__(self): if settings.GP_WS_ENABLED: cache = SqliteCache(timeout=30 * 24 * 60 * 60) session = Session() session.auth = HttpNtlmAuth( settings.GP_WS_USERNAME, settings.GP_WS_PASSWORD) self.client = Client( settings.GP_WS_URL, transport=Transport(session=session, cache=cache) ) self.ws_factory1 = self.client.type_factory('ns1') self.ws_factory2 = self.client.type_factory('ns2') company = self.ws_factory2.CompanyKey(settings.GP_COMPANY_ID) self.service_context = self.ws_factory2.Context( OrganizationKey=company, CurrencyType='Local' )
def session(requests_session=None, uri=None): global gerrit_session global api_uri if requests_session: gerrit_session = requests_session if uri: api_uri = uri if gerrit_session is None: gerrit_session = Session() # get credentials from .netrc: (user, password) = get_netrc_auth(api_uri) # Gerrit uses HTTP Digest authentication instead of basic: gerrit_session.auth = HTTPDigestAuth(user, password) return gerrit_session
def setup_api(): session = Session() session.headers.update({'Host': PRODUCTION_DOMAIN}) api_config = { 'base_url': '%s/api/v2/' % API_HOST, 'serializer': serialize.Serializer( default='json-drf', serializers=[ serialize.JsonSerializer(), DrfJsonSerializer(), ] ), 'session': session, } if USER and PASS: log.debug("Using slumber v2 with user %s, pointed at %s", USER, API_HOST) session.auth = (USER, PASS) else: log.warning("SLUMBER_USERNAME/PASSWORD settings are not set") return API(**api_config)
def main(url, files, user='', passwd=''): # create session if 'www.moodle.tum.de' in url: session = establish_moodle_session(user, passwd) else: session = Session() session.auth = (user, passwd) session.headers = { "Accept-Language": "en-US,en;" } # get file links links = get_file_links(session, url, files) # download files worker = [] for l in links: while active_count() > NUM_THREADS: sleep(0.1) worker.append(Thread(target=download_files, args=(session, l)).start()) [t.join() for t in worker if t]
def run(args, spicerack): """Required by Spicerack API.""" if spicerack.dry_run: logger.info('this cookbook does nothing with with --dry-run') return 0 ensure_shell_is_durable() session = Session() session.verify = False return_code = 0 current_password = get_secret('Current password') session.auth = (args.username, current_password) _pdus = pdus.get_pdu_ips(spicerack.netbox(), args.query) for pdu in _pdus: try: if args.since: uptime = pdus.parse_uptime(pdus.get_uptime(pdu, session)) if uptime < args.since: logger.info('%s: Not rebooting uptime is %d', pdu, uptime) continue reboot_time = datetime.utcnow() version = pdus.get_version(pdu, session) pdus.reboot(pdu, version, session) # Reboots from expereince take at least 60 seconds logger.info('%s: sleep while reboot', pdu) sleep(60) pdus.wait_reboot_since(pdu, reboot_time, session) except (pdus.VersionError, pdus.RebootError, pdus.UptimeError) as error: logger.error(error) return_code = 1 if args.check_default: if pdus.check_default(pdu, session): # TODO: delete default user return_code = 1 return return_code
def __init__( self, region: RegionEnum, service_endpoint_name, code_unit=True ): """Constructor method of nav base creates an instance of soap client(Zeep) based on endpoint name for Microsoft Navision. The client will be inherited and used by all subclasses of this class. Args: region (RegionEnum): What NAV configuration to use (eu or us) service_endpoint_name (str): NAV SOAP endpoint name. code_unit (bool, optional): There is 2 types of soap endpoints in Navision (Code Units and Pages). Raises: AttributeError: In case of wrong region Fault: Zeep faults in case of incorrect requests being made """ self._service_name = service_endpoint_name self._region = region settings = Settings(region) session = Session() session.auth = HTTPBasicAuth( settings.nav_username, settings.nav_password ) client_url = settings.base_url client_url += settings.store_name client_url += "/Codeunit" if code_unit else "/Page" client_url += "/{endpoint_name}".format( endpoint_name=service_endpoint_name ) self._client = zeep.Client( client_url, transport=Transport(session=session) )
def get_rpt(file_format, report_loc, file_name, filepath): # print('start get report') config = configparser.ConfigParser() config.read('config.ini') username = config['ssrs']['username'] password = config['ssrs']['password'] base_url = config['ssrs']['base_url'] default_report_loc = r'%2fRevenue%20Reporting%2fBranch+Revenue+Report&BRANCH=222-Team Nunzio' if file_format == 'pdf': file_ext = '.pdf' rpt_render = '&rs:Format=PDf' elif file_format == 'excel': file_ext = '.xls' rpt_render = '&rs:Format=EXCEL' else: return('invalid file format') url = base_url + default_report_loc + rpt_render if report_loc: url = base_url + report_loc +rpt_render if file_name: out_file = filepath + file_name + file_ext session = Session() session.auth = HttpNtlmAuth(username=username, password=password) response = session.get(url) try: with open(out_file, 'wb') as f: f.write(response.content) except: print('failed to write to file') session.close()
def init_zeep(self): ''' Initialize ZEEP objects and attach service method references directly to instance. ''' #are the credentials here self.check_config() #add http basic auth wrapper to http requests session = Session() session.auth = HTTPBasicAuth( self.PROD_USERNAME if not self.useTest else self.SANDBOX_USERNAME, self.PROD_PASSWORD if not self.useTest else self.SANDBOX_PASSWORD, ) #wrapped client self.client = zeep.Client( self.wsdl_url, transport=zeep.transports.Transport(session=session)) self.factory = self.client.type_factory('ns0') #wrong service endpoint in WSDL override if self.useTest: if self.useLabs: self.s = self.client.create_service( '{http://e-nadawca.poczta-polska.pl}LABSBinding', 'https://en-testwebapi.poczta-polska.pl/websrv/labs.php') else: self.s = self.client.create_service( '{http://e-nadawca.poczta-polska.pl}ENBinding', 'https://en-testwebapi.poczta-polska.pl/websrv/en.php') else: self.s = self.client.service self.service = self.s self.__attach_service_refs()
def atualizar(documento,tipo_documento): from requests import Session from requests.auth import HTTPBasicAuth import zeep from zeep.transports import Transport session = Session() session.auth = HTTPBasicAuth('example', 'example') transport_with_basic_auth = Transport(session=session) client = zeep.Client( wsdl='https://jiveasset.service-now.com/x_jam_bd_pesquisa.do?WSDL', transport=transport_with_basic_auth ) get = client.service.getKeys( u_cpf_cnpj= documento ) count = int(get['count']) if count == 1: _id = get['sys_id'] update = client.service.update( state="2", u_cpf_cnpj= documento, u_tipo_pessoa = tipo_documento, sys_id=_id[0] ) logger.info("<Update: Tabela de pesquisas do ServiceNow atualizada [%s]>"%documento) else: logger.error("<ERROR: Documento não existe ou duplicado na tabela de pesquisas [%s]>"%documento) return
def main(): path = Path('C:\\shared\\API\\credentials') wsdl = 'file://C://shared//API//axlsqltoolkit//schema//11.5//AXLAPI.wsdl' platform = 'CUCM' role = 'r' urllib3.disable_warnings(InsecureRequestWarning) server = path / REGION / platform / ('fqdn' + '.txt') binding_name = '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding' address = 'https://{fqdn}:8443/axl/'.format(fqdn=read(server)[0]) session = Session() session.verify = False session.auth = HTTPBasicAuth( read(file(path, platform, role)[0])[0], crypto(file(path, platform, role)[1], file(path, platform, role)[2])) transport = Transport(cache=SqliteCache(), session=session, timeout=60) client = Client(wsdl=wsdl, transport=transport) axl = client.create_service(binding_name, address) users = [items['userid'] for items in listUser(axl, '%')['return']['user']] for user in users: udp_to_user = getUser(axl, user)['return']['user']['phoneProfiles'] if udp_to_user is None: try: udp = [ item['name'] for item in listUDP(axl, user)['return']['deviceProfile'] ][0] print('No UDP associated to End User ' + user + '. However, ' + udp + ' could be assigned to that user') except: print('No UDP associated to End User ' + user + '. The user has left or is on CIC (we could check TP)') else: pass
def run(args, spicerack): """Required by Spicerack API.""" ensure_shell_is_durable() return_code = 0 session = Session() session.verify = False password = get_secret('Enter login password') snmp_ro = get_secret('New SNMP RO String', confirm=True) session.auth = (args.username, password) _pdus = pdus.get_pdu_ips(spicerack.netbox(), args.query) for pdu in _pdus: snmp_rw = random_string() if args.reset_rw else None try: if not spicerack.dry_run: version = pdus.get_version(pdu, session) if change_snmp(pdu, version, session, snmp_ro, snmp_rw, args.force): reboot_time = datetime.utcnow() pdus.reboot(pdu, version, session) # Reboots from experience take at least 60 seconds logger.info('%s: sleep while reboot', pdu) sleep(60) pdus.wait_reboot_since(pdu, reboot_time, session) else: logger.info('%s: Dry run, not trying.', pdu) if args.check_default: if pdus.check_default(pdu, session): # TODO: delete default user pass except (pdus.VersionError, SnmpResetError, pdus.RebootError) as error: logger.error(error) return_code = 1 return return_code
async def call_test(request): try: url = request.rel_url.query['url'] user = urllib.parse.quote_plus(request.rel_url.query['user']) password = urllib.parse.quote_plus(request.rel_url.query['pass']) #password= request.rel_url.query['pass'] print('url', url) print('user', user) print('pass', password) session = Session() session.auth = HTTPBasicAuth(user, password) client = Client(url, transport=Transport(session=session)) answer = client.service.wsMonitorTest() if answer == True: answer = '1' else: answer = '0' except Exception as e: answer = 'Error: ' + str(e) return web.Response(text=answer, content_type="text/html")
def getReport(): headerArr = {} settings = Settings(strict=False, xml_huge_tree=True,extra_http_headers=headerArr,raw_response=True) session = Session() session.auth = HTTPBasicAuth(userName, password) transport_with_basic_auth = Transport(session=session) client = Client(request.args['instanceURL'] + '/xmlpserver/services/ExternalReportWSSService?WSDL',settings=settings, transport=transport_with_basic_auth) requestData = { 'reportRequest': { 'flattenXML':'True', 'byPassCache':'True', 'reportAbsolutePath': request.args['reportXDOpath'], 'sizeOfDataChunkDownload':'-1', }, 'appParams': '' , } soapresult = client.service.runReport(**requestData) reportResultB64 = find_between(soapresult.text, '<ns2:reportBytes>', '</ns2:reportBytes>') reportResult = base64.b64decode(reportResultB64) f = open('reportData.csv',"wb") f.write(reportResult) f.close() with open('reportData.csv', 'r') as f: reader = csv.reader(f, delimiter=request.args['csvDelimiter']) data_list = list() for row in reader: data_list.append(row) data = [dict(zip(data_list[0],row)) for row in data_list] data.pop(0) #s = json.dumps(data) res = {'empdata':{'emp': []}} for i in range(len(data)): res['empdata']['emp'].append(data[i]) return jsonify(res)
def main(): path = Path('C:\\shared\\API\\credentials') wsdl = 'file://C://shared//API//axlsqltoolkit//schema//11.5//AXLAPI.wsdl' platform = 'CUCM' role = 'r' urllib3.disable_warnings(InsecureRequestWarning) server = path / REGION / platform / ('fqdn' + '.txt') binding_name = '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding' address = 'https://{fqdn}:8443/axl/'.format(fqdn=read(server)[0]) session = Session() session.verify = False session.auth = HTTPBasicAuth(read(file(path,platform,role)[0])[0], crypto(file(path,platform,role)[1], file(path, platform, role)[2])) transport = Transport(cache=SqliteCache(), session=session, timeout=60) client = Client(wsdl=wsdl, transport=transport) axl = client.create_service(binding_name, address) email = [row['email'] for row in csv.DictReader(open(FILE)) if row['DN'] == 'not known'] emailuser = [item for item in listUser(axl, USER)['return']['user']] csv_headers(NEWFILE) for item1 in emailuser: csv_email = unicodedata.normalize('NFD', str(email)).encode('ascii', 'ignore').decode("utf-8").casefold() cisco_email = unicodedata.normalize('NFD', str(item1['mailid'])).encode('ascii', 'ignore').decode("utf-8").casefold() if cisco_email in csv_email: if myvariables(axl, item1['userid'])['udp'] != 'None': print(myvariables(axl, item1['userid'])) ddi = myvariables(axl, item1['userid'])['DDI'] firstname = myvariables(axl, item1['userid'])['firstname'] lastname = myvariables(axl, item1['userid'])['lastname'] csv_user(NEWFILE, ("\\" + ddi), (firstname + " " + lastname), item1['mailid']) else: print(myvariables(axl, item1['userid'])) ddi = 'No DDI found in Cisco' firstname = myvariables(axl, item1['userid'])['firstname'] lastname = myvariables(axl, item1['userid'])['lastname'] csv_user(NEWFILE, ddi, (firstname + " " + lastname), item1['mailid'])
def retrieve(allocation, start_date, end_date): """Retrieve executed observations by ZTF. Parameters ---------- allocation: skyportal.models.Allocation The allocation with queue information. """ altdata = allocation.altdata if not altdata: raise ValueError('Missing allocation information.') jd_start = Time(start_date, format='datetime').jd jd_end = Time(end_date, format='datetime').jd if jd_start > jd_end: raise ValueError('start_date must be before end_date.') s = Session() s.auth = (altdata['tap_username'], altdata['tap_password']) client = pyvo.dal.TAPService(altdata['tap_service'], session=s) request_str = f""" SELECT field,rcid,fid,expid,obsjd,exptime,maglimit,ipac_gid,seeing FROM ztf.ztf_current_meta_sci WHERE (obsjd BETWEEN {jd_start} AND {jd_end}) """ fetch_obs = functools.partial( fetch_observations, allocation.instrument.id, client, request_str, ) IOLoop.current().run_in_executor(None, fetch_obs)
def get_publish_session(): last_used_setting = os.path.join(os.path.abspath(__file__), '..', 'lastusedprofile.json') try: with open(last_used_setting, 'r', encoding='utf-8') as f: path = json.load(f)["path"] except (OSError, LookupError, json.JSONDecodeError): path = input("Please enter the path to your publishing profile: ").strip('"\'') try: profile = ElementTree.parse(path) data = profile.getroot().find('./publishProfile[@publishMethod="MSDeploy"]') session = Session() session.auth = data.get('userName'), data.get('userPWD') session.headers['If-Match'] = '*' # allow replacing files on upload api_url = 'https://{}/api/'.format(data.get('publishUrl')) except OSError: print("Unable to read the profile at {}.".format(path), file=sys.stderr) print("Please restart deployment and provide the path to your publishing profile.", file=sys.stderr) try: os.unlink(last_used_setting) except OSError: pass sys.exit(2) try: with open(last_used_setting, 'w', encoding='utf-8') as f: json.dump({ 'path': path, 'NOTE': 'Your profile contains secret information. It should not be checked into your repository.' }, f) except OSError: print("Unable to save profile path. You will need to provide the path again", file=sys.stderr) print("for your next deployment.", file=sys.stderr) return session, api_url
def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs self.username = self.kwargs['username'] self.password = self.kwargs['password'] self.ipaddr = self.kwargs['ipaddr'] self.port = self.kwargs.get('port', None) print kwargs if self.port is not None: target = self.ipaddr + ":" + self.port else: target = self.ipaddr self.wsdl = "http://" + target + "/live/CPEManager/DMInterfaces/soap/getWSDL" print self.wsdl session = Session() session.auth = HTTPBasicAuth(self.username, self.password) self.client = Client(wsdl=self.wsdl, transport=Transport(session=session), wsse=UsernameToken(self.username, self.password))
def create_rest_session(self, alias, headers=None, auth=None, verify=False, cert=None): """ Creates REST session with specified alias. Arguments: | alias | session alias | | headers | custom headers for all requests | | auth | basic auth | | verify | SSL verification | | cert | path to SSL certificate file | Example usage: | ${headers} | Create Dictionary | Content-Type | application/json | | @{service_basic_auth} | Set Variable | username | password | | Create Rest Session | session_alias | headers=${headers} | auth=${service_basic_auth} | verify=False | """ session = Session() if headers: session.headers.update(headers) if auth: session.auth = tuple(auth) session.verify = self._builtin.convert_to_boolean(verify) session.cert = cert self._cache.register(session, alias)
def _create_session(self): session = Session() session.auth = self.username, self.key return session
Body: {xml} '''.format(headers=http_headers, xml=etree.tostring(envelope, pretty_print=True, encoding='unicode'))) session = Session() # We avoid certificate verification by default, but you can uncomment and set # your certificate here, and comment out the False setting #session.verify = CERT session.verify = False session.auth = HTTPBasicAuth(creds.USERNAME, creds.PASSWORD) # Create a Zeep transport and set a reasonable timeout value transport = Transport(session=session, timeout=10) # strict=False is not always necessary, but it allows zeep to parse imperfect XML settings = Settings(strict=False, xml_huge_tree=True) # If debug output is requested, add the MyLoggingPlugin callback plugin = [MyLoggingPlugin()] if DEBUG else [] # Create the Zeep client with the specified settings client = Client(WSDL_FILE, settings=settings, transport=transport, plugins=plugin)
from requests import Request, Session s = Session() # req = Request('GET', "https://steelseries.zendesk.com/api/v2/users/me.json") s.auth = ("*****@*****.**", "Fz4Kavncy49mTV6HCN6A") q = {"email": "*****@*****.**", "password": "******"} # s.headers.update({'x-test': 'true'}) s.get("https://steelseries.zendesk.com") # csrftoken = s.cookies['']] s.post("https://id.steelseries.com/zendesk", data=q) for i in s.cookies: print i r = s.get("https://steelseries.zendesk.com") # print r.content # r = s.get("https://analytics.zendesk.com/#s=/gdc/projects/oj4pd7uox9b8zlqq1fh3xa4disp1rasz|projectDashboardPage|") # from urllib2 import Request, urlopen # values = """ # { # "postUserLogin": { # "login": "******", # "password": "******", # "remember": 1
def invoice_validate(self): detalles = [] subtotal = 0 for factura in self: if factura.journal_id.usuario_gface and not factura.firma_gface and factura.amount_total != 0: DocElectronico = etree.Element("DocElectronico") Encabezado = etree.SubElement(DocElectronico, "Encabezado") Receptor = etree.SubElement(DocElectronico, "Receptor") NITReceptor = etree.SubElement(Receptor, "NITReceptor") NITReceptor.text = factura.partner_id.vat.replace('-','') if factura.partner_id.vat == "C/F": Nombre = etree.SubElement(Receptor, "Nombre") Nombre.text = factura.partner_id.name Direccion = etree.SubElement(Receptor, "Direccion") Direccion.text = factura.partner_id.street or "." InfoDoc = etree.SubElement(Encabezado, "InfoDoc") TipoVenta = etree.SubElement(InfoDoc, "TipoVenta") TipoVenta.text = "B" if factura.tipo_gasto == "compra" else "S" DestinoVenta = etree.SubElement(InfoDoc, "DestinoVenta") DestinoVenta.text = "1" Fecha = etree.SubElement(InfoDoc, "Fecha") Fecha.text = fields.Date.from_string(factura.date_invoice).strftime("%d/%m/%Y") Moneda = etree.SubElement(InfoDoc, "Moneda") Moneda.text = "1" Tasa = etree.SubElement(InfoDoc, "Tasa") Tasa.text = "1" Referencia = etree.SubElement(InfoDoc, "Referencia") Referencia.text = str(10000+factura.id) Totales = etree.SubElement(Encabezado, "Totales") Bruto = etree.SubElement(Totales, "Bruto") Bruto.text = "%.2f" % factura.amount_total Descuento = etree.SubElement(Totales, "Descuento") Descuento.text = "0" Exento = etree.SubElement(Totales, "Exento") Exento.text = "0" Otros = etree.SubElement(Totales, "Otros") Otros.text = "0" Neto = etree.SubElement(Totales, "Neto") Neto.text = "%.2f" % factura.amount_untaxed Isr = etree.SubElement(Totales, "Isr") Isr.text = "0" Iva = etree.SubElement(Totales, "Iva") Iva.text = "%.2f" % (factura.amount_total - factura.amount_untaxed) Total = etree.SubElement(Totales, "Total") Total.text = "%.2f" % factura.amount_total subtotal = 0 total = 0 Detalles = etree.SubElement(DocElectronico, "Detalles") for linea in factura.invoice_line_ids: if linea.price_unit != 0 and linea.quantity != 0: precio_unitario = linea.price_unit * (100-linea.discount) / 100 precio_unitario_base = linea.price_subtotal / linea.quantity total_linea = precio_unitario * linea.quantity total_linea_base = precio_unitario_base * linea.quantity total_impuestos = total_linea - total_linea_base tasa = "12" if total_impuestos > 0 else "0" Productos = etree.SubElement(Detalles, "Productos") Producto = etree.SubElement(Productos, "Producto") # Producto.text = linea.product_id.default_code or "-" Producto.text = 'P'+str(linea.product_id.id) Descripcion = etree.SubElement(Productos, "Descripcion") Descripcion.text = linea.name Medida = etree.SubElement(Productos, "Medida") Medida.text = "1" Cantidad = etree.SubElement(Productos, "Cantidad") Cantidad.text = str(linea.quantity) Precio = etree.SubElement(Productos, "Precio") Precio.text = "%.2f" % precio_unitario PorcDesc = etree.SubElement(Productos, "PorcDesc") PorcDesc.text = "0" ImpBruto = etree.SubElement(Productos, "ImpBruto") ImpBruto.text = "%.2f" % total_linea ImpDescuento = etree.SubElement(Productos, "ImpDescuento") ImpDescuento.text = "0" ImpExento = etree.SubElement(Productos, "ImpExento") ImpExento.text = "0" ImpOtros = etree.SubElement(Productos, "ImpOtros") ImpOtros.text = "0" ImpNeto = etree.SubElement(Productos, "ImpNeto") ImpNeto.text = "%.2f" % total_linea_base ImpIsr = etree.SubElement(Productos, "ImpIsr") ImpIsr.text = "0" ImpIva = etree.SubElement(Productos, "ImpIva") ImpIva.text = "%.2f" % (total_linea - total_linea_base) ImpTotal = etree.SubElement(Productos, "ImpTotal") ImpTotal.text = "%.2f" % total_linea total += total_linea subtotal += total_linea_base if factura.journal_id.tipo_documento_gface > 1: DocAsociados = etree.SubElement(Detalles, "DocAsociados") DASerie = etree.SubElement(DocAsociados, "DASerie") DASerie.text = "-".join(factura.numero_viejo.split("-")[:4]) DAPreimpreso = etree.SubElement(DocAsociados, "DAPreimpreso") DAPreimpreso.text = factura.numero_viejo.split("-")[4] xmls = etree.tostring(DocElectronico, xml_declaration=True, encoding="UTF-8", pretty_print=True) logging.warn(xmls) session = Session() session.verify = False session.auth = HTTPBasicAuth('usr_guatefac', 'usrguatefac') session.http_auth = HTTPBasicAuth('usr_guatefac', 'usrguatefac') session.headers.update({'Authorization': 'Basic dXNyX2d1YXRlZmFjOnVzcmd1YXRlZmFj'}) transport = Transport(session=session) wsdl = 'https://*****:*****@pdte.guatefacturas.com/webservices63/produccion/svc01/Guatefac?WSDL' client = zeep.Client(wsdl=wsdl, transport=transport) resultado = client.service.generaDocumento(factura.journal_id.usuario_gface, factura.journal_id.clave_gface, factura.journal_id.nit_gface, factura.journal_id.establecimiento_gface, factura.journal_id.tipo_documento_gface, factura.journal_id.id_maquina_gface, "R", xmls) resultado = resultado.replace("&", "&") logging.warn(resultado) resultadoXML = etree.XML(resultado) if len(resultadoXML.xpath("//Firma")) > 0: firma = resultadoXML.xpath("//Firma")[0].text numero = resultadoXML.xpath("//Serie")[0].text+'-'+resultadoXML.xpath("//Preimpreso")[0].text factura.firma_gface = firma factura.name = numero factura.nombre_cliente_gface = resultadoXML.xpath("//Nombre")[0].text factura.direccion_cliente_gface = resultadoXML.xpath("//Direccion")[0].text else: raise UserError(resultadoXML.xpath("//Resultado")[0].text) return super(AccountInvoice,self).invoice_validate()
# The first step is to create a SOAP client session session = Session() # We avoid certificate verification by default session.verify = False # To enabled SSL cert checking (production) # place the CUCM Tomcat cert .pem file in the root of the project # and uncomment the two lines below # CERT = 'changeme.pem' # session.verify = CERT session.auth = HTTPBasicAuth(creds.AXL_USERNAME, creds.AXL_PASSWORD) transport = Transport(session=session, timeout=10) # strict=False is not always necessary, but it allows zeep to parse imperfect XML settings = Settings(strict=False, xml_huge_tree=True) if DEBUG: client = Client(WSDL_FILE, settings=settings, transport=transport, plugins=[MyLoggingPlugin()]) else: client = Client(WSDL_FILE, settings=settings, transport=transport) service = client.create_service(
def _init_client(self, endpoint): session = Session() session.auth = HTTPDigestAuth( settings.MODC_DOI_API_ID, settings.MODC_DOI_API_PASSWORD) return Client(endpoint, transport=Transport(session=session))
from lxml import etree import getpass # CUCM HostName/ IP Address host = input("CUCM Hostname:") # WSDL Service location download AXLToolKit from Call Manager wsdl = input("WSDL Service path:") # UserName and Password user = input("Username: "******"{http://www.cisco.com/AXLAPIService/}AXLAPIBinding" session = Session() session.verify = False session.auth = HTTPBasicAuth(user, pwd) transport = Transport(cache=SqliteCache(), session=session, timeout=20) history = HistoryPlugin() client = Client(wsdl=wsdl, transport=transport, plugins=[history]) service = client.create_service(binding, location) # creating new device in call manager and configuring some of the device configurations # Note: you can add / remove configurations from the function # to check all the attribute names you can run python -mzeep wsdl def CreatePhone(deviceName, owner, line,description, devicePool, deviceType, phoneTemplateName, softkeyTemplateName, phoneProfile, mediaResourceListName, location, callingSearchSpaceName, subscribeCallingSearchSpaceName, routePartition): try: resp = service.addPhone(phone={'name':deviceName, 'description': description, 'Product':deviceType,
def main(): path = Path('C:\\shared\\API\\credentials') wsdl = 'file://C://shared//API//axlsqltoolkit//schema//11.5//AXLAPI.wsdl' platform = 'CUCM' role = 'rwx' urllib3.disable_warnings(InsecureRequestWarning) server = path / REGION / platform / ('fqdn' + '.txt') binding_name = '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding' address = 'https://{fqdn}:8443/axl/'.format(fqdn=read(server)[0]) session = Session() session.verify = False session.auth = HTTPBasicAuth( read(file(path, platform, role)[0])[0], crypto(file(path, platform, role)[1], file(path, platform, role)[2])) transport = Transport(cache=SqliteCache(), session=session, timeout=60) client = Client(wsdl=wsdl, transport=transport) axl = client.create_service(binding_name, address) for udps in listUDP(axl, UDP)['return']['deviceProfile']: if getUDP(axl, udps['name'])['return']['deviceProfile'][ 'lines'] is None: # and 'ModelProfileFor' not in udps['name']: if 'ModelProfileFor' not in udps['name']: delUDP(axl, udps['name']) print(udps['name'], 'has no Directory Number and has been deleted') print( '#####The End#########The End#########The End#########The End####' ) pass else: pass else: dn = [ items['dirn']['pattern'] for items in getUDP(axl, udps['name'])['return'] ['deviceProfile']['lines']['line'] ][0] if dn.startswith(RANGEDN) is True: mystuff = myvariables(axl, udps['name'], udps['model']) if NEWMODEL in mystuff['model']: print('UDP ' + mystuff['udp'] + ' on directory number ' + mystuff['dn'] + ' already exist for model ' + NEWMODEL) print( '#####The End#########The End#########The End#########The End####' ) if not mystuff['newmodelcheck']: if not mystuff['newmodelcheck'] and mystuff[ 'userid'] == 'no_userid': print( "Looks like a free UDP to me! Didnt find an enduser! Let's create the FREE UDP: " + mystuff['newudp'] + ' with description: ' + mystuff['desc']) addUDP(axl, mystuff['newudp'], NEWMODEL, mystuff['desc'], PTN, mystuff['local'], mystuff['dn'], mystuff['dnpt'], mystuff['llabel'], mystuff['ldisplay']) updateLine(axl, mystuff['dn'], mystuff['dnpt'], mystuff['desc'], mystuff['ldisplay']) print( '#####The End#########The End#########The End#########The End####' ) else: print( "Cool! I found an enduser! Let's create the UDP: " + mystuff['newudp'] + ' with description: ' + mystuff['desc']) addUDP(axl, mystuff['newudp'], NEWMODEL, mystuff['desc'], PTN, mystuff['local'], mystuff['dn'], mystuff['dnpt'], mystuff['llabel'], mystuff['ldisplay']) updateLine(axl, mystuff['dn'], mystuff['dnpt'], mystuff['desc'], mystuff['ldisplay']) mystuff['udplist'].append(mystuff['newudp']) updateUser(axl, mystuff['userid'], mystuff['local'], mystuff['udplist']) print( '#####The End#########The End#########The End#########The End####' ) else: pass else: pass
def __init__(self, uri): session = Session() session.auth = HTTPBasicAuth('tester', 'tester') transport = Transport(session=session) self.client = Client(uri, transport=transport)
#!/usr/bin/env python from requests import Session from requests.auth import HTTPBasicAuth from zeep import Client from zeep.transports import Transport username = '******' apiKey = 'YOUR_API_KEY' wsdlFile = 'https://flightxml.flightaware.com/soap/FlightXML3/wsdl' session = Session() session.auth = HTTPBasicAuth(username, apiKey) client = Client(wsdlFile, transport=Transport(session=session)) boards = client.service.AirportBoards('KHOU',0,'','enroute',10,0) flights = boards['enroute']['flights'] print "Flight enroute to KHOU:" for flight in flights: print "{} ({}) \t{} ({})".format(flight['ident'], flight['aircrafttype'], flight['origin']['airport_name'], flight['origin']['code'])
def GetTestWorkunits(): try: session = Session() if (args.nosslverify): session.verify = False session.sslverify = False if (args.pw and args.user): if (args.httpdigestauth): session.auth = HTTPDigestAuth(args.user, args.pw) else: session.auth = HTTPBasicAuth(args.user, args.pw) transport = DebugTransport(cache=SqliteCache(), session=session) wuquery = Client(wuqueryservice_wsdl_url, transport=transport) except: logging.critical ('Unable to obtain WSDL from %s', wuqueryservice_wsdl_url) raise # Calculate date range (LastNDays not processed correctly by wuquery) enddate = datetime.datetime.now() startdate = enddate - datetime.timedelta(days=args.lastndays) matchedWU = {} logging.debug ('Gathering Workunits') for reqjob in requiredJobs: reqJobname = reqjob[0] reqClusters = reqjob[1] nextPage = 0 while (nextPage >=0): wuqueryresp = wuquery.service.WUQuery(Owner='regress', State='completed', PageSize=500, PageStartFrom=nextPage, LastNDays=args.lastndays, StartDate=startdate.strftime('%Y-%m-%dT00:00:00'), EndDate=enddate.strftime('%Y-%m-%dT23:59:59'), Jobname=reqJobname + '*', Descending='1') try: nextPage = wuqueryresp['NextPage'] workunits = wuqueryresp['Workunits']['ECLWorkunit'] except: return matchedWU try: logging.debug('Workunit count: %d', len(workunits)) workunits.sort(key=lambda k: k['Jobname'], reverse=True) # Extract jobname from jobname with date postfix for wu in workunits: s = wu['Jobname'].split('-') cluster = wu['Cluster'] if (len(s) >2): sep = '-' job = sep.join(s[0:len(s)-2]) else: job = wu['Jobname'] key = job + '_' + cluster if ( (job == reqJobname) and (cluster in reqClusters) and (key not in matchedWU)): matchedWU[key] = wu['Wuid'] except: logging.error('Unexpected response from WUQuery: %s', wuqueryresp) raise return matchedWU
from requests import Session from tcommon import TokenAuth if __name__ == '__main__': s = Session() s.auth = TokenAuth(username='******', password='******', scopes=['me']) r = s.get('http://localhost:8082/api/v1/token_controller/tokenInfo') print(r.json())
Temp2=None, Accountid=None) db.session.add(input) db.session.commit() print( f'Adding {name} to {os} Database with {addr1} {addr2} {tel} {email}' ) newdat = People.query.filter(People.Company == name).first() return newdat.id else: print(f'Found {name}') return cdat.id session = Session() session.auth = HTTPBasicAuth(usernames['magaya'], passwords['magaya']) magaya_wsdl_url = apiservers['magaya'] client = Client(magaya_wsdl_url, transport=Transport(session=session)) token = client.service.StartSession(usernames['magaya'], passwords['magaya']) key = token['access_key'] ret = client.service.GetTransRangeByDate(key, 'BK', '2019-10-01', '2019-11-27', 0) ret_xml = ret['trans_list_xml'] root = ET.fromstring(ret_xml) print(root[0]) for child in root: print(child.tag, child.text) print('end of ET')
def main(): path = Path('C:\\shared\\API\\credentials') wsdl = 'file://C://shared//API//axlsqltoolkit//schema//11.5//AXLAPI.wsdl' platform = 'CUCM' role = 'r' urllib3.disable_warnings(InsecureRequestWarning) server = path / REGION / platform / ('fqdn' + '.txt') binding_name = '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding' address = 'https://{fqdn}:8443/axl/'.format(fqdn=read(server)[0]) session = Session() session.verify = False session.auth = HTTPBasicAuth(read(file(path, platform, role)[0])[0], crypto(file(path, platform, role)[1], file(path, platform, role)[2])) transport = Transport(cache=SqliteCache(), session=session, timeout=60) client = Client(wsdl=wsdl, transport=transport) axl = client.create_service(binding_name, address) csv_headers(FILE) fields_route = {'pattern', 'calledPartyTransformationMask', 'prefixDigitsOut', 'callingPartyTransformationMask', 'callingPartyPrefixDigits'} try: ##Searching for Directory Number for dn in sql_dn(axl, PATTERN): for nb in NBS: fields = {'dnorpattern', 'routepartitionname', 'cfadestination', 'cfbintdestination', 'cfbdestination', 'cfnaintdestination', 'cfnadestination', 'pffintdestination', 'pffdestination', 'devicefailuredn', 'cfurintdestination', 'cfurdestination'} for field in fields: if nb in (str(dn[field])): print_dn(axl,dn) csv_dn(axl,FILE,dn) ##Searching for Translation Pattern if not listTransPattern(axl, PATTERN)['return']: ##No item found pass else: for tp in listTransPattern(axl, PATTERN)['return']['transPattern']: for nb in NBS: for field in fields_route: if nb in (str(tp[field])): print_tp(tp) csv_tp(FILE,tp) ##Searching for Route Pattern if not listRoutePattern(axl, PATTERN)['return']: ##No item found pass else: for rp in listRoutePattern(axl, PATTERN)['return']['routePattern']: for nb in NBS: for field in fields_route: if nb in (str(rp[field])): print_rp(rp) csv_rp(FILE,rp) ##Searching for Hunt Pilot if not listHuntPilot(axl, PATTERN)['return']: ##No item found pass else: for hp in listHuntPilot(axl, PATTERN)['return']['huntPilot']: for nb in NBS: for field in fields_route: if nb in (str(hp[field])): print_hp(hp) csv_hp(FILE,hp) ##Searching for Calling Party Transformation Pattern if not listCallingPartyTransformationPattern(axl, PATTERN)['return']: ##No item found pass else: for cingp in listCallingPartyTransformationPattern(axl, PATTERN)['return']['callingPartyTransformationPattern']: for nb in NBS: fields = {'pattern', 'callingPartyTransformationMask', 'callingPartyPrefixDigits'} for field in fields: if nb in (str(cingp[field])): print_cingp(cingp) csv_cingp(FILE,cingp) ##Searching for Called Party Transformation Pattern if not listCalledPartyTransformationPattern(axl, PATTERN)['return']: ##No item found pass else: for cedp in listCalledPartyTransformationPattern(axl, PATTERN)['return']['calledPartyTransformationPattern']: for nb in NBS: fields = {'pattern', 'calledPartyTransformationMask', 'calledPartyPrefixDigits'} for field in fields: if nb in (str(cedp[field])): print_cedp(cedp) csv_cedp(FILE,cedp) except: print('Except ERROR') pass
from requests import Session s = Session() s.headers['Content-Type'] = 'application/json' s.auth = 'tarek', 'password' """ 同步请求 """ # doing some calls, auth and headers are all set! s.get('http://localhost:5000/api').json() s.get('http://localhost:5000/api2').json()
# The first step is to create a SOAP client session session = Session() # We avoid certificate verification by default session.verify = False # To enable SSL cert checking (recommended for production) # place the CUCM Tomcat cert .pem file in the root of the project # and uncomment the two lines below # CERT = 'changeme.pem' # session.verify = CERT session.auth = HTTPBasicAuth(os.getenv('USERNAME'), os.getenv('PASSWORD')) transport = Transport(session=session, timeout=10) # strict=False is not always necessary, but it allows Zeep to parse imperfect XML settings = Settings(strict=False, xml_huge_tree=True) # If debug output is requested, add the MyLoggingPlugin callback plugin = [MyLoggingPlugin()] if DEBUG else [] # Create the Zeep client with the specified settings client = Client(WSDL_FILE, settings=settings, transport=transport, plugins=plugin)
def _get_session(self) -> Session: """Return a session with headers and auth set.""" session = Session() session.headers = self.headers session.auth = HTTPBasicAuth(self.user, self.api_key) return session
minKW, maxKW, startAccKWH, endAccKWH, AccKWH) print(requete) try: cur = db.cursor() cur.execute(requete) db.commit() cur.close() except: print("unable to record data {0}".format(requete)) # CODE session = Session() session.auth = HTTPBasicAuth('ssegard', 'C3siN@nterre') client = Client( 'https://nrbdfpem.viacesi.fr/daa-webservice/services/soap/daaService?wsdl', transport=Transport(session=session)) db = MySQLdb.connect(host="localhost", user="******", passwd="cesi", db="TEST") PreviousMinute = -1 RoomTesla = Room(1, '00000000-0000-0001-0000-0000000007D7') RoomLumiere = Room(2, '00000000-0000-0001-0000-0000000007D8') RoomNobel = Room(3, '00000000-0000-0001-0000-0000000007D2')
def get_conn(self, *args, **kwargs) -> Session: session = Session() session.auth = self.auth_type(self.connection.password) return session
from requests.auth import HTTPBasicAuth from zeep import Client from zeep.transports import Transport from zeep.cache import SqliteCache import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) WSDL_URL = 'file://~/Python/axlToolkit/axlToolkit/schema/11.5/AXLAPI.wsdl' CUCM_URL = 'https://FQDN:8443/axl/' USERNAME = '******' PASSWD = 'password' session = Session() session.verify = False session.auth = HTTPBasicAuth(USERNAME, PASSWD) transport = Transport(session=session, timeout=10, cache=SqliteCache()) client = Client(WSDL_URL, transport=transport) service = client.create_service("{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", CUCM_URL) # list tags that you want to see or else they return with None tags = {'userid': '', 'presenceGroupName': '', 'acceptPresenceSubscription': '', 'acceptOutOfDialogRefer': '', 'acceptUnsolicitedNotification': '', 'allowReplaceHeader': '', 'isStandard': ''} resp = service.listAppUser(searchCriteria={'userid': '%'}, returnedTags=tags)
def DeepStyle(message, options, images=[]): print("Getting session") s = Session() s.auth = (dsEmail, dsPw) s.headers.update({'User-Agent' : str(UserAgent().chrome)}) print("Getting token") rToken = s.get(dsLoginUrl) if rToken.status_code != 200: message.ReplyText("Error DS 1") return CommandResult.Failed() mToken = dsTokenRx.match(rToken.text) token = mToken.group(1) info = {"_token":token, "email":dsEmail, "password":dsPw, "remember":"true"} print("Logging in") rLogin = s.post(dsLoginUrl, data=info) if rLogin.status_code != 200: message.ReplyText("Error DS 2") return CommandResult.Failed() TryChangeToken(rLogin.text, info) rDeepStyle = s.get(dsUrl, data=info) if rDeepStyle.status_code != 200: message.ReplyText("Error DS 3") return CommandResult.Failed() info = {"_token":info["_token"]} TryChangeToken(rDeepStyle.text, info) print("Getting images") style = images[0].bytes img = images[1].bytes print("Requesting deepstyle") info["style"] = "custom" info["dreamType"]="deep-style" info["resolution"]="normal" info["optimizer"]="alpha" info["iterationsDepth"] ="normal" info["preserveOriginalColors"]="no" info["access"] = "public" info["styleScale"] = "1" info["styleWeight"] = "5" rUploadImg = s.post(dsUploadUrl, data=info, files={'image':img, 'styleImage':style}) if rUploadImg.status_code != 200: message.ReplyText("Error DS 4\n" + rUploadImg.text) return CommandResult.Failed() mDsLink = dsLinkRx.match(rUploadImg.text) if mDsLink is None: message.ReplyText("Error DS 5 : '" + dsErrorRx.match(rUploadImg.text).group(1).replace('"', '"') + "'") return CommandResult.Failed() while mDsLink is None: time.sleep(300) rUploadImg = s.post(dsUploadUrl, data=info, files={'image':img, 'styleImage':style}) if rUploadImg.status_code != 200: message.ReplyText("Error DS 6") return CommandResult.Failed() mDsLink = dsLinkRx.match(rUploadImg.text) dsLink = mDsLink.group(1) message.ReplyText("[DeepStyle] Please wait up to 5 minutes\n" + dsLink) mDsLinkParse = dsLinkParseRx.match(dsLink) host = mDsLinkParse.group(1) path = mDsLinkParse.group(2) WaitOK(host, path) img = Image(url=dsLink) return CommandResult.Done(images=[img])
import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) load_dotenv() # Load Environmental Variable wsdl = os.getenv("WSDL_FILE") username = os.getenv("UCM_USERNAME") password = os.getenv("UCM_PASSWORD") ucm_pub_url = f'https://{os.getenv("UCM_PUB_ADDRESS")}:8443/axl/' session = Session() session.verify = False session.auth = HTTPBasicAuth(username, password) transport = Transport(session=session, timeout=10) history = HistoryPlugin() client = Client(wsdl=wsdl, transport=transport, plugins=[history]) service = client.create_service( binding_name="{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", address=ucm_pub_url, ) css_name = "dp-test-css" get_css_resp = service.getCss(name=css_name)
def registry_request(path, method="GET"): api_url = os.environ['REGISTRY_URL'] + '/v2/' + path try: r = getattr(s, method.lower())(api_url) if r.status_code == 401: raise Exception('Return Code was 401, Authentication required / not successful!') else: return r except RequestException: raise Exception("Problem during docker registry connection") if __name__ == "__main__": s = Session() # get authentication state or set default value REGISTRY_AUTH = os.environ.get('REGISTRY_AUTH',False) # get base_url or set default value FRONTEND_URL = os.getenv('FRONTEND_URL','/') if not FRONTEND_URL.endswith('/'): FRONTEND_URL = FRONTEND_URL + "/" if REGISTRY_AUTH == "True" or REGISTRY_AUTH == "true": s.auth = (os.environ['REGISTRY_USER'], os.environ['REGISTRY_PW']) print ("Registry URL: " + os.environ['REGISTRY_URL']) print ("Frontend URL: " + FRONTEND_URL) app.run(host='0.0.0.0', debug=True)