Djangoでpostgresを使うまでのメモ

環境はMacOSX 10.7.4
Djangoは普段から使ってるけど、いつもsqlite3かmysqlなので、postgresを使うまでの環境設定のメモ


1. Postgresをhomebrewでインストール

なんかdependencyでいろいろ入った

$ PYTHON=/usr/local/bin/python brew install postgresql
==> Installing postgresql dependency: readline
==> Downloading http://ftpmirror.gnu.org/readline/readline-6.2.tar.gz
######################################################################## 100.0%
==> Downloading patches
######################################################################## 100.0%
######################################################################## 100.0%
==> Patching
patching file vi_mode.c
patching file callback.c
patching file support/shobj-conf
patching file patchlevel
==> ./configure --prefix=/usr/local/Cellar/readline/6.2.2 --mandir=/usr/local/Cellar/readline/6.2.2/share/man --infodir=/usr/local/Cellar/readline/6.2.2/share/info --enable-multibyte
==> make install
==> Caveats
This formula is keg-only, so it was not symlinked into /usr/local.

OS X provides the BSD libedit library, which shadows libreadline.
In order to prevent conflicts when programs look for libreadline we are
defaulting this GNU Readline installation to keg-only.

Generally there are no consequences of this for you.
If you build your own software and it requires this formula, you'll need
to add its lib & include paths to your build variables:

    LDFLAGS  -L/usr/local/Cellar/readline/6.2.2/lib
    CPPFLAGS -I/usr/local/Cellar/readline/6.2.2/include
==> Summary
/usr/local/Cellar/readline/6.2.2: 30 files, 1.6M, built in 16 seconds
==> Installing postgresql dependency: ossp-uuid
==> Downloading ftp://ftp.ossp.org/pkg/lib/uuid/uuid-1.6.2.tar.gz
######################################################################## 100.0%
######################################################################## 100.0%==> ./configure --disable-debug --without-perl --without-php --without-pgsql --prefix=/usr/local/Cellar/ossp-uuid/1.6.2
==> make
==> make install
/usr/local/Cellar/ossp-uuid/1.6.2: 12 files, 336K, built in 20 seconds
==> Installing postgresql
==> Downloading http://ftp.postgresql.org/pub/source/v9.1.2/postgresql-9.1.2.tar.bz2
######################################################################## 100.0%
==> ./configure --disable-debug --prefix=/usr/local/Cellar/postgresql/9.1.2 --datadir=/usr/local/Cellar/postgresql/9.1.2/share/postgresql --docdir=/usr/local/Cellar/postgresql/9.1.2/share/do
==> make install-world
==> Caveats
# Build Notes

If builds of PostgreSQL 9 are failing and you have version 8.x installed,
you may need to remove the previous version first. See:
  https://github.com/mxcl/homebrew/issues/issue/2510

To build plpython against a specific Python, set PYTHON prior to brewing:
  PYTHON=/usr/local/bin/python  brew install postgresql
See:
  http://www.postgresql.org/docs/9.1/static/install-procedure.html

# Create/Upgrade a Database

If this is your first install, create a database with:
  initdb /usr/local/var/postgres

To migrate existing data from a previous major version (pre-9.1) of PostgreSQL, see:
  http://www.postgresql.org/docs/9.1/static/upgrading.html

# Start/Stop PostgreSQL

If this is your first install, automatically load on login with:
  mkdir -p ~/Library/LaunchAgents
  cp /usr/local/Cellar/postgresql/9.1.2/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
  launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

If this is an upgrade and you already have the homebrew.mxcl.postgresql.plist loaded:
  launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
  cp /usr/local/Cellar/postgresql/9.1.2/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
  launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

Or start manually with:
  pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

And stop with:
  pg_ctl -D /usr/local/var/postgres stop -s -m fast

# Loading Extensions

By default, Homebrew builds all available Contrib extensions.  To see a list of all
available extensions, from the psql command line, run:
  SELECT * FROM pg_available_extensions;

