Jul 29, 2011

Memcached

Установка

apt-get install memcached
apt-get install python-memcache
pylibmc работает быстрее но из-за того что написан на С вызывает дополнительные эксепшены, поэтому использовать надо осторожно
apt-get install python-pylibmc
Затем прописываем в settings.py
DATABASES = {
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',        
    }
}
или для pylibmc
DATABASES = {
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
        'LOCATION': '127.0.0.1:11211',        
    }
}

Сброс кэша

/etc/init.d/memcached restart
Или через телнет команду flush_all

Изменение конфигурации

vi /etc/memcached.conf

Jul 28, 2011

Управление пакетами в Debian

Список всех установленных пакетов

dpkg --get-selections

Информация о пакете

apt-cache showpkg nginx
Информация об установленном пакете:
dpkg -s apache2.2-common
Cписок файлов (включая директории), инсталлированных в составе пакета:
dpkg -L apache2.2-common
В каком пакете содержится файл:
dpkg -S /lib/libparted-1.8.so.12

Обновление системы

apt-get update  # синхронизация информации из локальной базы данных с источниками, указанными в /etc/apt/sources.list
apt-get -u upgrade
apt-get dist-upgrade

Удаление пакета и всех зависимостей

$ sudo apt-get autoremove gcl

Изменение конфигурации пакетов

Система APT содержит функцию с именем debconf, которая используется для настройки пакетов после их инсталляции. Пакеты, поддерживающие эту функцию (а поддерживают ее не все пакеты), можно заново конфигурировать после их инсталляции. Самый простой способ сделать это – использовать команду dpkg-reconfigure.
# Локаль
locale-gen en_US en_US.UTF-8
dpkg-reconfigure locales
# Часовой пояс
dpkg-reconfigure tzdata

Jul 21, 2011

Amazon ses + django

sudo apt-get install libio-socket-ssl-perl
sudo apt-get install libxml-libxml-perl

sudo pip install boto
sudo pip install django-ses
# in settings.py
AWS_ACCESS_KEY_ID = 'YOUR-ACCESS-KEY-ID'
AWS_SECRET_ACCESS_KEY = 'YOUR-SECRET-ACCESS-KEY'
EMAIL_BACKEND = 'django_ses.SESBackend'

Jul 18, 2011

Rename django admin app name and breadcrumbs

from django.db.models.base import ModelBase
from django.core.urlresolvers import resolve

class AppLabelRenamer(object):
    ''' Rename app label and app breadcrumbs in admin. '''
    def __init__(self, native_app_label, app_label):
        self.native_app_label = native_app_label
        self.app_label = app_label
        self.module = '.'.join([native_app_label, 'models'])

    class string_with_realoaded_title(str):
        ''' tnx to Ionel Maries Cristian for http://ionelmc.wordpress.com/2011/06/24/custom-app-names-in-the-django-admin/'''
        def __new__(cls, value, title):
            instance = str.__new__(cls, value)
            instance._title = title
            return instance

        def title(self):
            return self._title

        __copy__ = lambda self: self
        __deepcopy__ = lambda self, memodict: self

    def rename_app_label(self, f):
        app_label = self.app_label

        def rename_breadcrumbs(f):
            def wrap(self, *args, **kwargs):
                extra_context = kwargs.get('extra_context', {})
                extra_context['app_label'] = app_label
                kwargs['extra_context'] = extra_context
                return f(self, *args, **kwargs)
            return wrap

        def wrap(model_or_iterable, admin_class=None, **option):
            if isinstance(model_or_iterable, ModelBase):
                model_or_iterable = [model_or_iterable]
            for model in model_or_iterable:
                if model.__module__ != self.module:
                    continue
                if admin_class is None:
                    admin_class = type(model.__name__+'Admin', (admin.ModelAdmin,), {})
                admin_class.add_view = rename_breadcrumbs(admin_class.add_view)
                admin_class.change_view = rename_breadcrumbs(admin_class.change_view)
                admin_class.changelist_view = rename_breadcrumbs(admin_class.changelist_view)
                model._meta.app_label = self.string_with_realoaded_title(self.native_app_label, self.app_label)
            return f(model, admin_class, **option)
        return wrap

    def rename_app_index(self, f):
        def wrap(request, app_label, extra_context=None):
            requested_app_label = resolve(request.path).kwargs.get('app_label', '')
            if requested_app_label and requested_app_label == self.native_app_label:
                app_label = self.string_with_realoaded_title(self.native_app_label, self.app_label)
            else:
                app_label = requested_app_label
            return f(request, app_label, extra_context=None)
        return wrap

    def main(self):
        admin.site.register = self.rename_app_label(admin.site.register)
        admin.site.app_index = self.rename_app_index(admin.site.app_index)

