Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

send django queries to OutputDebugString (Win32)

Modify django/db/backends/util.py as follows:

import win32api

class CursorDebugWrapper(object):
    def __init__(self, cursor, db):
        self.cursor = cursor
        self.db = db # Instance of a BaseDatabaseWrapper subclass

    def debug_trace(self,category,message):
        win32api.OutputDebugString('|django              |%s|%s\n' % (category,message))

    def trace_entry (self, sql, elapsed): 
        self.debug_trace('Q',sql)
        if elapsed >= 0.01:
            self.debug_trace(' ','elapsed: %.3f' % elapsed)

    def execute(self, sql, params=()):
        start = time()
        try:
            return self.cursor.execute(sql, params)
        finally:
            stop = time()
            sql = self.db.ops.last_executed_query(self.cursor, sql, params)
            self.db.queries.append({
                'sql': sql,
                'time': "%.3f" % (stop - start),
            })
            self.trace_entry(sql, stop - start) 

    def executemany(self, sql, param_list):
        start = time()
        try:
            return self.cursor.executemany(sql, param_list)
        finally:
            stop = time()
            self.db.queries.append({
                'sql': '%s times: %s' % (len(param_list), sql),
                'time': "%.3f" % (stop - start),
            })
            self.trace_entry(sql, stop - start) 


Generating Taconite command documents

// description of your code here
Hello,

This is a port of a php class used to generate XML taconite command documents, useful for (very) easy and powerful ajaxy stuff, if you don't know what that is just check it there in french : http://www.desfrenes.com/playground/taconite/ or there in english : http://www.malsup.com/jquery/taconite/.

Basically what it does is generate an XML document that is later processed by a javascript plugin which executes a serie of DOM modifications.

About the code, I'm a Django beginner as well as a Python beginner so kind advices are welcome.

Cheers.
# usage:
#
# t = Taconite()
#
# t.append("#toto","<label>test</label>")
# t.remove("#tutu")
# t.js('alert("hello world");')
# t.toggleClass('blue','body')
# t.css("body","background-color","white")
# [...]
# print t.toprettyxml()

import xml.dom.minidom as dom

class Taconite(dom.Document):
    def __init__(self):
        dom.Document.__init__(self)
        taconite = self.createElement("taconite")
        self.appendChild(taconite)

    def __str__(self):
        return self.toxml(encoding="utf-8")
    
    def camelizeCssProperty(self,property):
        words = property.split('-')
        camelized = words[0].lower()
        for word in words[1:] :
            camelized = camelized + word[0].upper() + word[1:]
        return camelized
    
    def js(self,script):
        command = self.createElement("eval")
        js = self.createTextNode(script)
        command.appendChild(js)
        self.childNodes[0].appendChild(command)
    
    def changeContentCommand(self,method,selector,content):
        html_dom = dom.parseString(content)
        command = self.createElement(method)
        command.setAttribute("select",selector)
        command.appendChild(html_dom.childNodes[0])
        self.childNodes[0].appendChild(command)
    
    def changeStateCommand(self,action,selector):
        command = self.createElement(action)
        command.setAttribute("select",selector)
        self.childNodes[0].appendChild(command)
    
    def CssCommand(self,action,css_class,selector):
        command1 = self.createElement(action)
        command1.setAttribute("select",selector)
        command1.setAttribute("arg1",css_class)
        command2 = self.createElement(action)
        command2.setAttribute("select",selector)
        command2.setAttribute("value",css_class)
        self.childNodes[0].appendChild(command1)
        self.childNodes[0].appendChild(command2)
    
    def addClass(self,css_class,selector):
        self.CssCommand("addClass",css_class,selector)

    def removeClass(self,css_class,selector):
        self.CssCommand("remove",css_class,selector)

    def toggleClass(self,css_class,selector):
        self.CssCommand("toggleClass",css_class,selector)
    
    def append(self,selector,content):
        self.changeContentCommand("append",selector,content)
    
    def prepend(self,selector,content):
        self.changeContentCommand("prepend",selector,content)
        
    
    def before(self,selector,content):
        self.changeContentCommand("before",selector,content)
        
    
    def after(self,selector,content):
        self.changeContentCommand("after",selector,content)
    
    def wrap(self,selector,content):
        self.changeContentCommand("wrap",selector,content)
    
    def replace(self,selector,content):
        self.changeContentCommand("replace",selector,content)
    
    def replaceContent(self,selector,content):
        self.changeContentCommand("replaceContent",selector,content)
    
    def remove(self,selector):
        self.changeStateCommand("remove",selector)
    
    def show(self,selector):
        self.changeStateCommand("show",selector)
    
    def hide(self,selector):
        self.changeStateCommand("hide",selector)
    
    def removeContent(self,selector):
        self.changeStateCommand("empty",selector)
    
    def css(self,selector,property,value):
        command = self.createElement("css")
        command.setAttribute("select",selector)
        command.setAttribute("name",self.camelizeCssProperty(property))
        command.setAttribute("value",value)
        self.childNodes[0].appendChild(command)

