嗨,我正在尝试集成 Dagster进入正在进行的 Django 项目。我在向 Dagster 提供 Django 上下文(模型、应用程序等)方面遇到了困难。截至目前,我只是检查 dagit
是否存在于 init.py 中的 sys.argv[0]
中使用 Dagster 的应用程序。
<!-- language: python -->
## project/app/__init__.py
import sys
import django
if 'dagit-cli' in sys.argv[0]:
print('dagit')
django.setup()
有人可以帮我设置吗?
最佳答案
我还会使用 Django 自定义管理命令,如 Timothé 所说,在 Django 上下文中执行函数或访问 ORM。
但是,如果您的用例需要直接访问 Django ORM,则需要执行几个步骤:
- 将 Django 项目添加到
sys.path
中,以便 Python 可以找到包。 - 设置 Django 环境。
import os
import sys
import django
from dagster import execute_pipeline, pipeline, solid
# Add the project to sys.path, so that Python can find packages
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), 'demo')
sys.path.append(PROJECT_ROOT)
# Set up the Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings')
django.setup()
from customers.models import Customer
@solid
def hello_django_orm(context):
number_of_customers = Customer.objects.count()
message = f'Found {number_of_customers} customers!'
context.log.info(message)
return number_of_customers
@pipeline
def hello_django_orm_pipeline():
hello_django_orm()
if __name__ == '__main__':
result = execute_pipeline(hello_django_orm_pipeline)
assert result.success
查看下面的结果。
请查看完整示例 here .
关于python - 将 Dagster 与 Django 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59048161/