Created
July 16, 2013 23:34
-
-
Save marsam/6016226 to your computer and use it in GitHub Desktop.
suds urllib3 transport
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| from urllib3 import connection_from_url | |
| from urllib3.util import make_headers | |
| from urllib3.exceptions import HTTPError | |
| from suds.transport import Transport, TransportError, Reply | |
| class Urllib3Transport(Transport): | |
| """ | |
| urllib3 transport. | |
| Compatible with ``suds.transport.HttpTransport`` and | |
| ``suds.transport.HttpAuthenticated`` | |
| """ | |
| def __init__(self, url, **kwargs): | |
| """ | |
| @param url | |
| URL from which to get connection type (http or https), | |
| host name and a port. | |
| @param kwargs | |
| passed to [...] | |
| """ | |
| # suds uses old style classes :( | |
| # super(Urllib3Transport, self).__init__(*args, **kwargs) | |
| Transport.__init__(self) | |
| if kwargs.get('username') and kwargs.get('password'): | |
| username = kwargs.pop('username') | |
| password = kwargs.pop('password') | |
| basic_auth = '{0}:{1}'.format(username, password) | |
| self.headers = make_headers(basic_auth=basic_auth) | |
| else: | |
| self.headers = {} | |
| self.http = connection_from_url(url, **kwargs) | |
| def open(self, request): | |
| url = request.url | |
| self.headers.update(request.headers) | |
| try: | |
| response = self.http.request('GET', url=url, headers=self.headers) | |
| return response.data | |
| except HTTPError as e: | |
| raise TransportError(str(e), 0, e.message) | |
| def send(self, request): | |
| url = request.url | |
| body = request.message | |
| self.headers.update(request.headers) | |
| try: | |
| response = self.http.request_encode_url('POST', url=url, body=body, headers=self.headers) | |
| if response.status == 200: | |
| return Reply(200, response.headers, response.data) | |
| else: | |
| raise TransportError('Bad status code', response.status, response.data) | |
| except HTTPError as e: | |
| raise TransportError(str(e), 0, e.message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
thanks for this useful code snippet.
I've a problem with that and suds 0.4 because Transport.open method is expected to return a stream and not a string. A workaround could be returning StringIO object wrapping the
response.data. I didn't found a better strategy with current urllib3, but probably it exists.Luca