Jul 31, 2012

Do you check HTTPS certificates in your API clients?

  • All browsers use a ‘certificate store’ which contains the list of trusted root CAs.
  • The certificate store can either be provided by the OS, or by the browser.
  • On Windows, Chrome and IE use the operating-system provided certificate store. So they have the same points of trust. However, this means that the trust list is governed by the OS vendor, not the browser. I’m not sure how often this list is updated for Windows XP, which is still used by 50% of the world’s internet users.
  • On Mac, Chrome and Safari use the operating system provided store.
  • On Linux, there is no operating system provided certificate store  (see /etc/ssl/certs), so each browser maintains its own certificate store, with its own set of roots. 
  • Firefox, on all platforms (I believe, I might be wrong on this) uses its own certificate store, independent of the operating system store.
  • Finally, on mobile devices, everyone has their own certificate store. I’d hate to guess at how many there are or how often they are updated.

From comments:
"Python2.7's standard urllib2 module does not validate server certificates. Instead, we recommend using the "requests" or "urllib3" modules in python2, or the standard http.client.HTTPSConnection class in python3, and giving them a reasonable list of CA roots" 

Jul 30, 2012

Python 3.1 unittest2 framework new features

skip, skipIf and skipUnless decorators
class MyTestCase(unittest.TestCase):

    @unittest.skip("demonstrating skipping")
    def test_nothing(self):
        self.fail("shouldn't happen")

    @unittest.skipIf(mylib.__version__ < (1, 3),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

    @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        # windows specific testing code
        pass
expectedFailure decorator
class ExpectedFailureTestCase(unittest.TestCase):
    @unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "broken")

Jul 25, 2012

Django model visualization, dependency graph generator, call graphs

django-command-extensions - model visualization with pygraphviz:
pip install django-extensions
pip install pygraphviz

# add 'django_extensions' to INSTALLED_APPS

# all models from INSTALLED_APPS (django too)
./manage.py graph_models -a -g -o my_project.png  

# just two apps: emailing and localization 
./manage.py graph_models -g -e -l dot -o my_project.png emailing localization

# all project packages (without django; assumed packages in apps folder
./manage.py graph_models -g -e -l dot -o my_project.png  `ls -ld apps/* | grep "^d"|awk '{print $9}'| sed s/'apps\/'// | xargs`

django-detect-cyclic - application to detect cyclic imports. With this application you can analyze the dependence of your applications
pycallgraph - a Python module that creates call graphs for Python programs

snakefood - a dependency graph generator for Python source code

filtering and clustering dependencies
sfood /my_project/apps -i | sfood-cluster -f clusters | sfood-graph > my_package.dot
dot -Tpng -Ktwopi -O my_package.dot


Pyreverse - analyses Python code and extracts UML class diagrams and package dependencies
sudo apt-get install pylint
pyreverse -o png -A -s 0 -a 0 -k  apps/designer/ apps/core apps/company/ --ignore=migrations,tests,tests.py
pyreverse -o png --ignore=migrations,tests apps/interiors/

Gprof2Dot - Convert profiling output to a dot graph. dependencies
Python cProfile (formerly known as lsprof)
python -m cProfile -o output.pstats path/to/your/script arg1 arg2
gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png

Jul 19, 2012

Clone detection in python


Полезности для GIT

http://klen.github.com/some-git-things-ru.html

Алиас для более компактного git status:
$ git config --global alias.st 'status -sb' 
$ git st


Алиас для редактирования последнего коммита:
$ git config --global alias.amend 'commit --amend -C HEAD' 
$ git amend


Алиас для отмены последнего коммита:
$ git config --global alias.undo 'reset --soft HEAD^' 
$ git undo


Предпочитаемый мной вывод diff:
$ git config --global alias.diff 'diff --word-diff' 
$ git undo


«Визуальная» история веток в консоли:
$ git config --global alias.hist "log --pretty=format:'%Cred%h%Creset %ad | %Cgreen%s%d%Creset [%an]' --graph --date=short"


Удобная работа с Git-Flow:
$ git config --global alias.hotfix 'flow hotfix' 
$ git config --global alias.feature 'flow feature' 
$ git config --global alias.release 'flow release'


Автоматическая коррекция опечаток во вводимых командах:
$ git config --global help.autocorrect 1 
$ git comit 
$ git bronch


Автоматическая запись разрешенных мердж конфликтов, для будущего использования:
$ git config --global rerere.enabled 1


Получение веток с не влитыми данными:
$ git branch --no-merged


Список коммитов в ветке branchA отсуствующих в ветке branchB:
$ git log branchA ^branchB


Многие используют баш функцию __git_ps1 для вывода названия текущей ветки, но не все знают, что ее можно сделать более информативной.
# In your .bashrc or .profile: 
 GIT_PS1_SHOWDIRTYSTATE=1 
 GIT_PS1_SHOWSTASHSTATE=1 
 $ (develop *$):

Jul 12, 2012

Varnish Cache - caching HTTP reverse proxy

Varnish Cache is a web application accelerator also known as a caching HTTP reverse proxy. You install it in front of any server that speaks HTTP and configure it to cache the contents.

futures

Backport of the concurrent.futures package from Python 3.2
http://pypi.python.org/pypi/futures/

