createの改造

まずはcreateが呼ばれたときに、SQLAlchemyも呼び出すようにする。

phone.py

from phonebook.model import meta
 
 
    @restrict('POST')
    @validate(schema = NewPhoneForm(), form = 'new')
    def create(self):
        phone = model.Phone()
        for k, v in self.form_result.items():
            setattr(phone, k, v)

        p = jsonpickle.Pickler()
        self.mc.set(phone.id, p.flatten(phone))

        name = model.Name()
        name.phone_id = phone.id
        name.name = phone.name
        meta.Session.add(name)
        meta.Session.commit()

        response.status_int = 302
        response.headers['location'] = h.url_for(controller = 'phone',
                                                 action = 'view',
                                                 id = phone.id)
        return "Moved temporarily"

確認

フォームからデータを登録し、上記createを呼び出してみた後にsqlalchemyを操作して確認してみる。

$ paster shell
Pylons Interactive Shell
Python 2.6.4 (r264:75706, Dec 28 2009, 15:52:45)
[GCC 4.3.4]

  All objects from phonebook.lib.base are available
  Additional Objects:
  mapper     -  Routes mapper object
  wsgiapp    -  This project's WSGI App instance
  app        -  paste.fixture wrapped around wsgiapp

>>> from phonebook.model import meta
>>> names = meta.Session.query(model.Name).all()
23:46:23,625 INFO  [sqlalchemy.engine.base.Engine.0x...3110] BEGIN
23:46:23,629 INFO  [sqlalchemy.engine.base.Engine.0x...3110] SELECT name.id AS name_id, name.phone_id AS name_phone_id, name.name AS name_name
FROM name
23:46:23,629 INFO  [sqlalchemy.engine.base.Engine.0x...3110] []
>>> names
[<phonebook.model.Name object at 0xbef1d0>]
>>> names[0]
<phonebook.model.Name object at 0xbef1d0>
>>> names[0].id
1
>>> names[0].phone_id
u'3df3c13128024f3d881d72128fc807fa'
>>> names[0].name
u'333333333'
>>> 

→gitコミット先: http://github.com/masayang/pylons-mdb/commit/95e21747e0c0afcbc58b80a132fddf6e612774c9


目次に戻る