如何使用Luigi

时间:2019-02-15 01:56:48

标签: python luigi

我意识到我可能需要使用动态需求来完成以下任务,但是我无法将其束之高阁。

目标是使用Luigi生成数据并将其添加到数据库,而无需提前知道将要生成什么数据。

使用mongodb进行以下示例:

import luigi
from uuid import uuid4
from luigi.contrib import mongodb
import pymongo

# Make up IDs, though in practice the IDs may be generated from an API
class MakeID(luigi.Task):
    def run(self):
        with self.output().open('w') as f:
            f.write(','.join([str(uuid4()) for e in range(10)]))

    # Write the data to file
    def output(self):
        return luigi.LocalTarget('data.csv')


class ToDataBase(luigi.Task):
    def requires(self):
        return MakeID()

    def run(self):
        with self.input().open('r') as f:
            ids = f.read().split(',')

        # Add some fake data to simulate generating new data 
        count_data = {key: value for value, key in enumerate(ids)}
        # Add data to the database
        self.output().write(count_data)

    def output(self):
        # Attempt to read non-existent file to get the IDs to check if task is complete
        with self.input().open('r') as f:
            valid_ids = f.read().split(',')
        client = pymongo.MongoClient('localhost',
                                     27017,
                                     ssl=False)

        return mongodb.MongoRangeTarget(client,
                                        'myDB',
                                        'myData',
                                        valid_ids,
                                        'myField')


if __name__ == '__main__':
    luigi.run()

目标是获取数据,对其进行修改,然后将其添加到数据库中。

上面的代码在运行时失败,因为output的{​​{1}}方法在ToDataBase方法之前运行,因此当函数可以访问输入时,输入尚不存在。无论如何,我仍然需要检查以确保已将数据添加到数据库中。

这个github issue与我要寻找的内容很接近,尽管正如我提到的那样,实际上我还无法弄清楚此用例的动态需求。

1 个答案:

答案 0 :(得分:0)

解决方案是创建第三个任务(在示例Dynamic中),该任务将产生等待动态输入并将依赖项作为参数而不是requires方法的任务。

class ToDatabase(luigi.Task):
    fp = luigi.Parameter()

    def output(self):
        with open(self.fp, 'r') as f:
            valid_ids = [str(e) for e in f.read().split(',')]
        client = pymongo.MongoClient('localhost', 27017, ssl=False)
        return mongodb.MongoRangeTarget(client, 'myDB', 'myData',
                                        valid_ids, 'myField')

    def run(self):
        with open(self.fp, 'r') as f:
            valid_ids = [str(e) for e in f.read().split(',')]
        self.output().write({k: 5 for k in valid_ids})


class Dynamic(luigi.Task):
    def output(self):
        return self.input()

    def requires(self):
        return MakeIDs()

    def run(self):
        yield(AddToDatabase(fp=self.input().path))