Bootstrap Django templates out-of-framework

This is the quickest way I've found to bootstrap Django templates without using the entire framework. This is suited for "plain-python" apps without using all the Django types. You'll probably want to cache the Template returns for each given name, but here's the basics.

# Kick off django config machinery first
from django.conf import settings
settings.configure(TEMPLATE_DIRS=("/whatever/templates",))

import django.template
import django.template.loader


def render(name, *values):
    ctx = django.template.Context()
    for d in values:
        ctx.push()
        ctx.update(d)

    t = django.template.loader.get_template(name)
    return t.render(ctx)

print render('layout.tmpl', dict(title='User'), dict(name='Bob', gender='M'))

Multi-lingual model in Django used for internationalizing content

The approach taken here gives each object (in this case a wiki Page) a language and a translation_of field. These two fields can be added to any model that wants to add content translations.

Pages are created in a default language. To translate a page, you create a new page and set the translation_of field to the page in the default language that you are translating.

A set of helper methods allow you to get the root version of the page (in the default language), all translations of a page, or a specific translation. These are useful for adding translation links.

LANGUAGE_CHOICES = (
    ('en', 'English'),
    ('nl', 'Nederlands')
)

class Page(models.Model):
    language = models.CharField(maxlength=2, choices=LANGUAGE_CHOICES)
    title = models.CharField(maxlength=60)
    path = models.SlugField(prepopulate_from=('title',))
    translation_of = models.ForeignKey('self', related_name='translation_set', limit_choices_to = {'language' : settings.DEFAULT_LANGUAGE}, blank=True, null=True, help_text="Select which page this is a translation of. Don't set this for english pages.", validator_list = [local_models.validate_translation_of])
    content = models.TextField(blank=True)

    def get_root_translation(self):
        """Returns the root translation for this page.
        
        This page will be in the settings.DEFAULT_LANGUAGE."""
        if self.translation_of is None:
            return self
        else:
            return self.translation_of

    def get_translations(self):
        """Return all of the translations for this page."""
        # If I am the root translation, just return all of my translations.
        if self.translation_of is None:
            return self.translation_set.all()
        else:
            # If I am not the root, return the root translations, plus all of its
            # translations, minus myself.
            return Page.objects.filter(
                models.Q(id=self.translation_of.id) | 
                models.Q(translation_of=self.translation_of.id)).exclude(pk=self.id)
                
    def get_translation(self, language):
        """Return a specific translation of this page."""
        if self.language == language:
            return self
        # If I am the root translation, search for translations of me in the given language
        elif self.translation_of is None:
            try:
                return Page.objects.get(translation_of=self.id, language=language)
            except Page.DoesNotExist:
                return None
        # Find the root page and the specific translation
        else:
            # If am not the root, find the root page with the given language,
            # otherwise find the page that is a translation of me in the given language
            return Page.objects.filter(
                models.Q(id=self.translation_of.id) |
                models.Q(translation_of=self.translation_of.id),
                language=language)


In local_models.py there's this validator to check if the translation_of attribute was not set for pages in the default language:

def validate_translation_of(field_data, all_data):
  if field_data is not None and len(str(field_data)) > 0 and all_data['language'] == settings.DEFAULT_LANGUAGE:
    raise validators.ValidationError("Do not set the translation for english pages.")
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS