Python中缺少动态查找器和方法 [英] Dynamic Finders and Method Missing in Python

查看:132
本文介绍了Python中缺少动态查找器和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Python中实现像Rails动态查找器之类的东西(对于
webapp / GAE)。动态发现者的工作方式如下:


  • 您的人有一些字段:姓名,年龄和电子邮件地址。

  • 假设你想查找所有名字为Robot的用户。



Person类有一个名为find_by_name的方法,它接收名称
并返回查询结果:

  @classmethod 
def find_by_name(cls,name):
返回Person.gql(WHERE name = :1),name).get()

不必为每个属性,我想
有一些像Ruby的method_missing,允许我这样做。



到目前为止,我已经看到了这两篇博文: http://blog.iffy.us/?p=43
http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm 但我想要
听听做什么是最合适的方式。

解决方案

这里真的不需要使用GQL - 它只是复杂化事项。这里有一个简单的实现:

$ p $ 类FindableModel(db.Model):
def __getattr __(self,name):
如果不是name.startswith(find_by_):
raise AttributeError(name)
field = name [len(find_by_):]
返回lambda值:self.all ().filter(field,value)

请注意,它返回一个Query对象,您可以调用.get(),.fetch()等等;这是更通用的,但如果你想要,你当然可以让它只返回一个实体。


I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this:

  • Your Person has some fields: name, age and email.
  • Suppose you want to find all the users whose name is "Robot".

The Person class has a method called "find_by_name" that receives the name and returns the result of the query:

 @classmethod
 def find_by_name(cls, name):
    return Person.gql("WHERE name = :1", name).get()

Instead of having to write a method like that for each attribute, I'd like to have something like Ruby's method_missing that allows me to do it.

So far I've seen these 2 blog posts: http://blog.iffy.us/?p=43 and http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm but I'd like to hear what's the "most appropiate" way of doing it.

解决方案

There's really no need to use GQL here - it just complicates matters. Here's a simple implementation:

class FindableModel(db.Model):
  def __getattr__(self, name):
    if not name.startswith("find_by_"):
      raise AttributeError(name)
    field = name[len("find_by_"):]
    return lambda value: self.all().filter(field, value)

Note that it returns a Query object, which you can call .get(), .fetch() etc on; this is more versatile, but if you want you can of course make it just return a single entity.

这篇关于Python中缺少动态查找器和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