pyramid_peeweeでmysqlが動くことを確かめてみる。

準備の方が長いかもしれない。
環境はubuntu(10.10)

前提。

python,peewee,pyramid_peeweeが入っている。

mysqlのinstallなど

mysqlもインストールされていないので、mysqlのインストールから作業する。

$ sudo aptitude install mysql-server  libmysqlclient-dev python-dev

mysqlのパスワードを有効にするか尋ねられたので有効にして、password=fooと設置急いておく*1

peeweeでmysqlを使うためのモジュールをインストール(virtualenv環境)する。

$ pip search MySQL-python
MySQL-python              - Python interface to MySQL
$ pip install MySQL-python

pythonでMySQLdbがimportできるか確認

$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb

settings

日常的に使っている環境なので、bootの度にmysqldが立ち上がるのは嫌。
デフォルトでは立ち上がらないように設定する。

$ sudo update-rc.d -f mysql remove
## 復活されたい場合にはsudo update-rc.d mysql defaults

check

## ./bin/test-run.py

from datetime import datetime
from pyramid_peewee import get_management
import peewee as pw

Management = get_management()
Base = Management.get_base()

class SpellBook(Base):
    title = pw.CharField()
    published_at = pw.DateTimeField()

class Spell(Base):
    book = pw.ForeignKeyField(SpellBook)
    name = pw.CharField()

def main(dbtype, dbname, kwargs=None):
    print "dbtype:%s,  dbname:%s" % (dbtype, dbname)
    Management.setup(dbtype, dbname, **(kwargs or {}))
    Management.populate()
    
    book = SpellBook.create(title="foo", published_at=datetime.now())
    fire = Spell.create(book=book, title="fire")

    selected_book = SpellBook.select().where(id=1).get() == book
    print list(Spell.filter(book=selected_book))
    Management.drop_all()

if __name__ == "__main__":
    import sys
    if len(sys.argv) == 5: #fixme
        dbtype, dbname, kwargs = sys.argv[1], sys.argv[2], dict(user=sys.argv[3], passwd=sys.argv[4])
    elif len(sys.argv) < 3:
        dbtype, dbname = "sqlite", ":memory:", {}
    else:
        dbtype, dbname = sys.argv[1], sys.argv[2], {}
    main(dbtype, dbname, kwargs)

こんなコードを書いてあげて、動くか確かめる。

sqlite (memory)
$ python bin/test_run.py 
dbtype:sqlite,  dbname::memory:
[<__main__.Spell object at 0x2275d10>]

動いている。

sqlite file db
$ python bin/test_run.py  sqlite test.db 
dbtype:sqlite,  dbname:test.db
[<__main__.Spell object at 0xccfd10>]

動いている。

mysql

databaseの生成の部分から始めているので少しだけ長い。

$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 40
Server version: 5.1.49-1ubuntu8.1 (Ubuntu)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database peewee;
Query OK, 1 row affected (0.00 sec)

mysql> Bye
$ python bin/test_run.py mysql peewee root foo
dbtype:mysql,  dbname:peewee
[<__main__.Spell object at 0x7f9c7c66fc90>]

動いている。

*1:もちろん実際のpassword != foo