Dec 30, 2011

Extending the Django User model with inheritance

from django.contrib.auth.models import User, UserManager

class CustomUser(User):
    """User with app settings."""
    timezone = models.CharField(max_length=50, default='Europe/London')

    # Use UserManager to get the create_user method, etc.
    objects = UserManager()

...

user = CustomUser.objects.create(...)

# auth_backends.py
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model

class CustomUserModelBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try:
            user = self.user_class.objects.get(username=username)
            if user.check_password(password):
                return user
        except self.user_class.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return self.user_class.objects.get(pk=user_id)
        except self.user_class.DoesNotExist:
            return None

    @property
    def user_class(self):
        if not hasattr(self, '_user_class'):
            self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
            if not self._user_class:
                raise ImproperlyConfigured('Could not get custom user model')
        return self._user_class


# settings.py
AUTHENTICATION_BACKENDS = (
    'myproject.auth_backends.CustomUserModelBackend',
)
...

CUSTOM_USER_MODEL = 'accounts.CustomUser'

http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/

Dec 29, 2011

Monkey patch удаляющий "view on site" кнопку

from django.contrib.auth.models import User
del User.get_absolute_url

Dec 23, 2011

Requests: HTTP for Humans

Очень юзабельное приложение http://docs.python-requests.org/en/latest/index.html

И не менее красивый код https://github.com/kennethreitz/requests/blob/develop/requests/ Есть чему поучиться

Dec 18, 2011

Negative round

>>> str(round(1234.5678, -2))
'1200.0'

Operator overloading for the set builtin

>>> a = set([1,2,3,4])
>>> b = set([3,4,5,6])
>>> a | b # Union
{1, 2, 3, 4, 5, 6}
>>> a & b # Intersection
{3, 4}
>>> a < b # Subset
False
>>> a - b # Difference
{1, 2}
>>> a ^ b # Symmetric Difference
{1, 2, 5, 6}

The Computer Language speed comparison

http://benchmarksgame.alioth.debian.org/


See also: Popularity of Programming Languages

Avoid hardcoding urls

from django.conf import settings

urlpatterns=('',
    ...
    url('^%s$' %settings.LOGIN_URL[1:], 'django.contrib.auth.views.login', 
        name="login")
    ...
)

Django model to dict

from django.forms.models import model_to_dict
model_to_dict(intance, fields=[], exclude=[])

Include tag

<h1>Most sold items</h1>
{% include "items.html" with items=most_sold_items only %}

<h1>Latest items</h1>
{% include "items.html" with items=latest_items only %}

Dec 16, 2011

Readonly Tabluar Inline

# admin.py

class ReadonlyTabularInline(admin.TabularInline):
    can_delete = False
    extra = 0
    editable_fields = []
    
    def get_readonly_fields(self, request, obj=None):
        fields = []
        for field in self.model._meta.get_all_field_names():
            if (not field == 'id'):
                if (field not in self.editable_fields):
                    fields.append(field)
        return fields
    
    def has_add_permission(self, request):
        return False
    

# Usage Example (admin.py)

class FixturesInline(ReadonlyTabularInline):
    model = models.Fixture
    verbose_name_plural = _('List of unpublished Fixtures')
    editable_fields = ['public']



# My models.py (a part of)

class Competition(models.Model):
    name = models.CharField(max_length=200)
    location = models.ForeignKey(Location)

class Fixture(models.Model):
    competition = models.ForeignKey(Competition)
    conference = models.BooleanField()
    home_team = models.ForeignKey(Team, related_name='hometeam')
    guest_team = models.ForeignKey(Team, related_name='guestteam')
    datetime = models.DateTimeField()
    public = models.BooleanField()
    channels = models.ManyToManyField(ChanSatMembership)
    additional_infos = models.TextField(blank=True, null=True)

Form preview

Django comes with an optional “form preview” application

CommonMiddleware

...
Performs URL rewriting based on the APPEND_SLASH and PREPEND_WWW settings.
...

Dec 13, 2011

File

Best way to temporarily unzip a file

gzip.open(zipfile).read()  # will give you the contents of the file in a single string.
with open(tmpfile, "wb") as tmp:
    shutil.copyfileobj(gzip.open(zipfile), tmp)

Date, Time

Pythonic way to add date.timedate and datetime.time objects


>>> datetime.datetime.combine(datetime.date(2011, 01, 01), datetime.time(10, 23))
datetime.datetime(2011, 1, 1, 10, 23)

Dec 9, 2011

Экстремальное программирование. Разработка через тестирование

Качество разработанных тестов оценивается методами:
  • Покрытие операторов кода (statement coverage)
  • Намеренное добавление дефекта (defect insertion)
Паттерны разработки основанной на тестах
  • Тест. Отговорка что на тесты нет времени не совсем коректна, так как приложение все равно тестируется, но руками. Но автоматические тесты намного быстрее! Кроме того тесты снижают уровень стресса
  • Изолированный тест (Isolated Test) - основная причина производительность
  • Список тестов (Test List)
  • Вначале тест (Test First)
  • Вначале оператор assert (Assert First)
  • Тестовые данные (Test Data)
  • Понятные данные (Evident Data). Иногда, если данные используются только в одном методе, для лучшей читабельности можно использовать магические числа
Паттерны красной полосы
  • One Test Step
  • Starter Test (Начальный тест)
  • Explanation Test (Объясняющий тест). Тесты могут служить для объяснения кода
  • Learning Test (Тест для обучения)
  • Another Test
  • Regression Test
  • Break
  • Do Over (Начать сначала). Иногда лучше начать заново, чем пытаться довести до ума кривой код
  • Cheap Desk, Nice Chear. Ну, в общем, хорошее кресло решает..
Паттерны тестирования
  • Дочерний тест (Child Test)
  • Mock Object
  • Self Shunt (Самошунтирование). Как можно убедиться что один объект корректно взаимодействует с другим? Можно заставить тестируемый объект взаимодействовать не с целевым объектом, а с тестом.
        def testNotification(self):
            self.count = 0
            result = TestResult()
            result.addListener(self)
            WasRun('testMethod').run(result)
            self.assertEqual(1, self.count)
    
        def startTest(self):
            self.count = self.count + 1
  • Log String (Строка журнал). Полезен когда важен порядок операций. Хорошо сочетается с Self Shunt. Объект-тест реализует методы шунтируемого интерфейса таким образом, что каждый из них добавляет строку в журнал, затем проверяется корректность этих записей.
  • Crush Test Dummy (Тестирование обработки ошибок). Применяется когда надо протестировать как отрабатывает код по обработке ошибки, возникновение которой маловероятно. Для этого создается фэйковый объект который вместо реальной работы генерирует исключение.
  • Broken Test
  • Clean Check-In
