Category Archives: Django

South, fake migrations

Ako imaš tablicu koja je već u bazi i tek onda si napravio migraciju sa Southom moraš napraviti inicijalnu migraciju bez promjene i onda napraviti novu migraciju.
Kada se to sve odrati potrebno je “fejkati” inicijalnu migraciju (jer već postoji u bazi)

1. python manage.py schemamigration APP_NAME --initial
2. napravi promjenu u models.py
3. python manage.py schemamigration APP_NAME --auto
4. python manage.py migrate APP_NAME 0001 --fake
5. python manage.py migrate APP_NAME

mod_wsgi automatic code reload

links:
Using mod_wsgi when developing Django sites.
modwsgi – Monitoring For Code Changes

modify wsgi.py
add:

import cms_dict.monitor
cms_dict.monitor.start(interval=1.0)

create monitor.py

import os
import sys
import time
import signal
import threading
import atexit
import Queue

_interval = 1.0
_times = {}
_files = []

_running = False
_queue = Queue.Queue()
_lock = threading.Lock()

def _restart(path):
    _queue.put(True)
    prefix = 'monitor (pid=%d):' % os.getpid()
    print >> sys.stderr, '%s Change detected to \'%s\'.' % (prefix, path)
    print >> sys.stderr, '%s Triggering process restart.' % prefix
    os.kill(os.getpid(), signal.SIGINT)

def _modified(path):
    try:
        # If path doesn't denote a file and were previously
        # tracking it, then it has been removed or the file type
        # has changed so force a restart. If not previously
        # tracking the file then we can ignore it as probably
        # pseudo reference such as when file extracted from a
        # collection of modules contained in a zip file.

        if not os.path.isfile(path):
            return path in _times

        # Check for when file last modified.

        mtime = os.stat(path).st_mtime
        if path not in _times:
            _times[path] = mtime

        # Force restart when modification time has changed, even
        # if time now older, as that could indicate older file
        # has been restored.

        if mtime != _times[path]:
            return True
    except:
        # If any exception occured, likely that file has been
        # been removed just before stat(), so force a restart.

        return True

    return False

def _monitor():
    while 1:
        # Check modification times on all files in sys.modules.

        for module in sys.modules.values():
            if not hasattr(module, '__file__'):
                continue
            path = getattr(module, '__file__')
            if not path:
                continue
            if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']:
                path = path[:-1]
            if _modified(path):
                return _restart(path)

        # Check modification times on files which have
        # specifically been registered for monitoring.

        for path in _files:
            if _modified(path):
                return _restart(path)

        # Go to sleep for specified interval.

        try:
            return _queue.get(timeout=_interval)
        except:
            pass

_thread = threading.Thread(target=_monitor)
_thread.setDaemon(True)

def _exiting():
    try:
        _queue.put(True)
    except:
        pass
    _thread.join()

atexit.register(_exiting)

def track(path):
    if not path in _files:
        _files.append(path)

def start(interval=1.0):
    global _interval
    if interval < _interval:         _interval = interval     global _running     _lock.acquire()     if not _running:         prefix = 'monitor (pid=%d):' % os.getpid()         print >> sys.stderr, '%s Starting change monitor.' % prefix
        _running = True
        _thread.start()
    _lock.release()

Ubuntu & Debian PostgreSQL setup

#File Locations:
Configuration files: /etc/postgresql/[version]/[cluster]/
Binaries: /usr/lib/postgresql/[version]
Data files: /var/lib/postgresql/[version]/[cluster]
# Instaliraj server i dodatni softvare
apt-get install postgresql
apt-get install postgresql-contrib
# Generiraj hr_HR locale
sudo locale-gen hr_HR.UTF-8
# Postavi da se na bazu može spojiti i lokalno pomoću šifre
vi /etc/postgresql/9.1/main/pg_hba.conf
local   all             all                                     password
# Za development, da se može spojiti na server preko TCP/IP protokola
host   all   all  0.0.0.0/0   password
i u postgresql.conf: listen_address = '*'
# Kreiraj superuser korisnika, pita za šifru
createuser -P -s -e myuser
# Kreiraj bazu
createdb -O myuser -E UTF8 -T template0 --locale=hr_HR.utf8 mydb
# Napravi restart PostgreSQL servisa
sudo /etc/init.d/postgresql restart

Django south

South je aplikacija za Django koja prati promjene Django Modela i zapisuje te promjene u bazu.
npr. model Korisnik ima polja: Ime i Prezime dužine 10 znakova.
Kasnije se pokaže da je to pre malo znakova.
Bez south aplikacije bi morali ručno promjeniti polja u bazi.
South nam omogućava da promjene vršimo direktno u modelima.

$ easy_install south

Naredba za instalaciju
Moramo dodati ‘south’ u INSTALLED_APPS u settings.py

$ python.py manage.py schemamigration app_name --initial

Napravimo inicijalnu migraciju, tj. snimimo postojeće stanje.

$ python.py manage.py syncdb

Moramo pokrenuti ‘syncdb’ jer south dodaje svoje tablice u bazu.
Redoslijed je bitan, jer ako pokrenemo syncdb prije schemamigration, syncdb ce zapisati tablice u bazu i south neće moći kreirati tablice, jer već postoje..

$ python.py manage.py migrate app_name

Naredba koja zapiše promjene modela u bazu. (Kreira ih, modificira, briše…)

$ python.py manage.py schemamigration app_name --auto

Nakon što napravimo promjene u Modelu pokrećemo south koji detektira razlike i zapisuje ih.

Django WSGI Apache

Kreirati projekt.com.conf i prebaciti ga u /etc/httpd/conf.d

Konfiguracija:

Listen 8000

WSGISocketPrefix /var/run/wsgi


ServerName gandalf.local

Alias /static /vault0/podaci/_razvoj/webapps/is42/static
Alias /admin_media  /home/myuser/Django-1.1/django/contrib/admin/media

WSGIDaemonProcess is.dizajnzona42.com display-name=%{GROUP} python-path=/vault0/podaci/_razvoj/webapps/is42:/vault0/podaci/_razvoj/webapps/venv/is.dizajnzona42.com/lib/python2.7/site-packages
WSGIProcessGroup is.dizajnzona42.com

WSGIScriptAlias / /vault0/podaci/_razvoj/webapps/is42/is42/wsgi.py


    
        Order deny,allow
        Allow from all
    



 

Django virtualenv setup

Imamo aplikacije koje koriste različite verzije Djanga, kako napraviti da se sve vrte na istom serveru?
Pomoću virtualenv softvera.

Instaliramo python setuptools.

$ yum install python-setuptools

Nakon što smo instalirali setuptools, instaliramo virtualenv.

$ easy_install virtualenv

Preselimo se u direktorij gdje cemo pospremati virtualne instalacije.

$ cd ~/webapps/venv
$ virtualenv --no-site-packages projekt.com
$ source projekt.com/bin/activate
(projekt.com)$ pip install django
(projekt.com)$ deactivate

Ako trebamo verziju djanga koju nije moguce instalirati preko pipa, onda je procedura da se instalacijski paket skine sa interneta i standardnom procedurom instalira u virtualno okružje.
npr.

$ source projekt.com/bin/activate
(projekt.com)$ pip install django
(projekt.com)$ wget https://www.djangoproject.com/download/1.5c1/tarball/
(projekt.com)$ tar xzvf Django.tar.gz
(projekt.com)$ cd Django
(projekt.com)$ python setup.py install