Connect to Dynamics CRM with python suds - python

I want to use microsoft CRM webservice, I tried this code:
wsdl_url = 'http://crm-test:5555/CRMDeveleopment/XRMServices/2011/Organization.svc?wsdl'
username = 'user'
password = 'pass'
from suds.transport.https import WindowsHttpAuthenticated
from suds.client import Client
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
logging.getLogger('suds.transport').setLevel(logging.DEBUG)
ntlmTransport = WindowsHttpAuthenticated(username=username, password=password)
metadata_client = Client(wsdl_url, transport=ntlmTransport, cache=None)
and I get this error:
Traceback (most recent call last):
File "crm.py", line 15, in <module>
metadata_client = Client(wsdl_url, transport=ntlmTransport)
File "/usr/lib/python2.7/site-packages/suds/client.py", line 112, in __init__
self.wsdl = reader.open(url)
File "/usr/lib/python2.7/site-packages/suds/reader.py", line 152, in open
d = self.fn(url, self.options)
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 157, in __init__
self.open_imports()
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 202, in open_imports
imp.load(self)
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 314, in load
d = Definitions(url, options)
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 159, in __init__
self.build_schema()
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 220, in build_schema
self.schema = container.load(self.options)
File "/usr/lib/python2.7/site-packages/suds/xsd/schema.py", line 95, in load
child.dereference()
File "/usr/lib/python2.7/site-packages/suds/xsd/schema.py", line 323, in dereference
midx, deps = x.dependencies()
File "/usr/lib/python2.7/site-packages/suds/xsd/sxbasic.py", line 469, in dependencies
raise TypeNotFound(self.ref)
suds.TypeNotFound: Type not found: '(ManagedPropertyAttributeRequiredLevel, http://schemas.microsoft.com/xrm/2011/Contracts, )'
output for organization
from suds import WebFault
from suds.client import *
from suds.transport.https import WindowsHttpAuthenticated
user = r'domain.net\username'
password = "password"
url = "http://crm-test:5555/XRMServices/2011/Organization.svc?wsdl"
ntlm = WindowsHttpAuthenticated(username = user, password = password)
client = Client(url, transport=ntlm)
print client
error:
$ python organization.py
DEBUG:suds.transport.http:opening (http://crm-test.kavatelecom.net:5555/XRMServices/2011/Organization.svc?wsdl)
DEBUG:suds.transport.http:opening (http://crm-test.kavatelecom.net:5555/XRMServices/2011/Organization.svc?wsdl=wsdl0)
Traceback (most recent call last):
File "organization.py", line 15, in <module>
client = Client(url, transport=ntlm)
File "/usr/lib/python2.7/site-packages/suds/client.py", line 112, in __init__
self.wsdl = reader.open(url)
File "/usr/lib/python2.7/site-packages/suds/reader.py", line 152, in open
d = self.fn(url, self.options)
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 157, in __init__
self.open_imports()
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 202, in open_imports
imp.load(self)
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 314, in load
d = Definitions(url, options)
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 159, in __init__
self.build_schema()
File "/usr/lib/python2.7/site-packages/suds/wsdl.py", line 220, in build_schema
self.schema = container.load(self.options)
File "/usr/lib/python2.7/site-packages/suds/xsd/schema.py", line 95, in load
child.dereference()
File "/usr/lib/python2.7/site-packages/suds/xsd/schema.py", line 323, in dereference
midx, deps = x.dependencies()
File "/usr/lib/python2.7/site-packages/suds/xsd/sxbasic.py", line 469, in dependencies
raise TypeNotFound(self.ref)
suds.TypeNotFound: Type not found: '(ManagedPropertyAttributeRequiredLevel, http://schemas.microsoft.com/xrm/2011/Contracts, )'

It looks like you are configured to use SOAP 1.2. Can you try your request with Soap 1.1?
I say this because I'm looking at this walk through: http://msdn.microsoft.com/en-us/library/gg594434.aspx
The request mentioned there conforms to the earlier standard (as indicated by the mime type.)
As far as how to do this with the suds library: After reading through the documentation a bit, I was inclined to rip my own eyes out. (Just kidding, I'm just used to reading a different type of documentation I suppose.) I'm sure you're far more used to browsing it than I am, and would be able to figure it out very quickly: http://jortel.fedorapeople.org/suds/doc/

finnally I connect to crm web service.but I get ""400, u'Bad Request'"" error when I execute my reques!
my code is:
from suds import WebFault
from suds.client import *
from suds.transport.https import WindowsHttpAuthenticated
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.transport.http').setLevel(logging.DEBUG)
user = r'domain\username'
password = "pass"
url = "http://domain:5555/XRMServices/2011/Discovery.svc?wsdl"
ntlm = WindowsHttpAuthenticated(username = user, password = password)
client = Client(url, transport=ntlm)
print client
req = client.factory.create('ns3:RetrieveOrganizationsRequest')
accessTypes = client.factory.create('ns3:EndpointAccessType')
orgRel = client.factory.create('ns3:OrganizationRelease')
req.AccessType = accessTypes.Default
req.Release = orgRel.Current
headers = dict()
headers['Content-Type'] = 'application/soap+xml'
client.set_options(headers=headers)
resp = client.service.Execute(req)
the output of print client:
$ python newcrm.py
Suds ( https://fedorahosted.org/suds/ ) version: 0.4 GA build: R699-20100913
Service ( DiscoveryService ) tns="http://schemas.microsoft.com/xrm/2011/Contracts"
Prefixes (4)
ns0 = "http://schemas.datacontract.org/2004/07/System.Collections.Generic"
ns1 = "http://schemas.microsoft.com/2003/10/Serialization/"
ns2 = "http://schemas.microsoft.com/xrm/2011/Contracts"
ns3 = "http://schemas.microsoft.com/xrm/2011/Contracts/Discovery"
Ports (1):
(CustomBinding_IDiscoveryService)
Methods (1):
Execute(ns3:DiscoveryRequest request, )
Types (24):
BaseServiceFault
ns3:DiscoveryRequest
ns3:DiscoveryResponse
DiscoveryServiceFault
ns3:EndpointAccessType
ns3:EndpointCollection
ns3:EndpointType
ErrorDetailCollection
ns0:KeyValuePairOfEndpointTypestringztYlk6OT
ns0:KeyValuePairOfstringanyType
ns3:OrganizationDetail
ns3:OrganizationDetailCollection
ns3:OrganizationRelease
OrganizationServiceFault
ns3:OrganizationState
ns3:RetrieveOrganizationRequest
ns3:RetrieveOrganizationResponse
ns3:RetrieveOrganizationsRequest
ns3:RetrieveOrganizationsResponse
ns3:RetrieveUserIdByExternalIdRequest
ns3:RetrieveUserIdByExternalIdResponse
ns1:char
ns1:duration
ns1:guid
and the error I get :
DEBUG:suds.transport.http:sending:
URL:http://crm-test.kavatelecom.net:5555/XRMServices/2011/Discovery.svc
HEADERS: {'SOAPAction': u'"http://schemas.microsoft.com/xrm/2011/Contracts/Discovery/IDiscoveryService/Execute"', 'Content-Type': 'application/soap+xml', 'Content-type': 'application/soap+xml', 'Soapaction': u'"http://schemas.microsoft.com/xrm/2011/Contracts/Discovery/IDiscoveryService/Execute"'}
MESSAGE:
<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/xrm/2011/Contracts/Discovery" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><ns0:Body><ns1:Execute><ns1:request xsi:type="ns1:RetrieveOrganizationsRequest"><ns1:AccessType>Default</ns1:AccessType><ns1:Release>Current</ns1:Release></ns1:request></ns1:Execute></ns0:Body></SOAP-ENV:Envelope>
ERROR:suds.client:<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/xrm/2011/Contracts/Discovery" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns0:Body>
<ns1:Execute>
<ns1:request xsi:type="ns1:RetrieveOrganizationsRequest">
<ns1:AccessType>Default</ns1:AccessType>
<ns1:Release>Current</ns1:Release>
</ns1:request>
</ns1:Execute>
</ns0:Body>
</SOAP-ENV:Envelope>
Traceback (most recent call last):
File "newcrm.py", line 32, in <module>
resp = client.service.Execute(req)
File "/usr/lib/python2.7/site-packages/suds/client.py", line 542, in __call__
return client.invoke(args, kwargs)
File "/usr/lib/python2.7/site-packages/suds/client.py", line 602, in invoke
result = self.send(soapenv)
File "/usr/lib/python2.7/site-packages/suds/client.py", line 649, in send
result = self.failed(binding, e)
File "/usr/lib/python2.7/site-packages/suds/client.py", line 708, in failed
raise Exception((status, reason))
Exception: (400, u'Bad Request')

Related

AuthError trying to connect to neo4j from python

I'm trying to run neo4j in a docker container and connect to it from a python script not running in a container, but I'm getting AuthError.
I'm following the instructions from here
Start neo4j
docker run \
--publish=7474:7474 --publish=7687:7687 \
--volume=$HOME/neo4j/data:/data \
--volume=$HOME/neo4j/logs:/logs \
neo4j:3.5
I've also done this with these added insturctions "By default Neo4j requires authentication and requires you to login with neo4j/neo4j at the first connection and set a new password. You can set the password for the Docker container directly by specifying --env NEO4J_AUTH=neo4j/ in your run directive."
Start neo4j
docker run \
--publish=7474:7474 --publish=7687:7687 \
--volume=$HOME/neo4j/data:/data \
--volume=$HOME/neo4j/logs:/logs \
--env NEO4J_AUTH=neo4j/neo \
neo4j:3.5
After doing either of these, I am able to connect via the web interface at http://localhost:7474/
Now I want to connect with a python script as described here which has me run this code (note I've changed the password to match the NEO4J_AUTH setting from the docker command).
from neo4j import GraphDatabase
class HelloWorldExample:
def __init__(self, uri, user, password):
self.driver = GraphDatabase.driver(uri, auth=(user, password))
def close(self):
self.driver.close()
def print_greeting(self, message):
with self.driver.session() as session:
greeting = session.write_transaction(self._create_and_return_greeting, message)
print(greeting)
#staticmethod
def _create_and_return_greeting(tx, message):
result = tx.run("CREATE (a:Greeting) "
"SET a.message = $message "
"RETURN a.message + ', from node ' + id(a)", message=message)
return result.single()[0]
if __name__ == "__main__":
greeter = HelloWorldExample("bolt://localhost:7687", "neo4j", "neo")
greeter.print_greeting("hello, world")
greeter.close()
When I run this code I get this error.
Traceback (most recent call last):
File "/Users/j/projects/neotest/neo.py", line 25, in <module>
greeter = HelloWorldExample("bolt://localhost:7687", "neo4j", "neo4j")
File "/Users/j/projects/neotest/neo.py", line 6, in __init__
self.driver = GraphDatabase.driver(uri, auth=(user, password))
File "/usr/local/lib/python3.7/site-packages/neo4j/__init__.py", line 183, in driver
return cls.bolt_driver(parsed.netloc, auth=auth, **config)
File "/usr/local/lib/python3.7/site-packages/neo4j/__init__.py", line 196, in bolt_driver
return BoltDriver.open(target, auth=auth, **config)
File "/usr/local/lib/python3.7/site-packages/neo4j/__init__.py", line 359, in open
pool = BoltPool.open(address, auth=auth, pool_config=pool_config, workspace_config=default_workspace_config)
File "/usr/local/lib/python3.7/site-packages/neo4j/io/__init__.py", line 531, in open
seeds = [pool.acquire() for _ in range(pool_config.init_size)]
File "/usr/local/lib/python3.7/site-packages/neo4j/io/__init__.py", line 531, in <listcomp>
seeds = [pool.acquire() for _ in range(pool_config.init_size)]
File "/usr/local/lib/python3.7/site-packages/neo4j/io/__init__.py", line 545, in acquire
return self._acquire(self.address, timeout)
File "/usr/local/lib/python3.7/site-packages/neo4j/io/__init__.py", line 409, in _acquire
connection = self.opener(address, timeout)
File "/usr/local/lib/python3.7/site-packages/neo4j/io/__init__.py", line 528, in opener
return Bolt.open(addr, auth=auth, timeout=timeout, routing_context=routing_context, **pool_config)
File "/usr/local/lib/python3.7/site-packages/neo4j/io/__init__.py", line 227, in open
raise error
File "/usr/local/lib/python3.7/site-packages/neo4j/io/__init__.py", line 222, in open
connection.hello()
File "/usr/local/lib/python3.7/site-packages/neo4j/io/_bolt3.py", line 148, in hello
self.fetch_all()
File "/usr/local/lib/python3.7/site-packages/neo4j/io/_bolt3.py", line 393, in fetch_all
detail_delta, summary_delta = self.fetch_message()
File "/usr/local/lib/python3.7/site-packages/neo4j/io/_bolt3.py", line 339, in fetch_message
response.on_failure(summary_metadata or {})
File "/usr/local/lib/python3.7/site-packages/neo4j/io/_bolt3.py", line 544, in on_failure
raise AuthError(message)
neo4j.exceptions.AuthError: {code: None} {message: None}
Your error does indicate a bit different code:
Traceback (most recent call last):
File "/Users/j/projects/neotest/neo.py", line 25, in <module>
greeter = HelloWorldExample("bolt://localhost:7687", "neo4j", "neo4j")
Here it shows that you initiated the HelloWorldClass with password "neo4j" instead of "neo"

How to fix "google.api_core.exceptions.ServiceUnavailable: 503 Connect Failed" when connected to Google cloud API

I want to use GOOGLE vision API,and I get the error 'google.api_core.exceptions.ServiceUnavailable: 503 Connect Failed'.
I get 503 error when connecting to Google vision API, and i have followed the instruction step by step. The link is as follows:
https://cloud.google.com/vision/docs/quickstart-client-libraries
I download my key file(json format) and ensure API is enabled.I set the environment variable and follow other instruction by putting the os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r"/Users/a529157492/Desktop/application_default_credentials 2.json"
directly in the code.
However, i still get the error code.
import io
import os
from google.cloud import vision
from google.cloud.vision import types
from google.oauth2 import service_account
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] =
r"/Users/a529157492/Desktop/application_default_credentials 2.json"
client = vision.ImageAnnotatorClient()
file_name = os.path.abspath(r'/Users/a529157492/Desktop/demo-img.jpg')
with io.open(file_name, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')[enter image description here][1]
for label in labels:
print(label.description)
However, I get the following errors:
Traceback (most recent call last):
File "/Users/a529157492/PycharmProjects/untitled7/venv/lib/python3.6/site-
packages/google/api_core/grpc_helpers.py", line 57, in
error_remapped_callable
return callable_(*args, **kwargs)
File "/Users/a529157492/PycharmProjects/untitled7/venv/lib/python3.6/site-
packages/grpc/_channel.py", line 532, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/Users/a529157492/PycharmProjects/untitled7/venv/lib/python3.6/site-
packages/grpc/_channel.py", line 466, in _end_unary_response_blocking
raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "Connect Failed"
debug_error_string = "
{"created":"#1569469218.801077000","description":"Failed to create
subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc",
"file_line":2636,"referenced_errors":
[{"created":"#1569469218.801045000","description":"Pick
Cancelled","file":"src/core/ext/filters/client_channel/lb_policy/pick_first
/pick_first.cc","file_line":241,"referenced_errors":
[{"created":"#1569469218.800545000","description":"Connect
Failed","file":"src/core/ext/filters/client_channel/subchannel.cc",
"file_line":663,"grpc_status":14,"referenced_errors":
[{"created":"#1569469218.800511000","description":"Failed to connect to
remote host: FD
shutdown","file":"src/core/lib/iomgr/ev_poll_posix.cc",
"file_line":532,"grpc_status":14,"os_error":"Timeout
occurred","referenced_errors":
[{"created":"#1569469218.800460000","description":"connect() timed
out","file":"src/core/lib/iomgr/tcp_client_posix.cc","file_line":114}],
"target_address":"ipv4:172.217.27.138:443"}]}]}]}"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/a529157492/PycharmProjects/untitled7/pictureanalysis.py", line
24, in <module>
response = client.label_detection(image=image)
File "/Users/a529157492/PycharmProjects/untitled7/venv/lib/python3.6/site-
packages/google/cloud/vision_helpers/decorators.py", line 101, in inner
response = self.annotate_image(request, retry=retry, timeout=timeout)
File "/Users/a529157492/PycharmProjects/untitled7/venv/lib/python3.6/site-
packages/google/cloud/vision_helpers/__init__.py", line 72,
in annotate_image
r = self.batch_annotate_images([request], retry=retry, timeout=timeout)
File "/Users/a529157492/PycharmProjects/untitled7/venv/lib/python3.6/site-
packages/google/cloud/vision_v1/gapic/image_annotator_client.py", line 274,
in batch_annotate_images
request, retry=retry, timeout=timeout, metadata=metadata
File "/Users/a529157492/PycharmProjects/untitled7/venv/lib/python3.6/site-
packages/google/api_core/gapic_v1/method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "/Users/a529157492/PycharmProjects/untitled7/venv/lib/python3.6/site-
packages/google/api_core/grpc_helpers.py", line 59, in
error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.ServiceUnavailable: 503 Connect Failed

AXL Python getLine using pattern instead of uuid does not work (CUCM 11.5)

I'm struggling with getting for example line info via getLine using pattern instead of uuid. According to getLine AXL schema for CUCM 11.5 it should be possible to choose either uuid or pattern as lookup criteria. The python (2.7) module that I'm using is suds-jurko 0.6.
Base code is as follows:
from suds.client import Client
import ssl
wsdl = 'file:///C:/Users/xyz/Documents/axlplugin/schema/current/AXLAPI.wsdl'
location = 'https://10.10.20.1/axl/'
username = '***'
password = '***'
ssl._create_default_https_context = ssl._create_unverified_context
client = Client(wsdl, location=location, username=username, password=password)
First of all, the proof that the pattern I want to use as a lookup string for getLine actually exists:
>>> line2 = client.service.listLine({'pattern': '1018'}, returnedTags={'description': ''})
>>> line2
(reply){
return =
(return){
line[] =
(LLine){
_uuid = "{1EC56035-6B5D-283A-4DF0-EFEFA01FCEFF}"
description = None
},
}
}
Then, I try getLine using uuid which works well:
>>> line5 = client.service.getLine('1EC56035-6B5D-283A-4DF0-EFEFA01FCEFF')
>>> line5
(reply){
return =
(return){
line =
(RLine){
_uuid = "{1EC56035-6B5D-283A-4DF0-EFEFA01FCEFF}"
pattern = "1018"
description = None
usage = "Device"
routePartitionName = ""
aarNeighborhoodName = ""
----Rest omitted for brevity---
Now, if I try to use pattern, not uuid, I have following error:
line6 = client.service.getLine({'pattern': '1018'}, {'routePartitionName': ''})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\suds\client.py", line 521, in __call__
return client.invoke(args, kwargs)
File "C:\Python27\lib\site-packages\suds\client.py", line 576, in invoke
soapenv = binding.get_message(self.method, args, kwargs)
File "C:\Python27\lib\site-packages\suds\bindings\binding.py", line 109, in get_message
content = self.bodycontent(method, args, kwargs)
File "C:\Python27\lib\site-packages\suds\bindings\document.py", line 95, in bodycontent
add_param, self.options().extraArgumentErrors)
File "C:\Python27\lib\site-packages\suds\argparser.py", line 83, in parse_args
return arg_parser(args, kwargs, extra_parameter_errors)
File "C:\Python27\lib\site-packages\suds\argparser.py", line 108, in __call__
self.__process_parameters()
File "C:\Python27\lib\site-packages\suds\argparser.py", line 299, in __process_parameters
self.__process_parameter(*pdef)
File "C:\Python27\lib\site-packages\suds\argparser.py", line 294, in __process_parameter
self.__in_choice_context(), value)
File "C:\Python27\lib\site-packages\suds\bindings\document.py", line 86, in add_param
p = self.mkparam(method, pdef, value)
File "C:\Python27\lib\site-packages\suds\bindings\document.py", line 130, in mkparam
return Binding.mkparam(self, method, pdef, object)
File "C:\Python27\lib\site-packages\suds\bindings\binding.py", line 225, in mkparam
return marshaller.process(content)
File "C:\Python27\lib\site-packages\suds\mx\core.py", line 59, in process
self.append(document, content)
File "C:\Python27\lib\site-packages\suds\mx\core.py", line 72, in append
self.appender.append(parent, content)
File "C:\Python27\lib\site-packages\suds\mx\appender.py", line 88, in append
appender.append(parent, content)
File "C:\Python27\lib\site-packages\suds\mx\appender.py", line 229, in append
Appender.append(self, child, cont)
File "C:\Python27\lib\site-packages\suds\mx\appender.py", line 168, in append
self.marshaller.append(parent, content)
File "C:\Python27\lib\site-packages\suds\mx\core.py", line 71, in append
if self.start(content):
File "C:\Python27\lib\site-packages\suds\mx\literal.py", line 86, in start
raise TypeNotFound(content.tag)
suds.TypeNotFound: Type not found: 'pattern'
Trying different syntax also gives error:
line6 = client.service.getLine('1018')
No handlers could be found for logger "suds.client"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\suds\client.py", line 521, in __call__
return client.invoke(args, kwargs)
File "C:\Python27\lib\site-packages\suds\client.py", line 581, in invoke
result = self.send(soapenv)
File "C:\Python27\lib\site-packages\suds\client.py", line 619, in send
description=tostr(e), original_soapenv=original_soapenv)
File "C:\Python27\lib\site-packages\suds\client.py", line 670, in process_reply
raise WebFault(fault, replyroot)
suds.WebFault: Server raised fault: 'Item not valid: The specified Line was not found'
Am I using incorrect syntax or it's actually not possible to use pattern however schema file states differently?
Additionally, I'm wondering how to extract only uuid value from for example listLine method, is it possible via python axl?
In Suds, if memory serves me correctly, you can use keyword arguments for get and update requests.
For example:
resp = client.service.getLine(routePartitionName='PT-ONCLUSTER', pattern='\+49301234567')
if that doesn't work, try:
resp = client.service.getLine({'routePartitionName': 'PT-ONCLUSTER', 'pattern': '\+49301234567'})
Or better yet, check out python-zeep instead. It's much faster and better maintained than suds. Some example code with Zeep:
# -*- coding: utf-8 -*-
from zeep import Client
from zeep.cache import SqliteCache
from zeep.transports import Transport
from zeep.exceptions import Fault
from zeep.plugins import HistoryPlugin
from requests import Session
from requests.auth import HTTPBasicAuth
from urllib3 import disable_warnings
from urllib3.exceptions import InsecureRequestWarning
from lxml import etree
disable_warnings(InsecureRequestWarning)
username = 'admin'
password = 'password'
# If you're not disabling SSL verification, host should be the FQDN of the server rather than IP
host = '10.1.1.1'
wsdl = 'file://C:/path/to/wsdl/AXLAPI.wsdl'
location = 'https://{host}:8443/axl/'.format(host=host)
binding = "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding"
# Create a custom session to disable Certificate verification.
# In production you shouldn't do this,
# but for testing it saves having to have the certificate in the trusted store.
session = Session()
session.verify = False
session.auth = HTTPBasicAuth(username, password)
transport = Transport(cache=SqliteCache(), session=session, timeout=20)
history = HistoryPlugin()
client = Client(wsdl=wsdl, transport=transport, plugins=[history])
service = client.create_service(binding, location)
def show_history():
for item in [history.last_sent, history.last_received]:
print(etree.tostring(item["envelope"], encoding="unicode", pretty_print=True))
try:
resp = service.getLine(pattern='1018', routePartitionName='')
except Fault:
show_history()

python SOAP with zeep, requests.exception: 403 client error

I'm trying to make a SOAP client in python using zeepSo far I've had zero luck in trying to get it to run. I keep getting the following error.
Traceback (most recent call last):
File "C:/Users/z905/PycharmProjects/Soap_Test/soap_test.py", line 14, in <module>
client = Client(wsdl=client_location, transport=transport_with_basic_auth)
File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\client.py", line 134, in __init__
self.wsdl = Document(wsdl, self.transport, strict=strict)
File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\wsdl\wsdl.py", line 81, in __init__
root_definitions = Definition(self, document, self.location)
File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\wsdl\wsdl.py", line 178, in __init__
self.parse_imports(doc)
File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\wsdl\wsdl.py", line 270, in parse_imports
document = self.wsdl._get_xml_document(location)
File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\wsdl\wsdl.py", line 140, in _get_xml_document
location, self.transport, self.location, strict=self.strict)
File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\loader.py", line 72, in load_external
content = transport.load(url)
File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\transports.py", line 110, in load
content = self._load_remote_data(url)
File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\transports.py", line 126, in _load_remote_data
response.raise_for_status()
File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\requests\models.py", line 935, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden (Forbidden port) for url: http://url:7104
I've tried the program with and without basic authentication.
from zeep import Client
from requests import Session
from requests.auth import HTTPBasicAuth
from zeep.transports import Transport
client_location = "file://C:/<path-to-local-file>"
loc = "<url-to-wsdl>"
session = Session()
session.auth = HTTPBasicAuth('usrname', 'pass')
transport_with_basic_auth = Transport(session=session)
client = Client(wsdl=client_location, transport=transport_with_basic_auth)
And version without Basic Auth.
from zeep import Client
from zeep.wsse.username import UsernameToken
client_location = "file://C:/<path-to-local-file>"
loc = "<url-to-wsdl>"
client = Client(wsdl=loc, wsse=UsernameToken(usr, password, use_digest=True))
I was able to solve the issue by doing the following. The issue was caused by some firewall issues and the proxy not working.
import requests
session = requests.session()
session.trust_env = False
transport = Transport(session=session)
client = Client(wsdl=client_location, wsse=UsernameToken(usr, password, use_digest=True), transport=transport)

Fetching an jira issue using python i'm getting authentication error

>>> # Get all projects viewable by anonymous users.
... projects = jira.projects()
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Python27\lib\site-packages\jira_python-0.16-py2.7.egg\jira\client.py", line 941, in projects
r_json = self._get_json('project')
File "C:\Python27\lib\site-packages\jira_python-0.16-py2.7.egg\jira\client.py", line 1526, in _get_json
r = self._session.get(url, params=params, headers=self._options['headers'])
File "C:\Python27\lib\site-packages\requests-2.2.1-py2.7.egg\requests\sessions.py", line 395, in get
return self.request('GET', url, **kwargs)
File "C:\Python27\lib\site-packages\requests-2.2.1-py2.7.egg\requests\sessions.py", line 383, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests-2.2.1-py2.7.egg\requests\sessions.py", line 486, in send
r = adapter.send(request, **kwargs)
File "C:\Python27\lib\site-packages\requests-2.2.1-py2.7.egg\requests\adapters.py", line 381, in send
raise ProxyError(e)
**requests.exceptions.ProxyError: Cannot connect to proxy. Socket error: Tunnel connection failed: 407 authenticationrequired.**
Can you please any one help me how to solve this issue.
Try This:
basic_auth = ('username', 'password')
options = {
'server': <server url>,
'proxies' : <proxy>,
'verify' : False,
}
jira = JIRA(options,basic_auth=basic_auth,validate=True)
should work.
I tried and it is working for me.
Make sure you have access to the project to acess the issue.

Categories

Resources