diff options
Diffstat (limited to 'examples/pygments_api')
| -rw-r--r-- | examples/pygments_api/__init__.py | 0 | ||||
| -rw-r--r-- | examples/pygments_api/forms.py | 27 | ||||
| -rw-r--r-- | examples/pygments_api/models.py | 1 | ||||
| -rw-r--r-- | examples/pygments_api/tests.py | 46 | ||||
| -rw-r--r-- | examples/pygments_api/urls.py | 7 | ||||
| -rw-r--r-- | examples/pygments_api/views.py | 118 |
6 files changed, 0 insertions, 199 deletions
diff --git a/examples/pygments_api/__init__.py b/examples/pygments_api/__init__.py deleted file mode 100644 index e69de29b..00000000 --- a/examples/pygments_api/__init__.py +++ /dev/null diff --git a/examples/pygments_api/forms.py b/examples/pygments_api/forms.py deleted file mode 100644 index cc147740..00000000 --- a/examples/pygments_api/forms.py +++ /dev/null @@ -1,27 +0,0 @@ -from django import forms - -from pygments.lexers import get_all_lexers -from pygments.styles import get_all_styles - -LEXER_CHOICES = sorted([(item[1][0], item[0]) for item in get_all_lexers()]) -STYLE_CHOICES = sorted((item, item) for item in list(get_all_styles())) - - -class PygmentsForm(forms.Form): - """A simple form with some of the most important pygments settings. - The code to be highlighted can be specified either in a text field, or by URL. - We do some additional form validation to ensure clients see helpful error responses.""" - - code = forms.CharField(widget=forms.Textarea, - label='Code Text', - max_length=1000000, - help_text='(Copy and paste the code text here.)') - title = forms.CharField(required=False, - help_text='(Optional)', - max_length=100) - linenos = forms.BooleanField(label='Show Line Numbers', - required=False) - lexer = forms.ChoiceField(choices=LEXER_CHOICES, - initial='python') - style = forms.ChoiceField(choices=STYLE_CHOICES, - initial='friendly') diff --git a/examples/pygments_api/models.py b/examples/pygments_api/models.py deleted file mode 100644 index 402a813e..00000000 --- a/examples/pygments_api/models.py +++ /dev/null @@ -1 +0,0 @@ -#We need models.py otherwise the test framework complains (http://code.djangoproject.com/ticket/7198)
diff --git a/examples/pygments_api/tests.py b/examples/pygments_api/tests.py deleted file mode 100644 index b728c3c2..00000000 --- a/examples/pygments_api/tests.py +++ /dev/null @@ -1,46 +0,0 @@ -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):
- self.factory = RequestFactory()
- self.temp_dir = tempfile.mkdtemp()
- views.HIGHLIGHTED_CODE_DIR = self.temp_dir
-
- def tearDown(self):
- try:
- shutil.rmtree(self.temp_dir)
- except Exception:
- pass
-
- def test_get_to_root(self):
- '''Just do a get on the base url'''
- request = self.factory.get('/pygments')
- view = views.PygmentsRoot.as_view()
- response = view(request)
- self.assertEqual(response.status_code, 200)
-
- def test_snippets_datetime_sorted(self):
- '''Pygments examples should be datetime sorted'''
- locations = []
- for snippet in 'abcdefghij': # String length must not exceed views.MAX_FILES, otherwise test fails
- form_data = {'code': '%s' % snippet, 'style':'friendly', 'lexer':'python'}
- request = self.factory.post('/pygments', data=form_data)
- view = views.PygmentsRoot.as_view()
- response = view(request)
- locations.append(response.items()[2][1])
- import time
- time.sleep(.1)
- request = self.factory.get('/pygments')
- view = views.PygmentsRoot.as_view()
- response = view(request)
- response_locations = json.loads(response.content)
- self.assertEquals(locations, response_locations)
diff --git a/examples/pygments_api/urls.py b/examples/pygments_api/urls.py deleted file mode 100644 index e0d44ece..00000000 --- a/examples/pygments_api/urls.py +++ /dev/null @@ -1,7 +0,0 @@ -from django.conf.urls.defaults import patterns, url -from pygments_api.views import PygmentsRoot, PygmentsInstance - -urlpatterns = patterns('', - url(r'^$', PygmentsRoot.as_view(), name='pygments-root'), - url(r'^([a-zA-Z0-9-]+)/$', PygmentsInstance.as_view(), name='pygments-instance'), -) diff --git a/examples/pygments_api/views.py b/examples/pygments_api/views.py deleted file mode 100644 index a3812ef4..00000000 --- a/examples/pygments_api/views.py +++ /dev/null @@ -1,118 +0,0 @@ -from __future__ import with_statement # for python 2.5 -from django.conf import settings - -from djangorestframework.response import Response -from djangorestframework.renderers import BaseRenderer -from djangorestframework.reverse import reverse -from djangorestframework.views import View -from djangorestframework import status - -from pygments.formatters import HtmlFormatter -from pygments.lexers import get_lexer_by_name -from pygments import highlight - -from forms import PygmentsForm - -import os -import uuid -import operator - -# We need somewhere to store the code snippets that we highlight -HIGHLIGHTED_CODE_DIR = os.path.join(settings.MEDIA_ROOT, 'pygments') -MAX_FILES = 10 - -if not os.path.exists(HIGHLIGHTED_CODE_DIR): - os.makedirs(HIGHLIGHTED_CODE_DIR) - - -def list_dir_sorted_by_ctime(dir): - """ - 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('.')] - ctimes = [(path, os.path.getctime(path)) for path in filepaths] - ctimes = sorted(ctimes, key=operator.itemgetter(1), reverse=False) - return [filepath for filepath, ctime in ctimes] - - -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. - """ - [os.remove(path) for path in list_dir_sorted_by_ctime(dir)[max_files:]] - - -class HTMLRenderer(BaseRenderer): - """ - Basic renderer which just returns the content without any further serialization. - """ - media_type = 'text/html' - - -class PygmentsRoot(View): - """ - This example demonstrates a simple RESTful Web API around 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 - - 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)] - urls = [reverse('pygments-instance', args=[unique_id], request=request) - for unique_id in unique_ids] - return Response(urls) - - 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(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(self.CONTENT['code'], lexer, formatter, outfile) - - remove_oldest_files(HIGHLIGHTED_CODE_DIR, MAX_FILES) - - location = reverse('pygments-instance', args=[unique_id], request=request) - return Response(status=status.HTTP_201_CREATED, headers={'Location': location}) - - -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, unique_id): - """ - Return the highlighted snippet. - """ - pathname = os.path.join(HIGHLIGHTED_CODE_DIR, unique_id) - if not os.path.exists(pathname): - return Response(status=status.HTTP_404_NOT_FOUND) - return Response(open(pathname, 'r').read()) - - 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 Response(status=status.HTTP_404_NOT_FOUND) - os.remove(pathname) - return Response() |