Паттерны зеленой полосы
  • Fake It (Подделка)
  • Triangulate
  • Obvious Implemetnation (Очевидная реализация)
  • One To Many (От одного ко многим). Как реализовать работу с коллекцией объектов? Сначала реализуется для одного объекта, затем модернизируется для работы с коллекцией. 
Паттерны xUnit
  • Assertion
  • Fixture
  • External Fixture. Ресурсы освобождаются в tearDown()
  • Test Method
  • Exception Test
  • All Tests

Dec 4, 2011

get_list_or_404


get_list_or_404(klass*args**kwargs)
Returns the result of filter() on a given model manager, raising Http404 if the resulting list is empty.

Nov 30, 2011

Вывод прошедшего времени в удобочитаемом виде на JavaScript

function date_from_string(dt){
 // 2011-11-30 15:40:50
 var df = dt.split(' ');
 var d = df[0].split('-');
 var t = df[1].split(':');
 return d1 = new Date(d[0],d[1]-1,d[2],t[0],t[1],t[2]);
}

function diff_date(d1){
 var r = (new Date() - d1)/1000;
 
 var tt = {
   sec: ['{} секунд','{} секунда','{} секунды'],
   min: ['{} минут','{} минута','{} минуты'],
   hour: ['{} часов','{} час','{} часа'],
   day: ['{} дней','{} день','{} дня']
 }
 function sec(x,dtt){
  var r;
  x = x.toFixed(0);
  if(x>=11 && x<=14) r = null
  else {
   var s = '' + x;
   if(s.length>1) s = s.substring(1);
   r = { '1':dtt[1], '2':dtt[2], '3':dtt[2], '4':dtt[2] }[s];
  }
  if(!r) r = dtt[0];
  return r.replace('{}',x)
 }
 
 if(r<60) return sec(r, tt.sec) + ' назад';
 r = r / 60;
 if(r<60) return sec(r, tt.min) + ' назад';
 r = r / 60;
 if(r<24) return sec(r, tt.hour) + ' назад';
 r = r / 24;
 if(r<1) return 'сегодня';
 if(r<2) return 'вчера';
 return sec(r, tt.day) + ' назад';
}

Nov 11, 2011

Python Enum

class Color(Enum):
    RED = EnumValue('R', 'Red')
    GREEN = EnumValue('G', 'Green')
    BLUE = EnumValue('B', 'Blue')
Where Enum from here django-stdfields models.py

Nov 10, 2011

Django applications

CMS

Mezzanine - An open source content management platform built using the Django framework.
django-fiber - a simple, user-friendly CMS
merengue - Merengue is a full-featured and pluggable CMS designed for creating websites, writing less code and mantaining clean, elegant and re-usable code.
feincms - A Django-based CMS with a focus on extensibility and concise code

Blog

django-multiblogs - An application for managing multiple blogs, and even *gasp* blog "sets".
django-articles - The blog engine that powers codekoala.com. See http://bitbucket.org/codekoala/django-articles/issues for the ticket tracker

Forum

pybbm - PyBB Modified. Django forum application

Feedback

django-basic-feedback - Provides a Feedback button on your pages and lets you view feedback via Django's admin site. Requires jQuery. 
Django-feedback

Shop

Plata - the lean and mean Django-based Shop
LFS - Lightning Fast Shop

Shopping cart

Cartridge -A Django shopping cart application

Categories

django-categories - This app attempts to provide a generic category system that multiple apps could use. It uses MPTT for the tree storage and provides a custom admin for better visualization

Wiki

django-wiki - Super simple pluggable wiki application for Django.
Hatta - Wiki engine that lives in Mercurial repository.

Poll

django-poll-system - The application to organize polling (or voting) on your site. Demo

Admin

django-admin-sortable - Drag and drop sorting for models and inline models in Django admin
django-admin-filtrate - This Django app makes it easier to create custom filters in the change list of Django Admin and supplies a TreeFilter and a DateRangeFilter too
django-exportable-admin - Provides a custom ModelAdmin which adds CSV export for changelist views

Hosts

django-subdomains - Subdomain tools for the Django framework, including subdomain-specific URL routing
django-hosts - Dynamic and static host resolving for Django. Maps host names to URLconfs

Db

django-denorm - provides a declarative way of denormalizing models in Django based applications while maintaining data consistency.

Permissions

django-object-permissions - A method for adding object-level or row-level permissions
django-moderation - is reusable application for Django framework, that allows to moderate any model objects.
django-su - Login as any user from the Django admin interface, then switch back when done

Messages

django-postman - User-to-User messaging system for Django, with gateway to AnonymousUser, moderation and thread management, user & exchange filters, auto-complete support.

Translation

django-transmeta - an application for translatable content in Django's models. Each language is stored and managed automatically in a different column at database level.

Template tag

django-ttag - A template tag constructor library for Django

Image

django-image-cropping - A reusable app for cropping images easily and non-destructively in Django

JavaScript and CSS Compression

django-pipeline - Pipeline is an asset packaging library for Django, providing both CSS and JavaScript concatenation and compression, built-in JavaScript template support, and optional data-URI image embedding.

Geo

django-cities - Countries and cities of the world for Django projects
django-countries - Nice little application for Django projects providing fixtures and models for a "complete" list of world countries

Map

django-leaflet - allows you to use Leaflet (version 0.3) in your Django projects.

PDF

pdfdocument - ReportLab-wrapper

Barcodes

python-qrcode - This module uses the Python Imaging Library (PIL) to allow for the generation of QR Codes.

CSV

django-csv-importer - Convert csv files into python object or django model
django-exportable-admin - Provides a custom ModelAdmin which adds CSV export for changelist views

Visitors analytic

httpagentparser - Extracts OS Browser etc information from http user agent string
django-mobi - Django middleware and view decorator to detect phones and small-screen devices.
geobaza - Geobaza is the software for geolocation by IP-address.
django-online-counter - Django online visitor counter

JavaScript

djangbone - Django backends to talk to Backbone.js
dajaxproject - Easy to use AJAX libraries for django

Autocomplete/Select

django-ajax-selects - jQuery UI-powered auto-complete fields for ForeignKey, ManyToMany and text fields
django-chosen - django FormFields using the Chosen javascript plugin for jQuery
django-smart-selects - chained and grouped selects for django forms

