Permalink
Browse files

merged updates from the community and added CHANGELOG and AUTHORS upd…

…ates
  • Loading branch information...
1 parent 26bb6a8 commit fad43351d848da815159837d0a5f548b1fd2ef0f @montylounge committed Jan 16, 2010
View
@@ -0,0 +1 @@
+*.pyc
View
13 AUTHORS
@@ -0,0 +1,13 @@
+
+Primary Authors:
+
+ * Kevin Fricovsky <montylounge>
+
+Contributors:
+
+ * acdha <Chris Adams>
+ * Pablo Marti <pmarti>
+ * Dan Fairs <danfairs>
+ * Oleg Dolya <grengojbo>
+ * Nagy Viktor <nagyv>
+
View
@@ -0,0 +1,21 @@
+
+01.15.09
+---------
+Added this CHANGELOG file.
+Updated AUTHORS for most of the additions below.
+Updated cache tag
+Updated pygments_tag
+Added templatetags/sugar_pagination.py
+Added templatetags/sugar_template_utils.py
+Added more tags to templatetags/text_tags.py
+Added templatetags/querystring_tags.py
+Added templatetags/in_list.py
+Added templatags/media.py
+Add /tests.py (still need to add more tests)
+Added views/json.py
+Added views/helpers.py
+Added views/decorators.py
+Added views/exceptions.py
+
+
+
View
@@ -1,66 +1,75 @@
-import re, md5
+import re
+
+try:
+ from hashlib import md5
+except ImportError:
+ import md5
+
+
from django.db.models.manager import Manager
from django.utils.encoding import smart_str
+
def clean_cache_key(key):
- '''Replace spaces with '-' and hash if length is greater than 250.'''
+ '''Replace spaces with '-' and hash if length is greater than 250.'''
- #logic below borrowed from http://richwklein.com/2009/08/04/improving-django-cache-part-ii/
- cache_key = re.sub(r'\s+', '-', key)
- cache_key = smart_str(cache_key)
+ #logic below borrowed from http://richwklein.com/2009/08/04/improving-django-cache-part-ii/
+ cache_key = re.sub(r'\s+', '-', key)
+ cache_key = smart_str(cache_key)
- if len(cache_key) > 250:
- cache_key = cache_key[:200] + '-' + md5.new(cache_key).hexdigest()
+ if len(cache_key) > 250:
+ m = md5()
+ m.update(cache_key)
+ cache_key = cache_key[:200] + '-' + m.hexdigest()
+
+ return cache_key
- return cache_key
-
def create_cache_key(klass, field=None, field_value=None):
- '''
- Helper to generate standard cache keys.
+ '''
+ Helper to generate standard cache keys.
Concepts borrowed from mmalone's django-caching:
http://github.com/mmalone/django-caching/blob/ef7dd47e9beff39496e6a28ae129bae1b5f9ed71/app/managers.py
- Required Arguments
- ------------------
- 'klass'
- Model or Manager
-
- 'field'
- string, the specific Model field name used to create a more
- specific cache key. If you specify a field, it is used for the
- lookup to grab the value.
-
- 'field_value'
- value, unique value used to generate a distinct key. Often
- this will be the ID, slug, name, etc.
-
- *Note: could be optimized/restricted to pk lookup only
-
- Returns
- -------
- 'key'
- The key name.
-
- Example
- --------
- >>from blog.models import Post
- >>slug_val = 'test-foo'
- >>mykey = create_cache_key(Post, 'slug', slug_val)
- >>obj = cache.get(mykey)
- '''
-
- key_model = "%s.%s.%s:%s"
- key = ''
-
- if field and field_value:
- if isinstance(klass, Manager):
- key = key_model % (klass.model._meta.app_label, klass.model._meta.module_name, field, field_value)
- else:
- key = key_model % (klass._meta.app_label, klass._meta.module_name, field, field_value)
-
- if key is '':
- raise Exception('Cache key cannot be empty.')
-
- return clean_cache_key(key)
-
+ Required Arguments
+ ------------------
+ 'klass'
+ Model or Manager
+
+ 'field'
+ string, the specific Model field name used to create a more
+ specific cache key. If you specify a field, it is used for the
+ lookup to grab the value.
+
+ 'field_value'
+ value, unique value used to generate a distinct key. Often
+ this will be the ID, slug, name, etc.
+
+ *Note: could be optimized/restricted to pk lookup only
+
+ Returns
+ -------
+ 'key'
+ The key name.
+
+ Example
+ --------
+ >> from blog.models import Post
+ >> slug_val = 'test-foo'
+ >> mykey = create_cache_key(Post, 'slug', slug_val)
+ >> obj = cache.get(mykey)
+ '''
+
+ key_model = "%s.%s.%s:%s"
+ key = ''
+
+ if field and field_value:
+ if isinstance(klass, Manager):
+ key = key_model % (klass.model._meta.app_label, klass.model._meta.module_name, field, field_value)
+ else:
+ key = key_model % (klass._meta.app_label, klass._meta.module_name, field, field_value)
+
+ if not key:
+ raise Exception('Cache key cannot be empty.')
+
+ return clean_cache_key(key)
@@ -0,0 +1,42 @@
+# -*- mode: python; coding: utf-8; -*-
+
+from django.template.context import Context
+from functools import wraps
+
+def private_context(f):
+ """
+ Simple decorator which avoids the need to a) copy-and-paste code to force
+ context variables into inclusion_tag templates and b) carefully avoid
+ inclusion tag variables conflicting with global variables.
+
+ Instead each inclusion tag will be called with a *copy* of the provided
+ context variable and its results will be merged in to avoid leaking into
+ the global context
+
+ Django's standard inclusion_tag doesn't include context variables by
+ default. When you add takes_context you are required to manually merge the
+ context variables into the dict which your tag returns, which tends to
+ result in wasteful code or accidentally leaking variables into the global
+ context with something like context.update() or name collisions.
+
+ This decorator allows your inclusion tag to remain simple and still have
+ safe access to the global context for things like MEDIA_URL:
+
+ @register.inclusion_tag('my_template')
+ @private_context
+ def my_tag(context, …):
+ return {"foo": 1, "bar": 2}
+
+ See:
+ http://www.djangosnippets.org/snippets/1687/
+
+ """
+
+ @wraps(f)
+ def private_context_wrapper(context, *args, **kwargs):
+ c = Context(context)
+ rc = f(c, *args, **kwargs)
+ c.update(rc)
+ return c
+
+ return private_context_wrapper
@@ -0,0 +1,14 @@
+'''
+From http://www.djangosnippets.org/snippets/177/#c196 by mikeivanov
+'''
+from django import template
+register = template.Library()
+
+@register.filter
+def in_list(value,arg):
+ '''
+ Usage
+ {% if value|in_list:list %}
+ {% endif %}
+ '''
+ return value in arg
@@ -0,0 +1,37 @@
+from django.template import Library, Node
+from django.template.loader import render_to_string
+from django.contrib.sites.models import Site
+from django.conf import settings
+import os, urlparse
+
+register = Library()
+
+def _absolute_url(url):
+ if url.startswith('http://') or url.startswith('https://'):
+ return url
+ domain = Site.objects.get_current().domain
+ return 'http://%s%s' % (domain, url)
+
+@register.simple_tag
+def media(filename, flags=''):
+ """
+ Autor: http://softwaremaniacs.org/blog/2009/03/22/media-tag/
+
+ {% load media %}
+ <link rel="stylesheet" href="{% media "css/style.css" %}">
+
+ {% media "css/style.css" %} <!-- ...style.css?123456789 -->
+ {% media "css/style.css" "no-timestamp" %} <!-- ...style.css -->
+ {% media "images/edit.png" "timestamp" %} <!-- ...edit.png?123456789 -->
+ {% media "images/edit.png" "absolute" %} <!-- http://example.com/media/edit.png -->
+ """
+ flags = set(f.strip() for f in flags.split(','))
+ url = urlparse.urljoin(settings.MEDIA_URL, filename)
+ if 'absolute' in flags:
+ url = _absolute_url(url)
+ if (filename.endswith('.css') or filename.endswith('.js')) and 'no-timestamp' not in flags or \
+ 'timestamp' in flags:
+ fullname = os.path.join(settings.MEDIA_ROOT, filename)
+ if os.path.exists(fullname):
+ url += '?%d' % os.path.getmtime(fullname)
+ return url
@@ -1,42 +1,46 @@
-from django import template
-import re
-import pygments
-
-register = template.Library()
-regex = re.compile(r'<code>(.*?)</code>', re.DOTALL)
-
-@register.filter(name='pygmentize')
-def pygmentize(value):
+import re
+import pygments
+from django import template
+from pygments import lexers
+from pygments import formatters
+from BeautifulSoup import BeautifulSoup
+
+register = template.Library()
+regex = re.compile(r'<code(.*?)>(.*?)</code>', re.DOTALL)
+
+@register.filter(name='pygmentize')
+def pygmentize(value):
'''
- Finds all <code></code> blocks in a text block and replaces it with
- pygments-highlighted html semantics. It tries to guess the format of the
- input, and it falls back to Python highlighting if it can't decide. This
- is useful for highlighting code snippets on a blog, for instance.
+ Finds all <code class="python"></code> blocks in a text block and replaces it with
+ pygments-highlighted html semantics. It relies that you provide the format of the
+ input as class attribute.
- Source: http://www.djangosnippets.org/snippets/25/
+ Inspiration: http://www.djangosnippets.org/snippets/25/
+ Updated by: Samualy Clay
Example
-------
{% post.body|pygmentize %}
'''
-
- try:
- last_end = 0
- to_return = ''
- found = 0
- for match_obj in regex.finditer(value):
- code_string = match_obj.group(1)
- try:
- lexer = pygments.lexers.guess_lexer(code_string)
- except ValueError:
- lexer = pygments.lexers.PythonLexer()
- pygmented_string = pygments.highlight(code_string, lexer, pygments.formatters.HtmlFormatter())
- to_return = to_return + value[last_end:match_obj.start(1)] + pygmented_string
- last_end = match_obj.end(1)
- found = found + 1
- to_return = to_return + value[last_end:]
- return to_return
- except:
- return value
+ last_end = 0
+ to_return = ''
+ found = 0
+ for match_obj in regex.finditer(value):
+ code_class = match_obj.group(1)
+ code_string = match_obj.group(2)
+ if code_class.find('class'):
+ language = re.split(r'"|\'', code_class)[1]
@blueyed

blueyed Aug 19, 2010

This does not work for the following:
class=""
class="python anotherclass"

You may want to split by '"|\'| ' or just \b instead, and also only the part after "class=" and before any \w+= maybe.

+ lexer = lexers.get_lexer_by_name(language)
+ else:
+ try:
+ lexer = lexers.guess_lexer(str(code))
+ except ValueError:
+ lexer = lexers.PythonLexer()
+ pygmented_string = pygments.highlight(code_string, lexer, formatters.HtmlFormatter())
+ to_return = to_return + value[last_end:match_obj.start(0)] + pygmented_string
+ last_end = match_obj.end(2)
+ found = found + 1
+ to_return = to_return + value[last_end:]
+ return to_return
Oops, something went wrong.

0 comments on commit fad4335

Please sign in to comment.