2

由于之前还不清楚,我发布了这个场景:

class Scraper:
    def __init__(self,url):
      self.start_page = url

    def parse_html(self):
      pass

    def get_all_links(self):
      pass

    def run(self):
      #parse html, get all links, parse them and when done...
      return links

现在在像 rq 这样的任务队列中

from rq import Queue
from worker import conn

q = Queue(connection=conn)
result = q.enqueue(what_function, 'http://stackoverflow.com')

我想知道这个 what_function 是什么?我记得 Django 对他们的 CBV 做了类似的事情,所以我使用了这个类比,但不是很清楚。


我有一个像

class A:
    def run(self,arg):
        #do something

我需要将它传递到任务队列,所以我可以做类似的事情

a = A()
b = a.run
# q is the queue object
q.enqueue(b,some_arg)

我想知道还有什么其他方法可以做到这一点,例如,Django 在他们的基于类的视图中做到这一点,

class YourListView(ListView):
    #code for your view

最终作为函数传递

your_view = YourListView.as_view()

它是如何完成的?

编辑:详细地说,django 的基于类的视图被转换为函数,因为模式函数中的参数需要一个函数。同样,您可能有一个接受以下参数的函数

task_queue(callback_function, *parameters):
    #add to queue and return result when done

但是 callback_function 的功能可能主要在一个类中实现,该类有一个 run() 方法,通过该方法运行进程。

4

1 回答 1

4

我想你在描述一个classmethod

class MyClass(object):
    @classmethod
    def as_view(cls):
        '''method intended to be called on the class, not an instance'''
        return cls(instantiation, args)

可以这样使用:

call_later = MyClass.as_view

后来叫:

call_later()

最常见的是,类方法用于实例化一个新实例,例如dictfromkeys类方法:

dict.fromkeys(['foo', 'bar'])

返回一个新的 dict 实例:

{'foo': None, 'bar': None}

更新

在你的例子中,

result = q.enqueue(what_function, 'http://stackoverflow.com')

你想知道what_function可以去那里。我在 RQ 主页上看到了一个非常相似的例子。那必须是你自己的实现。这将是你可以用你的代码调用的东西。它只会用那个参数调用一次,所以如果使用一个类,你__init__应该看起来更像这样,如果你想使用Scraper你的what_function替换:

class Scraper:
    def __init__(self,url):
        self.start_page = url
        self.run()
        # etc...

如果要使用类方法,可能如下所示:

class Scraper:
    def __init__(self,url):
        self.start_page = url

    def parse_html(self):
        pass

    def get_all_links(self):
        pass

    @classmethod
    def run(cls, url):
        instance = cls(url)
        #parse html, get all links, parse them and when done...
        return links

然后你what_function会是Scraper.run

于 2014-09-21T04:55:31.040 回答