Inline edition

django-inplaceedit - allows inline edition of some data from the database

File upload

plupload - The developers of TinyMCE brings you Plupload, a highly usable upload handler for your Content Management Systems or similar. Plupload is currently separated into a Core API and a jQuery upload queue widget this enables you to either use it out of the box or write your own custom implementation.
uploadify - Uploadify is a jQuery plugin that integrates a fully-customizable multiple file upload utility on your website. It uses a mixture of Javascript, ActionScript, and any server-side language to dynamically create an instance over any DOM element on a page.

JSON

django-serverpush - django server push solution

GUI

pyside - bindings for the Qt cross-platform application and UI framework
wxpython - a blending of the wxWidgets C++ class library with the Python programming language

Testing

selenium - Python bindings for Selenium
django-selenium - Selenium testing support for django

Logging

django-peavy
  • Middleware to tag each request with a unique ID.
  • Logging filters to capture request metadata like user, remote IP, and headers.
  • Logging handlers for:
    • Capturing exception information, including a copy of the Django server error page, in a database.
    • Sending error notifications to admins without revealing sensitive information like the contents of request.POST.
  • A database router for sending log records to a separate database.
  • A simple user interface for browsing log records in the database.
django-object-log - A method for logging user actions on models

Profiling

django-profiler - Util for profiling python code mainly in django projects but can be used also on ordinary python code. It counts sql queries a measures time of code execution.
django-debug-logging - A plugin for the Django-Debug-Toolbar to provide statistic logging and a UI for reviewing the logs.
django-statsd - Integration between statsd and django. It allows you to use different clients, sends timings as middleware and integrates with django debug toolbar.
psutil - is a module providing an interface for retrieving information on all running processes and system utilization (CPU, disk, memory, network) in a portable way by using Python, implementing many functionalities offered by command line tools.

Data visualization

django-graphviz

Django and Python Coding Style and Best Practices

Introduction:
The Zen of Python (PEP 20)

Follow guide lines:
Style Guide for Python Code (PEP 8)
Django coding style
Google Python Style Guide (RU)

Tutorials:
Django best practices fork of Django Reusable App Conventions
Django Design Patterns
Django Advice
The Hitchhiker’s Guide to Python!
Python Project Howto
Code Like a Pythonista: Idiomatic Python
Nick Coghlan’s Python Notes
A Guide to Python's Magic Methods

Code checkers:
django-lint Online

Learn by examples:
Rosettacode code and algorithms examples

Be aware of
Python Standard Library: A Few of My Favorite (Python) Things
Design patterns
http://www.pypedia.com/index.php/Main_Page


Thoughts on RESTful API Design

Setup module function (UnitTest)

The default ordering of tests created by the unittest test loaders is to group all tests from the same modules and classes together. This will lead to setUpClass / setUpModule (etc) being called exactly once per class and module. If you randomize the order, so that tests from different modules and classes are adjacent to each other, then these shared fixture functions may be called multiple times in a single test run.
import unittest

def setUpModule():
    print 'Module setup...'

def tearDownModule():
    print 'Module teardown...'

class Test(unittest.TestCase):
    def setUp(self):
        print 'Class setup...'

    def tearDown(self):
        print 'Class teardown...'

    def test_one(self):
        print 'One'

    def test_two(self):
        print 'Two'

Nov 9, 2011

Mercurial HowTo

Tutorial
http://hginit.com/01.html

How to correctly close a feature branch in Mercurial?
hg up feature-x
hg ci -m 'branch closed' --close-branch

hg up default
hg merge feature-x
hg ci -m merge
To completely undo the uncommitted merge and discard all local modifications, you will need to issue a
# note the "dot" at the end of the command
hg update -C -r .

Merge or rebase with uncommitted changes

hg diff > somefile.diff
hg revert -a
hg import --no-commit somefile.diff

Undo not pushed commit

hg rollback

Finding the nearest with the ORM

from django.contrib.gis.geos import Point
lawrence = Point((-95.234657999999996, 38.972679999999997))
Campground.objects.all().distance(lawrence).order_by('distance')

Django decorator/middleware cache key for given URL

import hashlib
from django.utils.encoding import iri_to_uri
from django.conf import settings
from django.utils.translation import get_language

def url_cache_key(url, language=None, key_prefix=None):
    if key_prefix is None:
        key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
    ctx = hashlib.md5()
    path = hashlib.md5(iri_to_uri(url))
    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
        key_prefix, 'GET', path.hexdigest(), ctx.hexdigest())
    if settings.USE_I18N:
        cache_key += '.%s' % (language or get_language())
    return cache_key


http://djangosnippets.org/snippets/2595/

Nov 8, 2011

The Art of Readable Code - D. Boswell and T. Foucher

  • Attach important details to variable names - for example, append _ms to a variable whose value is in milliseconds or prepend raw_ to an unprocessed variable that needs escaping.
  • Use longer names for larger scopes - don’t use cryptic one- or two-letter names for variables that span multiple screens; shorter names are better for variables that span only a few lines.

Word Alternatives

send - deliver, dispatch, announce, distribute, route
find - search, extract, locate, recover
start - launch, create, begin, open
make - create, set up, build, generate, compose, add, new

Avoid generic names like tmp and retval, unless there’s a specific reason to use them.

Values with Units

Start(int delay) - delay - delay_secs
CreateCache(int size) - size - size_mb
ThrottleDownload(float limit) - limit - max_kbps
Rotate(float angle) - angle - degrees_cw

Encoding Security Attributes

This technique of attaching extra information to a name isn’t limited to values with units. You should do it any time there’s something dangerous or surprising about the variable.

For example, many security exploits come from not realizing that some data your program receives is not yet in a safe state. For this, you might want to use variable names like untrustedUrl or unsafeMessageBody. After calling functions that cleanse the unsafe input, the resulting variables might be trustedUrl or safeMessageBody.
  • A password is in “plaintext” and should be encrypted before further processing - password- plaintext_password 
  • A user-provided comment that needs escaping before being displayed - comment - unescaped_comment 
  • Bytes of html have been converted to UTF-8 - html - html_utf8 
  • Incoming data has been “url encoded” - data - data_urlenc

Coments Markers

TODO: Stuff I haven’t gotten around to yet
FIXME: Known-broken code here
HACK: Admittedly inelegant solution to a problem
XXX: Danger! major problem here

