Skip to content

Commit

Permalink
Merge pull request #1 from hfries/feature/update-django
Browse files Browse the repository at this point in the history
updates for django 3
  • Loading branch information
hfries authored Oct 7, 2020
2 parents 0bf66c2 + 156ab29 commit 62b5cb8
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 44 deletions.
4 changes: 2 additions & 2 deletions httpproxy/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class Migration(migrations.Migration):
('order', models.PositiveSmallIntegerField(default=1)),
('name', models.CharField(max_length=100, verbose_name='naam')),
('value', models.CharField(max_length=250, null=True, verbose_name='value', blank=True)),
('request', models.ForeignKey(related_name='parameters', verbose_name='request', to='httpproxy.Request')),
('request', models.ForeignKey(related_name='parameters', verbose_name='request', to='httpproxy.Request', on_delete=models.CASCADE)),
],
options={
'ordering': ('order',),
Expand All @@ -52,7 +52,7 @@ class Migration(migrations.Migration):
('status', models.PositiveSmallIntegerField(default=200)),
('content_type', models.CharField(max_length=200, verbose_name='inhoudstype')),
('content', models.TextField(verbose_name='inhoud')),
('request', models.OneToOneField(verbose_name='request', to='httpproxy.Request')),
('request', models.OneToOneField(verbose_name='request', to='httpproxy.Request', on_delete=models.CASCADE)),
],
options={
'verbose_name': 'response',
Expand Down
8 changes: 4 additions & 4 deletions httpproxy/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.db import models
from django.utils.six.moves import urllib
from urllib.parse import urlencode
from django.utils.translation import ugettext as _


Expand Down Expand Up @@ -55,7 +55,7 @@ class RequestParameterManager(models.Manager):
def urlencode(self):
output = []
for param in self.values('name', 'value'):
output.extend([urllib.parse.urlencode({param['name']: param['value']})])
output.extend([urlencode({param['name']: param['value']})])
return '&'.join(output)


Expand All @@ -68,7 +68,7 @@ class RequestParameter(models.Model):
('G', 'GET'),
('P', 'POST'),
)
request = models.ForeignKey(Request, verbose_name=_('request'), related_name='parameters')
request = models.ForeignKey(Request, verbose_name=_('request'), related_name='parameters', on_delete=models.CASCADE)
type = models.CharField(max_length=1, choices=REQUEST_TYPES, default='G')
order = models.PositiveSmallIntegerField(default=1)
name = models.CharField(_('name'), max_length=100)
Expand All @@ -89,7 +89,7 @@ class Response(models.Model):
The response that was recorded in response to the corresponding
:class:`~httpproxy.models.Request`.
"""
request = models.OneToOneField(Request, verbose_name=_('request'))
request = models.OneToOneField(Request, verbose_name=_('request'), on_delete=models.CASCADE)
status = models.PositiveSmallIntegerField(default=200)
content_type = models.CharField(_('content type'), max_length=200)
content = models.TextField(_('content'))
Expand Down
76 changes: 38 additions & 38 deletions httpproxy/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import re

from django.http import HttpResponse
from django.utils.six.moves import urllib
from urllib import parse, request, error
from django.views.generic import View

from httpproxy.recorder import ProxyRecorder
Expand All @@ -28,7 +28,7 @@ class HttpProxy(View):
)
Using the above configuration (and assuming your Django project is server by
the Django development server on port 8000), a request to
the Django development server on port 8000), a req to
``http://localhost:8000/my-proxy/index.html`` is proxied to
``http://python.org/index.html``.
"""
Expand All @@ -51,7 +51,7 @@ class HttpProxy(View):
If the mode is set to ``play``, no requests will be forwarded to the remote
server.
In ``play`` mode, if the response (to the request being made) was previously
In ``play`` mode, if the response (to the req being made) was previously
recorded, the recorded response will be served. Otherwise, a custom
``Http404`` exception will be raised
(:class:`~httpproxy.exceptions.RequestNotRecorded`).
Expand All @@ -68,40 +68,40 @@ class HttpProxy(View):

_msg = 'Response body: \n%s'