To load any of the extension names, navigate to the desired database and run:
  CREATE EXTENSION [extension name];

For instance, to load the tablefunc extension in the current database, run:
  CREATE EXTENSION tablefunc;

For more information on the CREATE EXTENSION command, see:
  http://www.postgresql.org/docs/9.1/static/sql-createextension.html
For more information on extensions, see:
  http://www.postgresql.org/docs/9.1/static/contrib.html

# Other

Some machines may require provisioning of shared memory:
  http://www.postgresql.org/docs/current/static/kernel-resources.html#SYSVIPC

To install postgresql (and ossp-uuid) in 32-bit mode:
   brew install postgresql --32-bit

If you want to install the postgres gem, including ARCHFLAGS is recommended:
    env ARCHFLAGS="-arch x86_64" gem install pg

To install gems without sudo, see the Homebrew wiki.
==> Summary
/usr/local/Cellar/postgresql/9.1.2: 2742 files, 36M, built in 2.8 minutes

dbの作成

$ initdb -A trust /usr/local/var/postgres -E utf8
The files belonging to this database system will be owned by user "yuhei".
This user must also own the server process.

The database cluster will be initialized with locale ja_JP.UTF-8.
initdb: could not find suitable text search configuration for locale ja_JP.UTF-8
The default text search configuration will be set to "simple".

creating directory /usr/local/var/postgres ... ok
creating subdirectories ... ok
selecting default max_connections ... 10
selecting default shared_buffers ... 800kB
creating configuration files ... ok
creating template1 database in /usr/local/var/postgres/base/1 ... ok
initializing pg_authid ... ok
initializing dependencies ... ok
creating system views ... ok
loading system objects' descriptions ... ok
creating collations ... ok
creating conversions ... ok
creating dictionaries ... ok
setting privileges on built-in objects ... ok
creating information schema ... ok
loading PL/pgSQL server-side language ... ok
vacuuming database template1 ... ok
copying template1 to template0 ... ok
copying template1 to postgres ... ok

Success. You can now start the database server using:

    postgres -D /usr/local/var/postgres
or
    pg_ctl -D /usr/local/var/postgres -l logfile start

ログインと同時に起動させる設定

$ cd ~/Library/LaunchAgents/
$ cp /usr/local/Cellar/postgresql/9.1.2/homebrew.mxcl.postgresql.plist  ./

手動で起動、停止する場合のコマンド

$ pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
$ pg_ctl -D /usr/local/var/postgres stop -s -m fast

つないでみる

macのログインユーザー/パスワードで接続される模様

$ psql postgres
psql (9.1.2)
Type "help" for help.

テスト用のユーザーを作成

postgresのインストールでcreateuserという名前のコマンドが/usr/local/binに作成されている

$ createuser dev -P
Enter password for new role: 
Enter it again: 
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) n

db作成

postgresのインストールでcreatedbという名前のコマンドが/usr/local/binに作成されている

$ createdb -U dev -E utf8 -O dev devdb -T template0

djangoの設定


ドライバのインストール

pip install psycopg2 


setting.pyの設定例

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', 
        'NAME': 'devdb',                    
        'USER': 'dev',            
        'PASSWORD': 'dev',             
        'HOST': 'localhost',                
        'PORT': '5432',  
   }
}


適当なmodels.py

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)


class Author(models.Model):
    name = models.CharField(max_length=100)


class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author)
    pub_date = models.DateTimeField()
    mod_date = models.DateTimeField()

syncdbでテーブルが作成

$ python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log
Creating table app_blog
Creating table app_author
Creating table app_entry

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): no
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

Process finished with exit code 0

consoleからモデルをさわってみる

$ python manage.py shell
>>> from app.models import *
>>> Blog.objects.create(name='brainstorm')
<Blog: Blog object>
>>> Blog.objects.all()
[<Blog: Blog object>]

問題なさそう