将 json 作为 celery 任务的一部分插入 postgres

Insert json into postgres as part of celery task

我是 Django 和 Celery 的新手。

高级别:

我正在开发 Django 应用程序。从管理页面使用将提交请求(工作)。这些请求将被发送到 Redis。然后 Celery 将轮询 Redis 并从队列中拉取一个作业。任务完成后,结果将存储在 postgres 中。

这是一个示例任务,用于通过 pytest.main() 启动一些测试。

# task for running tests by marker 
def run_tests_mark(test_marker):
    os.chdir('/service/lib/tests')
    # only allow specific strings to be passed in by the user
    if test_marker not in ['smoke', 'regression']: # update as more tages are introduced to the project
        return 'You have entered an invalid term. Please use either smoke of regression.'
    # run pytest command with self contained reporting
    results = pytest.main(['-v', '--json-report', '-m', test_marker])
    # TODO: after tests run send json report to postgres

代码将 运行 测试,但正如您在最后一条评论中看到的那样,我想获取结果 .json.report 并将其存储在 postgres 数据库中 [请注意我使用帮助获取 results]

生成的实际报告

这就是我感到困惑的地方。

我是否需要首先根据 pytest 生成的 json 报告中的所有键创建一个模型?

如果是这样,我会使用 TestResultModel.objects.create(.....) 之类的东西将报告插入到 postgres 中吗?

这是 json 的示例,由 pytest.main

输出

{"created": 1535570420.542123, "duration": 215.14111948013306, "exitcode": 1, "root": "/test", "environment": {"Python": "3.6.6", "Platform": "Linux-4.9.93-linuxkit-aufs-x86_64-with-debian-9.5", "Packages": {"pytest": "3.6.2", "py": "1.5.4", "pluggy": "0.6.0"}, "Plugins": {"xdist": "1.22.5", "metadata": "1.7.0", "json-report": "0.7.0", "forked": "0.2", "django": "3.3.3", "cov": "2.5.1", "celery": "4.2.1"}}, "summary": {"passed": 34, "failed": 7, "total": 41}

Do I need to first create a model based on all the keys in the json report that is going to be generated by pytest?

一般来说答案是肯定的。但它看起来不像您保存在数据库中的关系数据。因此,您可以使用 JSONField 并一次性将所有内容插入其中。 JSONField 对应于 postgresql 中的 JSONB 字段,用于存储 json 对象,并允许对这些对象进行搜索、修改等

您可能还想看看