Variables and readability

  • Reduce the scope of each variable to be as small as possible. Move each variable to a place where the fewest lines of code can see it. Out of sight is out of mind.
  • Prefer write-once variables. Variables that are set only once (or const, final, or otherwise immutable) make code easier to understand.

Reorganizing Your Code

  • Separate the generic code from the project-specific code.
  • Code should be organized so that it’s doing only one task at a time.
  • Avoid writing new lines of code by:
    • Eliminating nonessential features from your product and not overengineering
    • Rethinking requirements to solve the easiest version of the problem that still gets the job done
    • Staying familiar with standard libraries by periodically reading through their entire APIs

Testing and Readability

  • Implementing Custom “Minilanguages
  • Use the simplest test inputs that completely exercise your code.
  • Give your test functions a fully descriptive name so it’s clear what each is testing. Instead of Test1(), use a name like Test_<FunctionName>_<Situation>.

Data apps for Django

django-tables2

Simplifies the task of turning sets of data into HTML tables. It has native support for pagination and sorting

{% load django_tables2 %}
{% render_table table %}

django-autoreports (csv export)

Autoreports is a Django application that lets you create reports in very Django Admin listing
Redefine 'admin/change_list.html' templates as follows
{% load adminmedia admin_list i18n autoreports_tags %} {# add auto_reports_tags #}

#...#

{% block object-tools %}
  {% if has_add_permission %}
    <ul class="object-tools">
      <li>
        <a href="add/{% if is_popup %}?_popup=1{% endif %}" class="addlink">
          {% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}
        </a>
      </li>
      {% autoreports_admin %} {# add this stuff #}
    </ul>
  {% endif %}
{% endblock %}

#...#
For basic usage you have to api, and you can export to CSV each models.
/autoreports/app_label/module_name/
/autoreports/app_label/module_name/?filter1=value1

django-easyfilters

Easy creation of link-based filtering for a list of Django model objects. Demo

django-datatables - datatables.net

Nov 7, 2011

django-sekh - Highlight the keywords of a page if a visitor is coming form a search engine.

django-fabfile

django-fabfile - Fabric tasks for Django and Amazon Web Services

Django soft delete

django-softdelete Soft delete for Django ORM, with support for undelete

Forms apps, snippets, widgets

django-forms-ext

Fields
  • ForeignKeyChoiceField - When you have a formset that has a foreign key, Django will fire off a new (identical) query to build the choices for that field for each form in the formset by default. Using this field will allow you to run the query once for the choices and re-use that queryset for each form in the formset. CommaSeparatedField - Django has a comma separated integer field, but not just strings. Stupid, I know... we created one for use with strings 
  • QuerysetChoiceField - When you want to build a select box with a queryset but don't want a model instance when saving, use this thing. 

Views
  • FormSetView - Django 1.3's generic views do not include a FormSet view. That's what this is.

django-stdfields

Fields
  • MinutesField: use an integer to represent a duration of minutes and hours
  • EnumIntegerField: makes working with choices a bit easier
  • EnumCharField: the same, but for choices with a char key

django-forms-builder

A Django reusable app providing the ability for admin users to create their own forms

django-bfm

  • Multifile Uploads (Open File Dialog)
  • Live Upload Status report (Upload applet)
  • File browsing
  • Directory support
  • Core features has no dependencies (except for Django), lightweight
  • Looks like django admin (extends admin template)

django-custom-field

Allow end users to create easy (but slower to work with) fields attached to any Django model. Includes support so fields show up in the admin interface and helper functions that make it easy to access any custom fields programmatically.

django-wizard

allows views to be organized into steps for linear page flows

django-easyfilters

http://pypi.python.org/pypi/django-easyfilters/ - Easy creation of link-based filtering for a list of Django model objects.

DataTables jQuery plugin

DataTables jQuery plugin

Nov 3, 2011

geobaza - Geobaza is the software for geolocation by IP-address.

Nov 2, 2011

Snippets, schemas

Schema.org - This site provides a collection of schemas, i.e., html tags, that webmasters can use to markup their pages in ways recognized by major search providers. Search engines including Bing, Google and Yahoo! rely on this markup to improve the display of search results, making it easier for people to find the right web pages.

Python / Django Performance profiling

https://code.djangoproject.com/wiki/ProfilingDjango
http://ianozsvald.com/2012/03/18/high-performance-python-1-from-pycon-2012-slides-video-src/
Профилирование и отладка Python, инструменты

Django

django-extensions - this is a repository for collecting global custom management extensions for the Django Framework
python manage.py runprofileserver --use-cprofile --prof-path=/tmp/output
django-perftools
  • QueryCountLoggingMiddleware - Perftools includes a logger that will monitor requests execution time. Once it hits the defined threshold, it will log to the named perftools logger, including the metadata for the request (as defined by Sentry's logging spec).
  • RemoteProfilingMiddleware - Profiles a request and saves the results to disk.
  • SlowRequestLoggingMiddleware - Logs requests which exceed a maximum number of queries.
django-profiler is util for profiling python code mainly in django projects but can be used also on ordinary python code. It counts sql queries a measures time of code execution. It logs its output via standard python logging library and uses logger profiling. If your profiler name doesn't contain any empty spaces e.g. Profiler('Profiler1') django-profiler will log all the output to the profiling.Profiler logger. @profilehook decorator uses profilehooks python package to gather code execution stats. Except it logs via standard python logging it also outputs code execution stats directly to sys.stdout.
from profiling import profile

@profile
def complex_computations():
    #some complex computations

django-processinfo - application to collect information about the running server processes.

dogslow - Dogslow is a Django watchdog middleware class that logs tracebacks of slow requests.

Python

line_profiler - is a module for doing line-by-line profiling of functions. kernprof is a convenient script for running either line_profiler or the Python standard library's cProfile or profile modules, depending on what is available.
runsnakerun - is a small GUI utility that allows you to view (Python) cProfile or Profile profiler dumps in a sortable GUI view. It allows you to explore the profiler information using a "square map" visualization or sortable tables of data. It also (experimentally) allows you to view the output of the Meliae "memory analysis" tool using the same basic visualisations.
dis - The dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode.h and used by the compiler and the interpreter.
def myfunc(alist):
    return len(alist)

>>> dis.dis(myfunc)
  2           0 LOAD_GLOBAL              0 (len)
              3 LOAD_FAST                0 (alist)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE

plop - Plop is a stack-sampling profiler for Python. Profile collection can be turned on and off in a live process with minimal performance impact.
statprof.py - This package provides a simple statistical profiler for Python.
pytrace - is a fast python tracer. it records function calls, arguments and return values. can be used for debugging and profiling.

WSGI

wsgi-shell - The 'ispyd' package provides an in process shell for introspecting a running process. It was primarily intended for investigating running WSGI application processes, specifically to determine what a process is doing when it hangs, but has many other features as well. This includes being able to start an embedded interactive Python interpreter session, set debugger probe points to record tracebacks for exceptions and then later run 'pdb' in post mortem mode on those exceptions.

Linux

top -H
1 - нагруженность цпу
С - сортировать по цпу
М - сортировать по памяти
к - прибить процесс
с - показать путь к комманде

vmstat - выдает информационный отчет о активности процессов, памяти, свопинга, поблочного ввода/вывода, прерываний и процессора
w - кто зарегистрирован и что они делает
free – использование памяти
pstree - процессы в виде иерархии

ps
ps -u someusername -o pid,%cpu,%mem,start_time,size=-size-,state,cmd
ps -u someusername -o pid,%cpu,%mem,start_time,size=-size-,state,comm | grep runfastcgi.fcgi

Disks usage
df -h

Nov 1, 2011

Images processing apps

django-imagekit
from django.db import models
from imagekit.models import ImageSpec
from imagekit.processors import resize, Adjust

class Photo(models.Model):
    original_image = models.ImageField(upload_to='photos')
    thumbnail = ImageSpec([Adjust(contrast=1.2, sharpness=1.1),
            resize.Crop(50, 50)], image_field='original_image',
            format='JPEG', quality=90)

Translation apps

django-linguo

from linguo.models import MultilingualModel
from linguo.managers import MultilingualManager

class Product(MultilingualModel):
    name = models.CharField(max_length=255, verbose_name=_('name'))
    description = models.TextField(verbose_name=_('description'))
    price = models.FloatField(verbose_name=_('price'))

    objects = MultilingualManager()

    class Meta:
        # name and description are translatable fields
        translate = ('name', 'description')

Oct 28, 2011

Search applications

django-watson - Full-text multi-table search application for Django. Easy to install and use, with good performance.

django-solr - Solr Search Engine ORM for Django
http://yuji.wordpress.com/2011/08/18/installing-solr-and-django-haystack-on-ubuntu-with-openjdk/
pip install django-haystack

sudo apt-get install openjdk-6-jre jetty solr-jetty

./manage.py build_solr_schema > schema.xml
sudo mv schema.xml /etc/solr/conf/schema.xml

sudo vi /etc/jetty/jetty.xml
#set default HAYSTACK_SOLR_URL setting port
#<Set name="port"><SystemProperty name="jetty.port" default="8983"/></Set>

sudo vi /etc/solr/conf/solrconfig.xml
#<lockType>simple</lockType>
#<unlockOnStartup>true</unlockOnStartup>

sudo vi /etc/init.d/jetty
# change port to 8983
# change user to root

sudo vi /etc/default/jetty
# change NO_START to be 0
# JAVA_HOME=YOUR_JDK_HOME

sudo /etc/init.d/jetty restart

./manage.py rebuild_index

Testing applications and extensions

Python Testing Tools Taxonomy
Django Packages: Testing Tools

Open Source Testing
Link Checker

django-testtools - A helper for writting Django's tests.
  • assertRecipients
  • assertQuerySetEqual
  • assertErrorsInForm
django-test-extensions - A set of custom assertions and examples for use testing django applications.
  • login_as_admin
  • ...
  • assert_file_exists
  • assert_key_exists
  • assert_has_attr
  • ...
  • assert_mail
  • assert_latest
  • assert_model_changes
django-autofixture - Can create auto-generated test data
from autofixture import AutoFixture
fixture = AutoFixture(Entry)
entries = fixture.create(10)
django-test-utils
  • Django Testmaker 
  • Django Crawler 
  • Django Test Runner 
  • Twill Runner 
  • Persistent Database Test Runner
+
./manage.py makefixture proposals.Proposal[:10] --indent=4 > proposal_with_related_items.json
factory_boy - A test fixtures replacement for Python based on thoughtbot's factory_girl for Ruby
import factory
from models import User

class UserFactory(factory.Factory):
    FACTORY_FOR = User

    first_name = 'John'
    last_name = 'Doe'
    admin = False

# Returns a User instance that's not saved
user = UserFactory.build()

# Returns a saved User instance
user = UserFactory.create()

# Returns a dict of attributes that can be used to build a User instance
attributes = UserFactory.attributes()

# Returns an object with all defined attributes stubbed out:
stub = UserFactory.stub()
rebar - Rebar makes your Forms stronger
from rebar.testing import flatten_to_dict

form_data = flatten_to_dict(ContactForm())
form_data.update({
        'name': 'X' * 300,
    })
form = ContactForm(data=form_data)
assert(not form.is_valid())
The same for formsets
from rebar.testing import flatten_to_dict, empty_form_data

formset = ContactFormSet()
form_data = flatten_to_dict(formset)
form_data.update(
    empty_form_data(formset, len(formset))
)

django-uuslug

https://github.com/un33k/django-uuslug - Guarantee a unique unicode slug for use in Django projects

Oct 26, 2011

Программист-прагматик. Путь от подмастерья к мастеру - Э. Хант, Д. Томас

Прагматическая философия

  • Хаос в программе пораждает еще большую неразбириху. Если есть недоработки стоит сразу их устранить.

Прагматический подход

  • DRY
  • Ортогональность системы - объекты не должны пересекаться или пересекаться минимально. (сцепление - cohesion)
  • Стрельба трассирующими
  • Прототип
  • Язык должен отражать предметную область (именование переменных)
  • Определять для себя на сколько точной должна быть оценка. Часто не обязательно знать 2 дня 10 часов обычно достаточно около 3х дней

Походный набор инструментов

  • Генераторы текстов: пассивные и активные (каждый пересоздают на основе актуальных данных)

Прагматическая паранойя

  • Контракты
  • Утверждения
  • Исключения используется только в действительно исключительных ситуациях. В противном случае они становятся подобны оператору goto.
  • Участок кода использующий ресурс отвечает и за его освобождение. Освобождаютя ресурсы в обратной последовательности по отношению к распределению этих ресурсов.

Гибкость против хрупкости

  • Несвязанность и закон Деметера 
  • Если есть возможность распараллелить программу, то эту возможность надо использовать (потоки, асинхронность).
  • "Доски объявлений" для координации потоков работ.
  • События, паттерны Observer и MVC хорошо подходят для графических интерфейсов.

Пока вы пишите программу

  • Хороший код можно написать только четко понимая что и как происходит. Это и есть преднамеренное программирование.
  • Оценку скорости алгоритма можно сделать определив его порядок. Цикл Q(n), вложенный цикл Q(m x n). Для сортировки лучше использовать библиотечные методы, скорость их работы оптимизирована.
  • Перед рефакторингом лучше убедиться что все тесты прошли успешно. Лучше рефакторинг проводить отдельно от добавления новых возможностей. После реорганизации обязательно проводить регрессионные тесты.
  • Тестовый стенд. Отладочное окно по горячим клавишам.

Перед тем как начать проект

  • Список новых изменений и требований поможет остановит их последующий лавинообразный рост.
  • Глоссарий терминов проекта позволит использовать их согласованно и новым участникам проекта понять их значение.
  • Если документы хранятся в проекте, то больше шансов, что их будут читать.
  • Часто у сложной проблемы есть простое решение. Его надо увидеть за навязываемым сложным.

Прагматические проекты

  • Если ручное тестирование обнаружило баг, то следует обязательно написать тест который бы находил эту ошибку, чтобы в будущем автоматизированное тестирование вылавливало его.
  • Если слегка превысить ожидания пользователей это сделает их более дружелюбными к вашему приложению.

Рефакторинг. Улучшение существующего кода - Мартин Фаулер




Книга будет интересна тем кто не пользуется pycharm :) Ну действительно, кому интересно как делается "Introduce variable", если с этим отлично справляется IDEшка? )))

