aboutsummaryrefslogtreecommitdiffstats
path: root/examples/pygments_api
diff options
context:
space:
mode:
authorTom Christie2011-06-02 12:58:10 +0100
committerTom Christie2011-06-02 12:58:10 +0100
commitb50492853f537a2473bb0a9eea86c8b0ed6b8824 (patch)
treed289d39aacf187a8a0696a4c1c863aabe1472c3a /examples/pygments_api
parent7ee9adbe5c03c29cd4a894dd476548f7fe73b5e4 (diff)
parentfc1640de75511006e89f033c9270ec91a9f1e4d4 (diff)
downloaddjango-rest-framework-b50492853f537a2473bb0a9eea86c8b0ed6b8824.tar.bz2
pull in -dev as 0.2.0
Diffstat (limited to 'examples/pygments_api')
-rw-r--r--examples/pygments_api/tests.py3
-rw-r--r--examples/pygments_api/views.py96
2 files changed, 64 insertions, 35 deletions
diff --git a/examples/pygments_api/tests.py b/examples/pygments_api/tests.py
index 3bdc2ec5..6eb69da5 100644
--- a/examples/pygments_api/tests.py
+++ b/examples/pygments_api/tests.py
@@ -1,10 +1,13 @@
from django.test import TestCase
from django.utils import simplejson as json
+
from djangorestframework.compat import RequestFactory
+
from pygments_api import views
import tempfile, shutil
+
class TestPygmentsExample(TestCase):
def setUp(self):
diff --git a/examples/pygments_api/views.py b/examples/pygments_api/views.py
index 377761b1..76647107 100644
--- a/examples/pygments_api/views.py
+++ b/examples/pygments_api/views.py
@@ -2,9 +2,10 @@ from __future__ import with_statement # for python 2.5
from django.conf import settings
from django.core.urlresolvers import reverse
-from djangorestframework.resource import Resource
+from djangorestframework.resources import FormResource
from djangorestframework.response import Response
-from djangorestframework.emitters import BaseEmitter
+from djangorestframework.renderers import BaseRenderer
+from djangorestframework.views import View
from djangorestframework import status
from pygments.formatters import HtmlFormatter
@@ -17,73 +18,98 @@ import os
import uuid
import operator
-# We need somewhere to store the code that we highlight
+# We need somewhere to store the code snippets that we highlight
HIGHLIGHTED_CODE_DIR = os.path.join(settings.MEDIA_ROOT, 'pygments')
MAX_FILES = 10
+
def list_dir_sorted_by_ctime(dir):
- """Return a list of files sorted by creation time"""
+ """
+ Return a list of files sorted by creation time
+ """
filepaths = [os.path.join(dir, file) for file in os.listdir(dir) if not file.startswith('.')]
- return [item[0] for item in sorted([(path, os.path.getctime(path)) for path in filepaths],
- key=operator.itemgetter(1), reverse=False)]
+ return [item[0] for item in sorted( [(path, os.path.getctime(path)) for path in filepaths],
+ key=operator.itemgetter(1), reverse=False) ]
+
def remove_oldest_files(dir, max_files):
- """Remove the oldest files in a directory 'dir', leaving at most 'max_files' remaining.
- We use this to limit the number of resources in the sandbox."""
+ """
+ Remove the oldest files in a directory 'dir', leaving at most 'max_files' remaining.
+ We use this to limit the number of resources in the sandbox.
+ """
[os.remove(path) for path in list_dir_sorted_by_ctime(dir)[max_files:]]
-class HTMLEmitter(BaseEmitter):
- """Basic emitter which just returns the content without any further serialization."""
+class HTMLRenderer(BaseRenderer):
+ """
+ Basic renderer which just returns the content without any further serialization.
+ """
media_type = 'text/html'
-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."""
+
+class PygmentsFormResource(FormResource):
+ """
+ """
form = PygmentsForm
- allowed_methods = anon_allowed_methods = ('GET', 'POST',)
- def get(self, request, auth):
- """Return a list of all currently existing snippets."""
+
+class PygmentsRoot(View):
+ """
+ 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.
+ """
+ resource = PygmentsFormResource
+
+ 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):
- """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."""
+ 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)
return Response(status.HTTP_201_CREATED, headers={'Location': reverse('pygments-instance', args=[unique_id])})
-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,)
+class PygmentsInstance(View):
+ """
+ Simply return the stored highlighted HTML file with the correct mime type.
+ This Resource only renders HTML and uses a standard HTML renderer rather than the renderers.DocumentingHTMLRenderer class.
+ """
+ renderers = (HTMLRenderer,)
- def get(self, request, auth, unique_id):
- """Return the highlighted snippet."""
+ 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):
- """Delete the highlighted snippet."""
+ 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)