Отправка бесплатного sms сообщения в linux

http://habrahabr.ru/post/147583/

MaxMind GeoIP и GeoIPCity на ур-не nginx

http://markeev.labwr.ru/2012/07/maxmind-geoip-geoipcity-nginx.html


Установка бесплатной базы maxmind с данными о городах
1. Настраиваем nginx

sudo vim /etc/nginx/nginx.conf

http {
    geoip_city /usr/local/share/GeoIP/GeoLiteCity.dat;
    ...

2. В fastcgi_params добавляем

sudo vim /etc/nginx/fastcgi_params

### SET FASTCGI Variables ###
fastcgi_param GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code;
fastcgi_param GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3;
fastcgi_param GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name;
fastcgi_param GEOIP_REGION $geoip_region;
fastcgi_param GEOIP_CITY $geoip_city;
fastcgi_param GEOIP_POSTAL_CODE $geoip_postal_code;
fastcgi_param GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code;
fastcgi_param GEOIP_LATITUDE $geoip_latitude;
fastcgi_param GEOIP_LONGITUDE $geoip_longitude;

для uwsgi соответственно

sudo vim /etc/nginx/uwsgi_params

### SET UWSGI Variables ###
uwsgi_param GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code;

3. Качаем лайт базу (безвозмездно, значит даром)

wget -c http://www.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

gunzip GeoLiteCity.dat.gz

куда-нибудь в /usr/local/share/GeoIP/

4. Ставим пакеты - не знаю, когда это нужно, т.к. у меня на убунте и федоре уже стояли.

sudo apt-get install geoip-bin libgeoip-dev libgeoip1

5. Перезапускам nginx

6. Теперь можно использовать переданные модулем nginx заголовки:

GEOIP_CITY
GEOIP_CITY_CONTINENT_CODE
GEOIP_CITY_COUNTRY_CODE
GEOIP_CITY_COUNTRY_CODE3
GEOIP_CITY_COUNTRY_NAME
GEOIP_LATITUDE
GEOIP_LONGITUDE
GEOIP_POSTAL_CODE
GEOIP_REGION

Вот пример данных из лайт базы для моего рабочего IP
'GEOIP_CITY': '',
'GEOIP_CITY_CONTINENT_CODE': 'EU',
'GEOIP_CITY_COUNTRY_CODE': 'RU',
'GEOIP_CITY_COUNTRY_CODE3': 'RUS',
'GEOIP_CITY_COUNTRY_NAME': 'Russian Federation',
'GEOIP_LATITUDE': '60.0000',
'GEOIP_LONGITUDE': '100.0000',
'GEOIP_POSTAL_CODE': '',
'GEOIP_REGION': ''

Не очень точно, да?
Использование платных версий Maxmind ДБ
Для загрузки баз воспользуйся логопасом, у вас ведь есть подписка MaxMind? http://www.maxmind.com/app/account. Загрузить БД можно по адресу: http://www.maxmind.com/app/download_files. Думаю, опытный пират найдет способ скачать платную версию MaxMind с rutracker.org, но я ни коим образом не поощряю подобное поведение ;).

1. GeoIP Country binary database - база данных стран

http {
    geoip_country GeoIP.dat;
    ...

Доступные параметры:

fastcgi_param GEOIP_COUNTRY_CODE $geoip_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name;

2. GeoIP City binary database - база данных городов

http {
    geoip_city /usr/local/share/GeoIP/GeoIPCity.dat;
    ...

Пример ответа для того же IP
'GEOIP_CITY': 'Moscow',
'GEOIP_CITY_CONTINENT_CODE': 'EU',
'GEOIP_CITY_COUNTRY_CODE': 'RU',
'GEOIP_CITY_COUNTRY_CODE3': 'RUS',
'GEOIP_CITY_COUNTRY_NAME': 'Russian Federation',
'GEOIP_LATITUDE': '55.7522',
'GEOIP_LONGITUDE': '37.6156',
'GEOIP_POSTAL_CODE': '',
'GEOIP_REGION': '48'

Basic access authentication implementation. Django 1.4

http://pydanny.com/simple-http-basic-auth-wall.html

# Add to the bottom of your wsgi.py file
# Don't forget to add barrel to your requirements!
from barrel import cooper

REALM = "PRIVATE"
USERS = [('spam', 'eggs')]

application = cooper.basicauth(users=USERS, realm=REALM)(get_wsgi_application())

Jul 11, 2012

Pgtune - postgresql.conf tuning wizard

pgtune takes the wimpy default postgresql.conf and expands the database server to be as powerful as the hardware it's being deployed on
sudo apt-get install pgtune
pgtune -i /etc/postgresql/8.4/main/postgresql.conf -T Web -c 100 -M 96000000

Jul 4, 2012

Django cron job

http://pypi.python.org/pypi/django-cronjobs in cron.py

Templates caching

django-phased - Идея в том, чтобы рендерить шаблон в два прохода: сначала общие для всех закешированные куски шаблона, а потом специфичные для аутентифицированного пользователя части. Как уверяет автор, “this enables very fast generation of pages that have user-specific content”. Даже немного документации есть.

Python IDEs and Editors

Ninja