Если серьезно, то в книге много полезной информации для чего делаются разные виды рефакторинга и, соответственно, есть каталог типов рефакторинга. Пометим несколько моментов..
Перед тем как проводить рефакторинг проверяется работоспособность кода, пишутся тесты.
Рефакторинг проводится поэтапно шаг за шагом, небольшими кусками кода и, обязательно, отдельно от добавления новой функциональности.
Не надо пытаться покрыть тестами все возможные варианты выполнения кода, но обязательно надо проверить все узкие места.

Источники неприятных запахов

  • Дублирование кода
  • Длинный метод
  • Большой класс
  • Длинный список параметров
  • Расходящиеся модификации (когда один класс модифицируется различными способами по разным функциональным причинам)
  • Стрельба дробью (изменения разбросаны по коду)
  • Завистливые функции (метод класса больше интересуется другим классом а не собственным)
  • Группы данных
  • Одержимость элементарными типами (валюта, номера телефонов, почтовые индексы)
  • Операторы switch
  • Параллельные иерархии наследования
  • Ленивый класс (лишний)
  • Теоретическая общность (программированное наперед)
  • Временное поле (когда в объекте атрибут устанавливается только при определенных обстоятельствах)
  • Цепочки сообщений (o.getBla().getFoo().getBar()...)
  • Посредник (лишний делегат)
  • Неуместная близость
  • Альтернативные классы с разными интерфейсами
  • Неполнота библиотечного класса
  • Классы данных
  • Отказ от наследства (например, пустой переопределенный метод)
  • Комментарии

