Skip to content

Commit

Permalink
Adding request Handler support.
Browse files Browse the repository at this point in the history
  • Loading branch information
jkeyes committed Mar 7, 2016
1 parent 73127d6 commit 5d1f334
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 3 deletions.
12 changes: 12 additions & 0 deletions methodview/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ def __init__(self, allowed=None):
allowed = ALLOWED_METHODS
self._allowed_methods = [a.upper() for a in allowed]
self._method_supported = False
self._handlers = []
super(MethodView, self).__init__()

def add_handler(self, request):
"""Add a handler."""
self._handlers.append(request)

def _get_handler(self, http_method, accept):
self._methods = inspect.getmembers(self, inspect.ismethod)
Expand Down Expand Up @@ -124,6 +130,12 @@ def __call__(self, request, *args, **kwargs):

accept = self._get_accept(request)

# call any handlers
for h in self._handlers:
resp = h.handle(request, *args, **kwargs)
if resp:
return resp

# authorize the call if possible
try:
self._authorize(request, accept)
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@

setup(
name="django-methodview",
version='0.2',
version='0.3',
description="Class based HTTP method view",
long_description=open('README').read(),
long_description=open('README.rst').read(),
author="John Keyes",
author_email="john@keyes.ie",
license="MIT License",
Expand Down
37 changes: 36 additions & 1 deletion tests/unit/test_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,43 @@ class TestView(MethodView):

def test_no_get(self):
"""Test a GET request."""
view = MethodRequestTest.TestView()
view = MethodNotImplementedTest.TestView()

request = create_request('GET')
res = view(request)
self.assertEqual(501, res.status_code)


class HandlerTest(TestCase):
"""Test for checking _method support."""

class DebugHandler(object):
"""Test Handler."""

def __init__(self, *args, **kwargs):
"""Initialize the handler."""
print("BOO" * 10)
super(HandlerTest.DebugHandler, self).__init__(*args, **kwargs)
self.add_handler(self)

def handle(self, request):
"""Handle the request."""
request.GET['DEBUG_HANDLER'] = True

class TestView(MethodView, DebugHandler):
"""Test View."""

def get(self, request):
"""Return 'GET'."""
return HttpResponse('GET')

def test_get(self):
"""Test a GET."""
view = HandlerTest.TestView()

request = create_request('GET')
self.assertFalse('DEBUG_HANDLER' in request.GET)
res = view(request)
self.assertEqual(200, res.status_code)
self.assertEqual(b'GET', res.content)
self.assertTrue('DEBUG_HANDLER' in request.GET)

0 comments on commit 5d1f334

Please sign in to comment.