python-zeep
python-zeep copied to clipboard
Authentication with AsyncTransport
I'm trying to perform HTTP authentication with AsyncTransport using the following code:
session = Session()
session.auth = HTTPBasicAuth(user, password)
transport = AsyncTransport(session=session, cache=None)
client = AsyncClient('http://my-endpoint.com/production.svc?wsdl', transport=transport)
But it returns me the following error:
AttributeError: 'AsyncTransport' object has no attribute 'session'
How can I correctly perform authentication for async calls? Thank you!
Hi,
Synchronous transport is handed by the requests
module, but asynchronous transport is handled by the httpx
module.
To perform HTTP basic auth with httpx
, you need to create an httpx.AsyncClient
object and pass the basic auth parameters in to that object - then you need to pass that object in as the client
parameter to AsyncTransport
, like this:
#!/usr/bin/env python
import httpx
import zeep
from zeep.transports import AsyncTransport
USER = 'username'
PASSWORD = 'password'
HAAC = httpx.AsyncClient(auth=(USER, PASSWORD))
aclient = zeep.AsyncClient(
"http://localhost:8080/webservices/Eval?wsdl",
transport=AsyncTransport(client=HAAC)
)
More details on the httpx
AsyncClient API's can be found here: https://www.python-httpx.org/api/#asyncclient
Hope this helps.
Hello, thank you very much!
I tried this code but authentication does not seem to work properly. I always get "Unauthorized" while the same credentials work fine for the synchronous zeep-only code as provided in the documentation
I also tried to pass authentication credentials manually using the headers option in the httpx
AsyncClient, but nothing changed.
Hi,
I'm not sure where to point you next, as my example code works for me. Have you tested against a different SOAP server to isolate the issue from that side?
Full worked code:
async def aio_main():
client = httpx.AsyncClient(auth=(login, password))
wsdl_client = httpx.Client(auth=(login, password))
client = zeep.AsyncClient(
wsdl=wsdl_url, transport=AsyncTransport(client=client, wsdl_client=wsdl_client))
client.wsdl.dump()
asyncio.run(aio_main())
I have stumbled upon the same issue.
The example code only sets basic-auth for the httpx.AsyncClient
(AsyncTransport.client
) and not the for requests
(AsyncTransport.wsdl_client
).
So if basic-auth is also needed to access the wsdl itself the current async basic-auth example will fail as described in this bug report.
The code posted by @tonal seems to work, by replacing the requests
client with httpx.Client
(non async httpx client).