ActiveRecord like API for Python
之前看到 ActiveRecord 有一個很方便的功能: find_by_COLUMN,而 COLUMN 是那個 Table 裡的 columns。這用 Ruby 的 define_method 很好實做,當然 Python 也可以做到。下面是一段 POC (Prove of Concept) code:
執行結果:
Google 一下就可以找到一個跟 ActiveRecord API 類供的 Python SQL library:
ActiveModel - Python implementation of the ActiveRecord pattern as found in Ruby on Rails
# -*- coding: utf-8 -*-
from functools import partial
class Table(object):
# 假設 columns 已經在別的地方定義了,這裡只直接列在 list 裡
columns = [ 'id', 'name', 'subject' ]
@classmethod
def generate_find_by_methods(cls):
def find_by_column(name, value):
print 'find_by_%s(%s) called' % (name, repr(value))
# Do SQL
for column in cls.columns:
setattr(cls, 'find_by_%s' % column,
partial(find_by_column, column))
Table.generate_find_by_methods()
Table.find_by_id(1)
Table.find_by_name('Francis')
Table.find_by_subject('Test')
執行結果:
find_by_id(1) called
find_by_name('Francis') called
find_by_subject('Test') called
Google 一下就可以找到一個跟 ActiveRecord API 類供的 Python SQL library:
ActiveModel - Python implementation of the ActiveRecord pattern as found in Ruby on Rails
留言