CMSs

django-fiber
ella - Ella is an opensource CMS based on the Django framework. It originated in CentrumHoldings as CMS for their lifestyle magazines (mainly Žena.cz) with an ambition to become the only CMS powering all CentrumHoldings content websites from lifestyle magazines with medium traffic to news sites with millions of pageviews per day.

Oct 22, 2011

django-helptext

http://pypi.python.org/pypi/django-helptext/0.3 - A django application for editing django model field help text in the django admin

Oct 21, 2011

The Python Standard Library

http://docs.python.org/library/index.html

References & Development Aides

Using Vim with Django

https://code.djangoproject.com/wiki/UsingVimWithDjango

Oct 20, 2011

Web App Security: Django and the OWASP Top 10


  1. Code Injection:  For most Django applications, the primary code injection risk is SQL injection.  Django protects against SQL injection through its ORM abstraction layer, which automatically escapes input.  Note that it's possible toperform raw sql queries with Django, any any such code should be manually audited for if it interacts with direct user input.  Though raw SQL is needed occasionally, especially for optimization, it's generally a code smell in a Django application.

    If your application interacts with any other backends, like LDAP, you'll want to investigate those third-party libraries separately.  Client-side javascript is also mitigated through its templating system; see #2 below.
  2. Cross-site scripting:  Generally, the most important way to mitigate XSS is to prevent unescaped user input from making it into your application's rendered HTML. Django’s templating system facilitates this by automatically excaping all variable values.  If you don't want to escape something on the front end, you have to explicitly tell Django not to escape it.  In your code reviews, you can concentrate more on the few areas of your app where you don't escape user input.
  3. Session hijacking:  With the default Django SessionMiddleware, the framework doesn't allow any session data in the url.  Session IDs are also stored as hashes, mitigating brute force attacks.

    While you'll still want to ensure your code doesn't expose direct session data to the user in any way, Django makes it difficult to expose that information.
  4. Insecure direct object references:  Django has several mechanisms in place to mitigate IDORs.  It provides a special "slug" field if you don't want to pass object IDs around as parameters.  Django 1.2 also lets you explicitly name read-only fields in the admin, so you can prevent users from hacking together forms that alter protected  data.

    Note that you'll still want to manually audit your code to expose areas where users can access arbitrary object data, especially outside of the admin.
  5. Cross-site request forgery:  Django has built-in CSRF protection middleware, so it would be extraordinarily difficult for an attacker to maliciously submit a form to your site using an authenticated user's credentials.
  6. Security misconfiguration:  This is one item that is largely outside the domain of the web framework itself; it's more about the application's deployment environment.  You need to keep up with Python security updates, Django security updates, and keep track of any third-party libraries you use for security updates.  You need to disable ports/services you don't use, and more.  With complex apps, this can be a huge job.

    Fortunately, there are great, frequently-updated blogs for both the Python andDjango core teams where you can keep track of security updates.  It's also easy to follow security announcement lists for your web server (e.g. apachenginx) or operating system to keep track of security updates.
  7. Insecure cryptographic storage:  If the only secure information you're encrypting is user password data, you're all set if you use Django's built-in user authentication.  Django encrypts password data using SHA1 by default, but also supports MD5 and crypt out-of-the-box.

    If your application directly stores or manipulates any sensitive user data, you'll need to audit that code manually.  Fortunately, OWASP maintains a great cryptographic storage cheat sheet to help you along the way.
  8. Failure to restrict URL access:  Django has great built-in support for restricting access to specific content.  Access is always controlled at the view level, before anything is rendered.  You're able to restrict access for specific actions or forentire views.  Note that you'll still want to audit each url/action in your app to ensure that you're restricting access the way you intended.  It's easy to miss a @login_required decorator or forget to lock down an AJAX action.
  9. Insufficient transport layer protection:  In many cases, strong transport layer protection means using SSL.  Though this falls outside the domain of Django itself, the framework does provide some help:  Django supports the secure cookie protocol (PDF link to research paper), and also allows developers to force the use of secure cookies over HTTPS.
  10. Unvalidated redirects and forwards:  Because of Django's robust, built-in URL access restriction (see #7), it would be very hard for an attacker to take advantage of unvalidated redirects.  Again, since access is handled at the view level, you can't [easily] redirect users to a different url on your site without access control.

    Additionally, Django's built-in user authentication system doesn't allow off-site redirect links as url parameters.  Note that you'll still want to audit your code for any manual use of redirect links in URL parameters.

