Created
June 5, 2014 18:29
-
-
Save dgouldin/ce69774497b6a63b3712 to your computer and use it in GitHub Desktop.
Requests-based Suds transport
This file contains 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 __future__ import unicode_literals | |
from requests import Session | |
from requests.adapters import BaseAdapter | |
from requests.auth import HTTPBasicAuth | |
from requests.models import Response | |
from suds.properties import Unskin | |
from suds.transport import Transport, TransportError, Reply | |
class FileAdapter(BaseAdapter): | |
def send(self, request, **kwargs): | |
response = Response() | |
response.headers = {} | |
response.encoding = 'utf-8' # FIXME: this is a complete guess | |
response.url = request.url | |
response.request = request | |
response.connection = self | |
try: | |
response.raw = open(request.url.replace('file://', ''), 'r') | |
except IOError as e: | |
response.status_code = 404 | |
return response | |
response.status_code = 200 | |
return response | |
def close(self): | |
pass | |
class RequestsHttpTransport(Transport): | |
def __init__(self, session=None, **kwargs): | |
super(RequestsHttpTransport, self).__init__() | |
Unskin(self.options).update(kwargs) | |
self.session = session or Session() | |
# Suds expects support for local files URIs. | |
self.session.mount('file://', FileAdapter()) | |
def _call(self, request, method): | |
headers = dict(self.options.headers) | |
headers.update(request.headers) | |
if self.options.username and self.options.password: | |
auth = HTTPBasicAuth(self.options.username, self.options.password) | |
else: | |
auth=None | |
response = getattr(self.session, method)(request.url, | |
auth=auth, | |
data=request.message, | |
headers=headers, | |
timeout=self.options.timeout, | |
proxies=self.options.proxy, | |
stream=True) | |
if response.status_code >= 400: | |
raise TransportError(response.content, response.status_code) | |
return response | |
def open(self, request): | |
return self._call(request, 'get').raw | |
def send(self, request): | |
response = self._call(request, 'post') | |
return Reply(response.status_code, response.headers, response.content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment