From 028851bfa1ee44b8e92808b18d32278d4a473cc8 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 27 Apr 2011 18:07:28 +0100 Subject: [PATCH] Fix up tests and examples after refactoring --- djangorestframework/authenticators.py | 8 ++++++- djangorestframework/modelresource.py | 4 ++-- djangorestframework/resource.py | 8 +++++-- djangorestframework/tests/authentication.py | 2 ++ examples/blogpost/views.py | 4 ---- examples/mixin/urls.py | 5 +++-- examples/modelresourceexample/views.py | 2 -- examples/pygments_api/views.py | 24 ++++++++++----------- examples/resourceexample/views.py | 10 ++++----- examples/sandbox/views.py | 3 +-- 10 files changed, 36 insertions(+), 34 deletions(-) diff --git a/djangorestframework/authenticators.py b/djangorestframework/authenticators.py index e6f51dd57..19181b7d6 100644 --- a/djangorestframework/authenticators.py +++ b/djangorestframework/authenticators.py @@ -73,4 +73,10 @@ class UserLoggedInAuthenticator(BaseAuthenticator): if resp is None: # csrf passed return request.user return None - + + +#class DigestAuthentication(BaseAuthentication): +# pass +# +#class OAuthAuthentication(BaseAuthentication): +# pass diff --git a/djangorestframework/modelresource.py b/djangorestframework/modelresource.py index a91c79ee6..1afd7fa03 100644 --- a/djangorestframework/modelresource.py +++ b/djangorestframework/modelresource.py @@ -416,7 +416,7 @@ class RootModelResource(ModelResource): queryset = self.queryset if self.queryset else self.model.objects.all() return queryset.filter(**kwargs) - put = delete = http_method_not_allowed + put = delete = None class QueryModelResource(ModelResource): """Resource with default operations for list. @@ -428,4 +428,4 @@ class QueryModelResource(ModelResource): queryset = self.queryset if self.queryset else self.model.objects.all() return queryset.filer(**kwargs) - post = put = delete = http_method_not_allowed \ No newline at end of file + post = put = delete = None \ No newline at end of file diff --git a/djangorestframework/resource.py b/djangorestframework/resource.py index 65aa09c64..fbf51cfcb 100644 --- a/djangorestframework/resource.py +++ b/djangorestframework/resource.py @@ -41,7 +41,7 @@ class Resource(RequestMixin, ResponseMixin, AuthMixin, View): authenticators.BasicAuthenticator ) # List of all permissions required to access the resource - permissions = ( permissions.DeleteMePermission, ) + permissions = () # Optional form for input validation and presentation of HTML formatted responses. form = None @@ -54,7 +54,7 @@ class Resource(RequestMixin, ResponseMixin, AuthMixin, View): @property def allowed_methods(self): - return [method.upper() for method in self.http_method_names if hasattr(self, method)] + return [method.upper() for method in self.http_method_names if getattr(self, method, None)] def http_method_not_allowed(self, request, *args, **kwargs): """Return an HTTP 405 error if an operation is called which does not have a handler method.""" @@ -96,6 +96,9 @@ class Resource(RequestMixin, ResponseMixin, AuthMixin, View): # Get the appropriate handler method if self.method.lower() in self.http_method_names: handler = getattr(self, self.method.lower(), self.http_method_not_allowed) + # If a previously defined method has been disabled + if handler is None: + handler = self.http_method_not_allowed else: handler = self.http_method_not_allowed @@ -125,3 +128,4 @@ class Resource(RequestMixin, ResponseMixin, AuthMixin, View): return self.emit(response) + diff --git a/djangorestframework/tests/authentication.py b/djangorestframework/tests/authentication.py index 723005069..f2c249a6d 100644 --- a/djangorestframework/tests/authentication.py +++ b/djangorestframework/tests/authentication.py @@ -7,11 +7,13 @@ from django.utils import simplejson as json from djangorestframework.compat import RequestFactory from djangorestframework.resource import Resource +from djangorestframework import permissions import base64 class MockResource(Resource): + permissions = ( permissions.IsAuthenticated, ) def post(self, request): return {'a':1, 'b':2, 'c':3} diff --git a/examples/blogpost/views.py b/examples/blogpost/views.py index 59a3fb9ff..9e07aa8ab 100644 --- a/examples/blogpost/views.py +++ b/examples/blogpost/views.py @@ -8,25 +8,21 @@ MAX_POSTS = 10 class BlogPosts(RootModelResource): """A resource with which lists all existing blog posts and creates new blog posts.""" - anon_allowed_methods = allowed_methods = ('GET', 'POST',) model = models.BlogPost fields = BLOG_POST_FIELDS class BlogPostInstance(ModelResource): """A resource which represents a single blog post.""" - anon_allowed_methods = allowed_methods = ('GET', 'PUT', 'DELETE') model = models.BlogPost fields = BLOG_POST_FIELDS class Comments(RootModelResource): """A resource which lists all existing comments for a given blog post, and creates new blog comments for a given blog post.""" - anon_allowed_methods = allowed_methods = ('GET', 'POST',) model = models.Comment fields = COMMENT_FIELDS class CommentInstance(ModelResource): """A resource which represents a single comment.""" - anon_allowed_methods = allowed_methods = ('GET', 'PUT', 'DELETE') model = models.Comment fields = COMMENT_FIELDS diff --git a/examples/mixin/urls.py b/examples/mixin/urls.py index 050092845..96b630e38 100644 --- a/examples/mixin/urls.py +++ b/examples/mixin/urls.py @@ -1,12 +1,13 @@ from djangorestframework.compat import View # Use Django 1.3's django.views.generic.View, or fall back to a clone of that if Django < 1.3 -from djangorestframework.emitters import EmitterMixin, DEFAULT_EMITTERS +from djangorestframework.mixins import ResponseMixin +from djangorestframework.emitters import DEFAULT_EMITTERS from djangorestframework.response import Response from django.conf.urls.defaults import patterns, url from django.core.urlresolvers import reverse -class ExampleView(EmitterMixin, View): +class ExampleView(ResponseMixin, View): """An example view using Django 1.3's class based views. Uses djangorestframework's EmitterMixin to provide support for multiple output formats.""" emitters = DEFAULT_EMITTERS diff --git a/examples/modelresourceexample/views.py b/examples/modelresourceexample/views.py index e912c019d..07f50b653 100644 --- a/examples/modelresourceexample/views.py +++ b/examples/modelresourceexample/views.py @@ -7,12 +7,10 @@ class MyModelRootResource(RootModelResource): """A create/list resource for MyModel. Available for both authenticated and anonymous access for the purposes of the sandbox.""" model = MyModel - allowed_methods = anon_allowed_methods = ('GET', 'POST') fields = FIELDS class MyModelResource(ModelResource): """A read/update/delete resource for MyModel. Available for both authenticated and anonymous access for the purposes of the sandbox.""" model = MyModel - allowed_methods = anon_allowed_methods = ('GET', 'PUT', 'DELETE') fields = FIELDS diff --git a/examples/pygments_api/views.py b/examples/pygments_api/views.py index 6fb9217aa..f1a89702f 100644 --- a/examples/pygments_api/views.py +++ b/examples/pygments_api/views.py @@ -41,26 +41,25 @@ class PygmentsRoot(Resource): """This example demonstrates a simple RESTful Web API aound the awesome pygments library. This top level resource is used to create highlighted code snippets, and to list all the existing code snippets.""" form = PygmentsForm - allowed_methods = anon_allowed_methods = ('GET', 'POST',) - def get(self, request, auth): + def get(self, request): """Return a list of all currently existing snippets.""" unique_ids = [os.path.split(f)[1] for f in list_dir_sorted_by_ctime(HIGHLIGHTED_CODE_DIR)] return [reverse('pygments-instance', args=[unique_id]) for unique_id in unique_ids] - def post(self, request, auth, content): + def post(self, request): """Create a new highlighed snippet and return it's location. For the purposes of the sandbox example, also ensure we delete the oldest snippets if we have > MAX_FILES.""" unique_id = str(uuid.uuid1()) pathname = os.path.join(HIGHLIGHTED_CODE_DIR, unique_id) - lexer = get_lexer_by_name(content['lexer']) - linenos = 'table' if content['linenos'] else False - options = {'title': content['title']} if content['title'] else {} - formatter = HtmlFormatter(style=content['style'], linenos=linenos, full=True, **options) + lexer = get_lexer_by_name(self.CONTENT['lexer']) + linenos = 'table' if self.CONTENT['linenos'] else False + options = {'title': self.CONTENT['title']} if self.CONTENT['title'] else {} + formatter = HtmlFormatter(style=self.CONTENT['style'], linenos=linenos, full=True, **options) with open(pathname, 'w') as outfile: - highlight(content['code'], lexer, formatter, outfile) + highlight(self.CONTENT['code'], lexer, formatter, outfile) remove_oldest_files(HIGHLIGHTED_CODE_DIR, MAX_FILES) @@ -70,20 +69,19 @@ class PygmentsRoot(Resource): class PygmentsInstance(Resource): """Simply return the stored highlighted HTML file with the correct mime type. This Resource only emits HTML and uses a standard HTML emitter rather than the emitters.DocumentingHTMLEmitter class.""" - allowed_methods = anon_allowed_methods = ('GET',) emitters = (HTMLEmitter,) - def get(self, request, auth, unique_id): + def get(self, request, unique_id): """Return the highlighted snippet.""" pathname = os.path.join(HIGHLIGHTED_CODE_DIR, unique_id) if not os.path.exists(pathname): - return Resource(status.HTTP_404_NOT_FOUND) + return Response(status.HTTP_404_NOT_FOUND) return open(pathname, 'r').read() - def delete(self, request, auth, unique_id): + def delete(self, request, unique_id): """Delete the highlighted snippet.""" pathname = os.path.join(HIGHLIGHTED_CODE_DIR, unique_id) if not os.path.exists(pathname): - return Resource(status.HTTP_404_NOT_FOUND) + return Response(status.HTTP_404_NOT_FOUND) return os.remove(pathname) diff --git a/examples/resourceexample/views.py b/examples/resourceexample/views.py index 41d2e5c5c..911fd467b 100644 --- a/examples/resourceexample/views.py +++ b/examples/resourceexample/views.py @@ -8,24 +8,22 @@ from resourceexample.forms import MyForm class ExampleResource(Resource): """A basic read-only resource that points to 3 other resources.""" - allowed_methods = anon_allowed_methods = ('GET',) - def get(self, request, auth): + def get(self, request): return {"Some other resources": [reverse('another-example-resource', kwargs={'num':num}) for num in range(3)]} class AnotherExampleResource(Resource): """A basic GET-able/POST-able resource.""" - allowed_methods = anon_allowed_methods = ('GET', 'POST') form = MyForm # Optional form validation on input (Applies in this case the POST method, but can also apply to PUT) - def get(self, request, auth, num): + def get(self, request, num): """Handle GET requests""" if int(num) > 2: return Response(status.HTTP_404_NOT_FOUND) return "GET request to AnotherExampleResource %s" % num - def post(self, request, auth, content, num): + def post(self, request, num): """Handle POST requests""" if int(num) > 2: return Response(status.HTTP_404_NOT_FOUND) - return "POST request to AnotherExampleResource %s, with content: %s" % (num, repr(content)) + return "POST request to AnotherExampleResource %s, with content: %s" % (num, repr(self.CONTENT)) diff --git a/examples/sandbox/views.py b/examples/sandbox/views.py index 561bdb1d7..5b84e8e42 100644 --- a/examples/sandbox/views.py +++ b/examples/sandbox/views.py @@ -24,9 +24,8 @@ class Sandbox(Resource): 6. A blog posts and comments API. Please feel free to browse, create, edit and delete the resources in these examples.""" - allowed_methods = anon_allowed_methods = ('GET',) - def get(self, request, auth): + def get(self, request): return [{'name': 'Simple Resource example', 'url': reverse('example-resource')}, {'name': 'Simple ModelResource example', 'url': reverse('my-model-root-resource')}, {'name': 'Simple Mixin-only example', 'url': reverse('mixin-view')},