# Example
AppLabelRenamer(native_app_label=u'exampleapp', app_label=u'your custom label').main()

Оригинал: http://djangosnippets.org/snippets/2488/

См. также: Изменение названия модуля в django admin

Jul 14, 2011

Decorators ideas

def get_article_from_id(view):
    """
    Retrieves a specific article, passing it to the view directly
    """
    def wrapper(request, id, *args, **kwargs):
        article = get_object_or_404(Article, id=int(id))
        return view(request, article=article, *args, **kwargs)
    return wraps(view)(wrapper)

def content_type(c_type):
    """
    Overrides the Content-Type provided by the view.
    Accepts a single argument, the new Content-Type
    value to be written to the outgoing response.
    """
    def decorator(view):
        def wrapper(request, *args, **kwargs):
            response = view(request, *args, **kwargs)
            response['Content-Type'] = c_type
        return wraps(view)(wrapper)
    return decorator

def dual_format(template_name):
    def decorator(view):
        def wrapper(request, *args, **kwargs):
            data = view(request, *args, **kwargs)
            if request.is_ajax():
                json = simplejson.dumps(data, cls=DjangoJSONEncoder)
                return HttpResponse(json)
            else:
                context = RequestContext(request)
                return render_to_response(template_name, data, context)
        return wraps(view)(wrapper)
    return decorator

def logged(view):
    """
    Logs any errors that occurred during the view
    in a special model design for app-specific errors
    """
    def wrapper(request, *args, **kwargs):
        try:
            return view(request, *args, **kwargs)
        except Exception, e:
            # Log the entry using the application’s Entry model
            Entry.objects.create(path=request.path, type='View exception', description=str(e))

            # Re-raise it so standard error handling still applies
            raise
    return wraps(view)(wrapper)

Jul 6, 2011

Notes

'a' + 'b' # slow
'%s%s' % ('a', 'b') # faster

>> 'an' in 'Django'
True

>> ['a', 'b', 'c'] * 2
['a', 'b', 'c', 'a', 'b', 'c']

>> [x for x in range(10) if x % 2 == 0]
[0, 2, 4, 6, 8]

{'a' : 123, 'b' : '345'}['c'] # KeyError

{'a' : 123, 'b' : '345'}.get('c', 'N/A') # {'a' : 123, 'b' : '345', 'c' : 'N/A'}
'N/A'

Jul 4, 2011

Currency template filter

from django import template
import locale
register = template.Library()
@register.filter(name='currency')
def currency(value):
    try:
        locale.setlocale(locale.LC_ALL,'en_US.UTF-8')
    except:
        locale.setlocale(locale.LC_ALL,'')
    loc = locale.localeconv()
    return locale.currency(value, loc['currency_symbol'], grouping=True)

Making Changes to a Database Schema

Adding Fields

  1. Add the field to your model.
  2. Run manage.py sqlall [yourapp] to see the new CREATE TABLE statement for the model. Note the column definition for the new field.
  3. Start your database’s interactive shell (e.g., psql or mysql, or you can use manage.py dbshell). Execute an ALTER TABLE statement that adds your new column.

Adding NOT NULL Columns

BEGIN;
ALTER TABLE books_book ADD COLUMN num_pages integer;
UPDATE books_book SET num_pages=0;
ALTER TABLE books_book ALTER COLUMN num_pages SET NOT NULL;
COMMIT;

Removing Fields

  1. Remove the field’s code from your model class and restart the Web server.
  2. Remove the column from your database, using a command like this: 
    ALTER TABLE books_book DROP COLUMN num_pages;
Removing Many-to-Many Fields
  1. Remove the ManyToManyField code from your model class and restart the Web server.
  2. Remove the many-to-many table from your database, using a command like this:
    DROP TABLE books_book_authors;

Using South ;)

South brings migrations to Django applications. Its main objectives are to provide a simple, stable and database-independent migration layer to prevent all the hassle schema changes over time bring to your Django applications.