Django caching

Полезная презентация: Cache rules everything around me
http://lanyrd.com/2011/djangocon-us/shbrr/

django-cacheops

A slick app that supports automatic or manual queryset caching and automatic granular event-driven invalidation. It can also cache results of user functions and invalidate them by time or the same way as querysets. It uses redis as backend for ORM cache and redis or filesystem for simple time-invalidated one.

django-newcache

Ничего особо полезного не нашел. Есть бэкенд для pylibmc, но такой уже имеется в джанге.

johnny-cache

Кэширует все запросы. есть серьезные ограничения
Avoiding the database at all costs was not a goal, so different ordering clauses on the same dataset are considered different queries. Since invalidation happens at the table level, any table having been modified makes the cached query inaccessible
# cached, depends on `publisher` table
p = Publisher.objects.get(id=5)
# cached, depends on `book` and `publisher` table
Book.objects.all().select_related('publisher')
p.name = "Doubleday"
# write on `publisher` table, modifies publisher generation
p.save()
# the following are cache misses
Publisher.objects.get(id=5)
Book.objects.all().select_related('publisher')

django-autocache

В объект добавляется поле cache.
Instance Caching
class Model(django.models.Model):
    cache = autocache.CacheController()
    field = django.models.TextField()

Model.objects.get(pk=27)    # hits the database
Model.cache.get(27)         # Tries cache first
Related Objects Caching
instance = Model.cache.get(pk=27)
related_things = instance.things_set.all()  # hits the database
related_things = instance.cache.things_set  # Tries cache first
 Тоже есть ограничения
Autocache relies on the post_save and post_delete signals to keep your cache up to date. Performing operations that alter the database state without sending these signals will result in your cache becoming out of sync with your database.

cache-machine

Еще одна библиотека для автоматического кэширования и инвалидации. Ограничение - CachingManager должен быть менеджером модели по умолчанию
from django.db import models

import caching.base

class Zomg(caching.base.CachingMixin, models.Model):
    val = models.IntegerField()

    objects = caching.base.CachingManager()

django-cache-utils2

Django caching decorator + invalidate function
from cache_utils2 import cached, invalidate

@cached(60)
def foo(x, y=0):
    print 'foo is called'
    return x+y

foo(1, 2) # foo is called
foo(1, y=2)
foo(5, 6) # foo is called
foo(5, 6)
invalidate(foo, {'x': 1, 'y': 2})
foo(1, 2) # foo is called
foo(5, 6)
foo(x=2) # foo is called
foo(x=2)

Caching parsed templates

django.template.loaders.cached.Loader
https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types

Expire page from cache

from django.core.cache import cache
from django.http import HttpRequest
from django.utils.cache import get_cache_key

def expire_page(path):
    request = HttpRequest()
    request.path = path
    key = get_cache_key(request)
    if cache.has_key(key):   
        cache.delete(key)
http://djangosnippets.org/snippets/936/

Oct 19, 2011

Django servers benchmarks

fcgi vs. gunicorn vs. uWSGI
Benchmark of Python WSGI Servers

A Django setup

Using Nginx and Gunicorn
http://senko.net/en/django-nginx-gunicorn/

Using Nginx and uWsgi
http://grokcode.com/784/how-to-setup-a-linux-nginx-uwsgi-python-django-server/
http://www.eshlox.net/en/2012/09/11/nginx-uwsgi-virtualenv-and-django-ubuntu-1204/

A skeleton Django project

http://senko.net/en/django-quickstart-skeleton-project/
https://github.com/senko/dj-skeletor

DJ Skeletor is a skeleton Django project handy for bootstrapping new empty projects.

The repository contains an empty, relocatable Django project with South, Django Debug Toolbar and Sentry apps set, and with provisions for test and production settings.

HTML5 Boilerplate

http://html5boilerplate.com/ - A rock-solid default for HTML5 awesome.

Bootstrap, from Twitter

http://twitter.github.com/bootstrap/

Bootstrap is a toolkit from Twitter designed to kickstart development of webapps and sites.It includes base CSS and HTML for typography, forms, buttons, tables, grids, navigation, and more.

Модель акторов

http://jodal.github.com/pykka/
http://ru.wikipedia.org/wiki/%D0%9C%D0%BE%D0%B4%D0%B5%D0%BB%D1%8C_%D0%B0%D0%BA%D1%82%D0%BE%D1%80%D0%BE%D0%B2


Модель акторов исходит из такой философии, что всё вокруг является акторами. Это похоже на философию объектно-ориентированного программирования, где всё вокруг является некоторыми объектами, но отличается тем, что в объектно-ориентированном программировании программы, как правило, выполняются последовательно, в то время как в модели акторов вычисления по своей сути совпадают по времени.

Актор является вычислительной сущностью, которая в ответ на полученное сообщение может одновременно:
  • отправить конечное число сообщений другим акторам;
  • создать конечное число новых акторов;
  • выбрать тип поведения, которое будет использоваться для следующего сообщения в свой адрес.

Может существовать произвольная последовательность вышеописанных действий, и все они могут выполняться параллельно.

Развязка отправителя и посланных сообщений стала фундаментальным достижением модели акторов, обеспечившая асинхронную связь и управление структурами как прототип передачи сообщений.

Получатели сообщений идентифицируются по адресу, который иногда называют «почтовым адресом». Таким образом, актор может взаимодействовать только с теми акторами, адреса которых он имеет. Он может извлечь адреса из полученных сообщений или знать их заранее, если актор создан им самим.

