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

Oct 10, 2011

Проверка состояния сервера и перезапуск в случае необходимости

Можно воспользоваться Supervisor или чем-то подобным, но для небольших проектов достаточно crontab:
crontab -e
Например, для проверки memcached каждую минуту:
*/1     *       *       *       *       netstat -ln | grep ":11211 " | wc -l | awk '{if ($1 == 0) system("/etc/init.d/memcached start") }'

Oct 5, 2011

Signals registration

Best place for Django signals is app/signals.py file. This snippet imports signal modules from all installed apps.
from importlib import import_module
from django.conf import settings

for app in settings.INSTALLED_APPS:
    try:
        import_module( 'signals', app)
    except ImportError as e:
        print 'Failed to import "%s", reason: %s' % (app, str(e)))
Original: http://djangosnippets.org/snippets/2561/

Sep 23, 2011

django_graceful

django_graceful - Плавный перезапуск FastCGI-процессов

Его идея проста: настройки FastCGI хранятся в файле settings.py, а для управления FastCGI-процессами используются простые команды из manage.py. Эти команды поддерживают несколько параллельно запущенных экземпляров FastCGI-сервера и позволяют переключать веб-сервер между ними с помощью символической ссылки на файл unix-socket-а, то есть без перезапуска веб-сервера.

Sep 20, 2011

Git housekeeping

git fsck # Verifies the connectivity and validity of the objects in the database
git prune # Prune all unreachable objects from the object database
git gc # Cleanup unnecessary files and optimize the local repository
git pack # Pack unpacked objects in a repository
git prune-packed # Remove extra objects that are already in pack files

Memcached telnet commands

telnet localhost 11211

flush_all # Flashes the entire cache
stats # General statistics
stats slabs # Memory statistics
stats memory # Memory statistics
stats items # Higher level statistics
quit # Quit the telnet interface

Sep 14, 2011

Python property object has getter, setter, and deleter methods

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Sep 1, 2011

Unix as IDE. Сетевые утилиты

netstat

Показывает сетевые соединения (входящие/исходящие), таблицу маршрутизации, статистику по сетевым интерфейсам и т.д.
netstat -at # Список всех открытых портов (TCP)
netstat -au # Список всех открытых портов (UDP)
netstat -nagrep 22 # Список открытых хостов по порту
netstat -lt # Список только прослушиваемых портов (TCP)
netstat -s # Статистика по всем открытым портам
# Подробное отображение списка с открытыми портами - добавлен PID и имя процессов
netstat -p 
# Команда для просмотра открытых TCP/UDP портов с именами процессов
# (может понадобиться root-доступ)
netstat -ltupn 
# Список подключенных хостов
netstat -lantp | grep ESTABLISHED |awk '{print $5}' | awk -F: '{print $1}' | sort -u

ss

Позволяет просматривать информацию об используемых сокетах в системе. Эта команда обладает схожим функционалом c netstat, но есть и уникальные возможности. Например возможность фильтровать вывод по установленным соединениям с определенным портом.
ss -p  # Список процессов, использующие соединения в данный момент
ss -l # Список сокетов в режиме прослушивания
 # Пример фильтра - список всех соединений к порту 80
ss -o state established '( dport = :www or sport = :www )'

lsof

Отображает процессы, которые работают с определенным файлом или сокетом.
lsof -i # Список всех сетевых соединений
lsof -i :80 # Список процессов, работающих с портом 80

netcat

Позволяет передавать/принимать данные через TCP/UDP соединения.
# Передача файла
nc -l 1234 > file # На принимающей стороне
nc localhost 1234 < file # На отправляющей стороне

# Или отдавать файл любому подключившемуся
nc -l 1234 < file # На передающей стороне
nc localhost 1234 > file # На принимающей стороне

nmap

Cканирует IP-сети с любым количеством объектов, определяет состояние объектов сканируемой сети (портов и соответствующих им служб).
Для работы большинства возможностей nmap требуется права root. Разработчики nmap предлагают хост scanme.nmap.org для тестового сканирования.
# Получение информации об портах удаленного хоста и определение операционной системы
sudo nmap -sS -P0 -sV -O scanme.nmap.org 
# scanme.nmap.org – сканируемый хост, может быть: IP, имя хоста или подсеть
# -sS – TCP SYN сканирование (полуоткрытое)
# -P0 – отключение ICMP сканирования
# -sV – определение сервисов, запущенных на открытых портах
# -O – определение версии операционной системы

# Пингование диапазона адресов
sudo nmap -sP -v "192.168.1.*" 
sudo nmap -sP -v 192.168.1.0/24
sudo nmap -sP -v 192.168.1.1-20
# -sP - ping-сканирование

sudo nmap -sT -p 22 scanme.nmap.org # Проверка одного порта
sudo nmap -sT -p 20-110 scanme.nmap.org # Проверка диапазона портов
# -sT - TCP-сканирование

sudo nmap -sS scanme.nmap.org -D 8.8.8.8 # Cкрыть свой IP адрес

nmap localhost # Определения открытых портов на локальной машине нужно выполнить

fuser

Принудительное закрытие определенного порта
fuser -k 80/tcp

DNS lookup

http://greendail.ru/node/474
dig  www.podkova.by  +trace

nslookup podkova.by
# or using google ns server
nslookup podkova.by 8.8.8.8

tshark

You can use the specific HTTP header display filters to show either just the request headers, just the response headers or both.
tshark tcp port 80 -V -R "http.request || http.response"

curl

curl \
  -s -u <USER>:<API_TOKEN> \
  -d '{ "id": "ce9d27f8", "method": "getContact", "params": [77777] }' \
  https://app01.nutshell.com/api/v1/json | python -m json.tool

# with Headers
curl -H 'Authorization: OAuth <SECURE_TOKEN>' https://blabla.com/api/?var=foo

# GET request (-G) with data (-d)
curl -G \
  -d 'access_token=77777777777777777777' \
  -d 'page=1' \ 
  -d 'per_page=1' \
  https://api.nimble.com/api/v1/contacts/list
How to test request to django-tastypie API using ApiKey:
curl \
  -H 'Authorization: ApiKey someusername:83a82c7941f6dba06510541c71505c71a0625741' \
  -H 'Content-Type:application/json' \
  -X PATCH -d '{"first_name" : "bob","last_name" : "marley"}' \
  http://127.0.0.1:8000/api/profile/