Commits

Bruce Kroeze committed ab80229

multiple domains now working

  • Participants
  • Parent commits ddf006c

Comments (0)

Files changed (5)

File httpproxy/decorators.py

 from httpproxy import settings
 from httpproxy.recorder import ProxyRecorder
 
-
-proxy = ProxyRecorder(settings.PROXY_DOMAIN, settings.PROXY_PORT)
+if hasattr(settings, 'PROXY_DOMAIN'):
+    proxy = ProxyRecorder(settings.PROXY_DOMAIN, settings.PROXY_PORT)
+else:
+    proxy = ProxyRecorder(None, None, domains=settings.PROXY_DOMAINS)
 
 def normalize_request(fn):
     """
     Updates all path-related info in the original request object with the url
     given to the proxy.
-    
+
     This way, any further processing of the proxy'd request can just ignore
     the url given to the proxy and use request.path safely instead.
     """
     Decorator for recording the request being made and its response.
     """
     def decorate(request, *args, **kwargs):
-        
+
         # Make the actual live request as usual
         response = fn(request, *args, **kwargs)
-        
+
         # Record the request and response
         proxy.record(request, response)
 
     """
     def decorate(request, *args, **kwargs):
         response = fn(request, *args, **kwargs)
-        proxy_root = reverse('httpproxy.views.proxy', 
+        proxy_root = reverse('httpproxy.views.proxy',
             kwargs={'url': ''}
         )
         response.content = REWRITE_REGEX.sub(r'\1%s' % proxy_root, response.content)
         return response
 
-    return decorate
+    return decorate

File httpproxy/exceptions.py

 Some generic exceptions that can occur in the Django HTTP Proxy.
 """
 
-class UnkownProxyMode(Exception):
+class UnknownProxyMode(Exception):
     pass
 
 class ResponseUnsupported(Exception):

File httpproxy/recorder.py

     """
     Facilitates recording and playback of Django HTTP requests and responses.
     """
-    
-    def __init__(self, domain, port):
+
+    def __init__(self, domain, port, domains=None):
         super(ProxyRecorder, self).__init__()
         self.domain, self.port = domain, port
-    
+        self.domains = domains
+
     def record(self, request, response):
         """
         Attempts to record the request and the corresponding response.
             self.record_response(recorded_request, response)
         elif not settings.PROXY_IGNORE_UNSUPPORTED:
             raise ResponseUnsupported('Response of type "%s" could not be recorded.' % response['Content-Type'])
-    
+
     def record_request(self, request):
         """
         Saves the provided request, including its parameters.
         """
         logger.info('Recording: GET "%s"' % self._request_string(request))
-        
+
         recorded_request, created = Request.objects.get_or_create(
             domain=self.domain,
             port=self.port,
             path=request.path,
             querykey=self._get_query_key(request),
         )
-        
+
         self.record_request_parameters(request, recorded_request)
-        
+
         # Update the timestamp on the existing recorded request
         if not created:
             recorded_request.save()
-        
+
         return recorded_request
-    
+
     def record_request_parameters(self, request, recorded_request):
         """
         Records the request parameters for the recorded request.
-        
+
         The order field is set to reflect the order in which the QueryDict
         returns the GET parameters.
         """
                     value=value,
                 )
                 position += 1
-    
+
     def record_response(self, recorded_request, response):
         """
         Records a response so it can be replayed at a later stage.
-        
+
         The recorded response is linked to a previously recorded request and
         its request parameters to allow for reverse-finding the recorded
         response given the recorded request object.
         """
-        
+
         # Delete the previously recorded response, if any
         try:
             recorded_request.response.delete()
         except Response.DoesNotExist:
             pass
-        
+
         # Extract the encoding from the response
         content_type = response['Content-Type']
         encoding = content_type.partition('charset=')[-1] or 'utf-8'
             request=recorded_request,
             status=response.status_code,
             content_type=content_type,
-            content=response.content.decode(encoding), 
+            content=response.content.decode(encoding),
         )
-    
+
     def playback(self, request):
         """
         Returns a previously recorded response based on the provided request.
             ).latest()
         except Request.DoesNotExist, e:
             raise RequestNotRecorded('The request made has not been recorded yet. Please run httpproxy in "record" mode first.')
-        
+
         logger.info('Playback: GET "%s"' % self._request_string(request))
         response = matching_request.response # TODO handle "no response" situation
         encoding = self._get_encoding(response.content_type)
-        
+
         return HttpResponse(
-            response.content.encode(encoding), 
-            status=response.status, 
+            response.content.encode(encoding),
+            status=response.status,
             mimetype=response.content_type
         )
-    
+
     def response_supported(self, response):
         return response['Content-Type'].partition(';')[0] in RESPONSE_TYPES_SUPPORTED
-    
+
     def _get_encoding(self, content_type):
         """
         Extracts the character encoding from an HTTP Content-Type header.
         """
         return content_type.partition('charset=')[-1] or 'utf-8'
-        
+
     def _request_string(self, request):
         """
         Helper for getting a string representation of a request.
         """
         return '%(domain)s:%(port)d%(path)s' % {
-            'domain': self.domain, 
-            'port': self.port, 
+            'domain': self.domain,
+            'port': self.port,
             'path': request.get_full_path()
         }
-    
+
     def _get_query_key(self, request):
         """
         Returns an MD5 has of the request's query parameters.
         """
         querystring = request.GET.urlencode()
         return md5_constructor(querystring).hexdigest()
-    
+

File httpproxy/settings.py

 'httpproxy' application.
 """
 
-try:
-    PROXY_DOMAIN = getattr(settings, 'PROXY_DOMAIN')
-except AttributeError:
-    from django.core.exceptions import ImproperlyConfigured
-    raise ImproperlyConfigured("To use the 'httpproxy' app, please add the PROXY_DOMAIN setting to your settings module.")
+PROXY_DOMAINS = getattr(settings, 'PROXY_DOMAINS', None)
 
-PROXY_PORT = getattr(settings, 'PROXY_PORT', 80)
+if PROXY_DOMAINS is None:
+    try:
+        PROXY_DOMAIN = getattr(settings, 'PROXY_DOMAIN')
+    except AttributeError:
+        from django.core.exceptions import ImproperlyConfigured
+        raise ImproperlyConfigured("To use the 'httpproxy' app, please add the PROXY_DOMAIN setting to your settings module.")
 
-# Optional authentication
-if hasattr(settings, 'PROXY_USER') and hasattr(settings, 'PROXY_PASSWORD'):
-    PROXY_USER = settings.PROXY_USER
-    PROXY_PASSWORD = settings.PROXY_PASSWORD
+    PROXY_PORT = getattr(settings, 'PROXY_PORT', 80)
+
+    # Optional authentication
+    if hasattr(settings, 'PROXY_USER') and hasattr(settings, 'PROXY_PASSWORD'):
+        PROXY_USER = settings.PROXY_USER
+        PROXY_PASSWORD = settings.PROXY_PASSWORD
 
 PROXY_MODE = getattr(settings, 'PROXY_MODE', None)
 

File httpproxy/views.py

 from httpproxy import settings
 from httpproxy.exceptions import UnknownProxyMode
 from httpproxy.decorators import normalize_request, rewrite_response
+import logging
 
+log = logging.getLogger(__file__)
 
+log.debug('init')
 PROXY_FORMAT = u'%s:%d%s'
 
 def proxy(request, proxy_server = None):
             data = request.PUT.urlencode()
         response, content = conn.request(url, request.method, data)
 
+    log.debug('returning proxy request: %s', url);
     return HttpResponse(content, status=int(response['status']), mimetype=response['content-type'])