def dispatch(self, request, url, *args, **kwargs):
def dispatch(self, req, url, *args, **kwargs):
self.url = url
self.original_request_path = request.path
request = self.normalize_request(request)
self.original_request_path = req.path
req = self.normalize_request(req)
if self.mode == 'play':
response = self.play(request)
response = self.play(req)
# TODO: avoid repetition, flow of logic could be improved
if self.rewrite:
response = self.rewrite_response(request, response)
response = self.rewrite_response(req, response)
return response

response = super(HttpProxy, self).dispatch(request, *args, **kwargs)
response = super(HttpProxy, self).dispatch(req, *args, **kwargs)
if self.mode == 'record':
self.record(response)
if self.rewrite:
response = self.rewrite_response(request, response)
response = self.rewrite_response(req, response)
return response

def normalize_request(self, request):
def normalize_request(self, req):
"""
Updates all path-related info in the original request object with the
Updates all path-related info in the original req 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.
This way, any further processing of the proxy'd req can just ignore
the url given to the proxy and use req.path safely instead.
"""
if not self.url.startswith('/'):
self.url = '/' + self.url
request.path = self.url
request.path_info = self.url
request.META['PATH_INFO'] = self.url
return request
req.path = self.url
req.path_info = self.url
req.META['PATH_INFO'] = self.url
return req

def rewrite_response(self, request, response):
def rewrite_response(self, req, response):
"""
Rewrites the response to fix references to resources loaded from HTML
files (images, etc.).
Expand All @@ -111,64 +111,64 @@ def rewrite_response(self, request, response):
"src", "href" and "action" attributes with a value starting with "/"
– your results may vary.
"""
proxy_root = self.original_request_path.rsplit(request.path, 1)[0]
proxy_root = self.original_request_path.rsplit(req.path, 1)[0]
response.content = REWRITE_REGEX.sub(r'\1{}/'.format(proxy_root),
response.content)
return response

def play(self, request):
def play(self, req):
"""
Plays back the response to a request, based on a previously recorded
request/response.
Plays back the response to a req, based on a previously recorded
req/response.
Delegates to :class:`~httpproxy.recorder.ProxyRecorder`.
"""
return self.get_recorder().playback(request)
return self.get_recorder().playback(req)

def record(self, response):
"""
Records the request being made and its response.
Records the req being made and its response.
Delegates to :class:`~httpproxy.recorder.ProxyRecorder`.
"""
self.get_recorder().record(self.request, response)
self.get_recorder().record(self.req, response)

def get_recorder(self):
url = urllib.parse(self.base_url)
url = parse(self.base_url)
return ProxyRecorder(domain=url.hostname, port=(url.port or 80))

def get(self, *args, **kwargs):
return self.get_response()

def post(self, request, *args, **kwargs):
def post(self, req, *args, **kwargs):
headers = {}
if request.META.get('CONTENT_TYPE'):
headers['Content-type'] = request.META.get('CONTENT_TYPE')
return self.get_response(body=request.body, headers=headers)
if req.META.get('CONTENT_TYPE'):
headers['Content-type'] = req.META.get('CONTENT_TYPE')
return self.get_response(body=req.body, headers=headers)

def get_full_url(self, url):
"""
Constructs the full URL to be requested.
"""
param_str = self.request.GET.urlencode()
param_str = self.req.GET.urlencode()
request_url = u'%s%s' % (self.base_url, url)
request_url += '?%s' % param_str if param_str else ''
return request_url

def create_request(self, url, body=None, headers={}):
request = urllib.request.Request(url, body, headers)
logger.info('%s %s' % (request.get_method(), request.get_full_url()))
return request
req = request.Request(url, body, headers)
logger.info('%s %s' % (req.get_method(), req.get_full_url()))
return req

def get_response(self, body=None, headers={}):
request_url = self.get_full_url(self.url)
request = self.create_request(request_url, body=body, headers=headers)
response = urllib.request.urlopen(request)
req = self.create_request(request_url, body=body, headers=headers)
response = request.urlopen(req)
try:
response_body = response.read()
status = response.getcode()
logger.debug(self._msg % response_body)
except urllib.error.HTTPError as e:
except error.HTTPError as e:
response_body = e.read()
logger.error(self._msg % response_body)
status = e.code
Expand Down

0 comments on commit 62b5cb8

Please sign in to comment.