我是 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 数据库中 [请注意,我使用了一个帮助程序来获取由结果
]
这就是我感到困惑的地方。
我是否需要先根据 pytest 生成的 json 报告中的所有键创建一个模型?
如果是这样,我会使用类似 TestResultModel.objects.create(.....)
的方法将报告插入到 postgres 中吗?
这是 pytest.main 输出的 json 示例
{"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对象,并允许对这些对象进行搜索、修改等。
关于django - 作为 celery 任务的一部分将 json 插入 postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52105031/