Python 中缺少动态查找器和方法 [英] Dynamic Finders and Method Missing in Python
问题描述
我正在尝试在 Python 中实现类似 Rails dynamic-finders 的东西(对于网络应用程序/GAE).动态查找器的工作方式如下:
I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this:
- 你的人有一些字段:姓名、年龄和电子邮件.
- 假设您要查找名称为Robot"的所有用户.
Person 类有一个名为find_by_name"的方法,它接收名称并返回查询结果:
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()
与其为每个属性都写一个这样的方法,我想有类似 Ruby 的 method_missing 之类的东西可以让我做到这一点.
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.
到目前为止,我已经看过这 2 篇博文:http://blog.iffy.us/?p=43 和http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm 但我会想听听最合适"的做法是什么.
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.
推荐答案
这里真的没有必要使用 GQL - 它只会使问题复杂化.这是一个简单的实现:
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)
请注意,它返回一个 Query 对象,您可以调用 .get()、.fetch() 等;这是更通用的,但如果你愿意,你当然可以让它只返回一个实体.
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屋!