Модель акторов характеризуется внутренне присущим параллелизмом вычислений внутри одного актора и между ними, динамическое создание акторов, включение адресов акторов в сообщения, а также взаимодействие только через прямой асинхронный обмен сообщениями без каких-либо ограничений на порядок прибытия сообщений.

Oct 16, 2011

Virtualenv + pip

Install easy_install, pip, virtualen

sudo apt-get install python-setuptools python-virtualenv python-pip

Create virtual environment

$ virtualenv --no-site-packages env # from version 1.7 --no-site-packages default behavior
$ source env/bin/activate

(env)$ export PYTHONPATH=  # sometimes required
(env)$ pip install django
# ...
(env)$ pip freeze > requirements.txt
(env)$ deactivate

$ virtualenv --no-site-packages env2
$ source env2/bin/activate
(env2)$ pip install -r requirements.txt

Pip

# concrete package version
(env)$ pip install ipython==0.11

# archive link
(env)$ pip install -f http://downloads.sourceforge.net/project/matplotlib/matplotlib/matplotlib-1.0/matplotlib-1.0.0.tar.gz matplotlib

# install for concrete python interpreter version
sudo pip install ipython -E python2.5

Bonuses

List all packages with requirements:
pip list --local | awk '{print $1}' | xargs pip show | grep -v -e '^Location' -e '^Requires: $'
yolk - list installed packages
(env2)$ pip install yolk
(env2)$ yolk -l
vanity - list available versions
(env2)$ pip install vanity
(env2)$ vanity django -v

PyCharm

If you use PyCharm you’ll want to set up your virtualenv there for your project. Edit your project settings. Select Python Interpreter -> Add -> Specify Other… Add python from your virtual_env (env/bin/python)

Oct 11, 2011

500/404 templates if you only use the admin

If you have a project that only exposes the admin you should just use the 500/404 templates from the admin.

urls.py:
from django.utils.functional import curry
from django.views.defaults import server_error, page_not_found

handler500 = curry(server_error, template_name='admin/500.html')
handler404 = curry(page_not_found, template_name='admin/404.html')
If you have other drop-in apps that need authentication (like rosetta or sentry) bare in mind that the admin doesn’t have a reusable login view so you must hook one. You should just reuse django admin’s login template.
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}),

Making Django's signals asynchronous with Celery

from celery.task import task
from django.db.models.signals import post_save

from myproject.models import MyModel

# Warning. Monkey patch.
from django.dispatch.dispatcher import Signal
def reducer(self):
    return (Signal, (self.providing_args,))
Signal.__reduce__ = reducer

# With the patch done, we can now connect to celery tasks.
@task(ignore_result=True)
def async_post_save(sender, instance, **kwargs):
    # do something with the instance.
    pass
post_save.connect(async_post_save.delay, sender=MyModel)
Патч нужен только если требуется в декоратор task передавать аргумент(ы). В противном случае достаточно:
from celery.task import task
from django.db.models.signals import post_save

from myproject.models import MyModel

@task
def async_post_save(instance):
    # do something with the instance.
    pass

def post_save_reciever(sender, instance, **kwargs):
    async_post_save.delay()
post_save.connect(post_save_reciever)
Оригинал в блоге  Dougal Matthews

My Vim plugins and config for comfortable Python / Django scripting

Generate ctags:
ctags --languages=Python -R --exclude=IPython --exclude=test --exclude=tests

Plugins:
python-mode
ctrlp.vim
django_template_textobjects
nerdtree
patchreview-vim
tagbar
ultisnips
vim-commentary
vim-repeat
vim-sparkup
vim-surround
vim-textobj-user
vim-unimpaired
vim-visual-star-search


Config:
set nocompatible

" Command line history size 
set history=1000
set undolevels=1000

" Set to auto read when a file is changed from the outside
set autoread

" Turn backup off, since most stuff is in SVN, git et.c anyway...
set nobackup
set nowb
set noswapfile

" Return to last edit position when opening files (You want this!)
autocmd BufReadPost *
     \ if line("'\"") > 0 && line("'\"") <= line("$") |
     \   exe "normal! g`\"" |
     \ endif

syntax enable
set autoindent

set t_Co=256
let g:solarized_termcolors=16
colorscheme jellybeans


" Tab completion like bash
set wildmode=longest,list
" Tab completion like zch
"set wildmenu
"set wildmode=full

set shiftwidth=4 softtabstop=4 expandtab

" Jump between special words
filetype plugin on
runtime macros/matchit.vim

" Disable arrow keys
noremap  
noremap  
noremap  
noremap  

" Pathogen load
filetype off
call pathogen#infect()
call pathogen#helptags()

filetype plugin indent on
syntax on
let g:pymode_folding = 0
"let g:pymode_rope_vim_completion = 0
"let g:pymode_rope = 0
"let g:pymode_lint_write = 0
"let g:pymode_lint_onfly = 1
"let g:pymode_lint_cwindow = 0
let g:ropevim_extended_complete=1

nmap  :set number!
nmap  :PyLintAuto
set pastetoggle=

nnoremap  :!ctags -R

nmap  :NERDTreeToggle
nmap  :TagbarToggle

noremap   :cal VimCommanderToggle()

" SEARCH

" enable ack
set grepprg=ack\ --nogroup\ --column\ $*
set grepformat=%f:%l:%c:%m

" mutes search highlight and redraws screen
nnoremap   :nohlsearch

set hls

" show search matches as you type
set incsearch
set ignorecase
set smartcase

" NETRW

let s:split_width=24

"let g:netrw_menu=0
let g:netrw_liststyle='tree'

let NERDTreeIgnore = ['\.pyc$', '^tags$', 'nohup.out']
let NERDTreeChDirMode=2
let NERDTreeMinimalUI=1
let NERDTreeDirArrows=1

" EX MODE

" %% instead %:h
cnoremap  %% getcmdtype() == ':' ? expand('%:h').'/' : '%%'

" Fixing the & Command
nnoremap & :&&
xnoremap & :&&

" set path+=apps/
"set path+gtemplates/
"set path+=/usr/local/lib/python2.7/dist-packages/

" SPELL

" syn spell toplevel
set spell
" autocmd BufNewFile,BufRead * setlocal spell spelllang=en 
autocmd BufNewFile,BufRead * syn spell toplevel

set mouse=a

let g:clipbrdDefaultReg = '+'

" When I close a tab, remove the buffer
set nohidden


if filereadable(".vimrc")
    so .vimrc
endif