457475451 发表于 2015-12-2 08:51:40

python下申明式的对象关系DB映射器--Pony

  
  之前看到了Sails.js的waterline提供了声明式的关系型对象与DB的映射器,惊为天人,可以说是极大地提升了效率。
  利用waterline的对象关系模型,用户可以直接使用javascript语言定义关系型的数据库,也就是说,我们不再需要像在java环境中那样声明一个个model,然后具体的关系操作还需要用户在业务逻辑中代码处理,而是提供了关系型的申明方式来创建model,支持one way relation, one-one relation, one-many relation, many-many relation。其语法如下:
  one way relation:



#myApp/api/models/pet.js
module.exports = {
attributes: {
name:'STRING',
color:'STRING'
}
}


#myApp/api/models/user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
pony:{
model: 'pet'
}
}
}
  one-many relation:



#myApp/api/models/pet.js
module.exports = {
attributes: {
name:'STRING',
color:'STRING',
owner:{
model:'user'
}
}
}

#myApp/api/models/user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
pets:{
collection: 'pet',
via: 'owner'
}
}
}
  还有 many-many relation:



#myApp/api/models/pet.js
module.exports = {
attributes: {
name:'STRING',
color:'STRING',
// Add a reference to User
      owners: {
collection: 'user',
via: 'pets',
dominant:true
}
}
}
#myApp/api/models/user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
// Add a reference to Pet
      pets:{
collection: 'pet',
via: 'owners'
}
}
}
  可以看到,所有的数据库关系都通过了对象model定义好了,同时还支持流水线式(waterline)的操作方式:



User.find().populate('pets').exec(function(err,r){console.log(r.toJSON())});
//以下为返回的json
{ pets:
[ { name: 'Pinkie Pie',
color: 'pink',
id: 2,
createdAt: Tue Feb 11 2014 17:58:04 GMT-0600 (CST),
updatedAt: Tue Feb 11 2014 17:58:04 GMT-0600 (CST),
owner: 1 },
{ name: 'Applejack',
color: 'orange',
id: 4,
createdAt: Tue Feb 11 2014 18:02:58 GMT-0600 (CST),
updatedAt: Tue Feb 11 2014 18:02:58 GMT-0600 (CST),
owner: 1 } ],
name: 'Mike',
age: 21,
createdAt: Tue Feb 11 2014 17:49:04 GMT-0600 (CST),
updatedAt: Tue Feb 11 2014 17:49:04 GMT-0600 (CST),
id: 1 }

  
  眼见着javascript生态环境一片欣欣向荣,不得不感叹我大python却无如此激情洋溢的框架,不禁扼腕。于是打算自己开创一个,却由于水平和时间所限,至今任然没开始动工,只是开了个repo在github。
  今天偶然发现了一个python的package,名叫Pony,其功能与waterline相当,而且整个生态环境更加友好,还提供了UI工具供开发者使用。
  
  
  
  参考:
  1. Pony ORM官网:http://ponyorm.com/
  2. Pony Demo:http://www.blog.pythonlibrary.org/2014/07/21/python-101-an-intro-to-pony-orm/
  3. Pony github: https://github.com/ponyorm/pony
  4. Pony Docs: http://doc.ponyorm.com/
  5. Pony Editor: https://editor.ponyorm.com/
  
页: [1]
查看完整版本: python下申明式的对象关系DB映射器--Pony