有没有办法将 activity 复制到另一个数据库?
Is there a way to copy an activity to another database?
我想创建一个 activity 的副本并将其移动到另一个数据库中。
我可以看到两个解决方案:
方案1 - 使用我的activity的方法.copy()
,然后更改副本的数据库。问题是我不知道如何将 activity 从一个数据库移动到另一个数据库,甚至不知道如何移动。
选项 2 - 在目标数据库中重新创建一个 activity,其中包含要复制的 activity 的数据。虽然不难,但我觉得这种选择方式不太优雅。
下面是选项 2 的实现。
def copy_activity(activity, target_database=None, target_name=None):
"""
Copy an activity to another database
Args:
activity: Activity to copy
target_database (str):
Name of the database in which to copy the activity default is the database of the activity
target_name (str): Name of the copy, default is the name of the activity
"""
if (target_database is None) and (target_name is None):
raise ValueError('You must specify at least a target database or a target name')
db_name = target_database or activity.key[0]
db = bw.Database(db_name)
activity_copy = db.new_activity(activity.key[1])
for attribute in activity:
activity_copy[attribute] = activity[attribute]
for exchange in activity.exchanges():
if exchange.input == exchange.output:
activity_copy.new_exchange(input=activity_copy, output=activity_copy)
else:
activity_copy.new_exchange(input=exchange.input, output=activity_copy)
activity_copy.save()
我想创建一个 activity 的副本并将其移动到另一个数据库中。
我可以看到两个解决方案:
方案1 - 使用我的activity的方法.copy()
,然后更改副本的数据库。问题是我不知道如何将 activity 从一个数据库移动到另一个数据库,甚至不知道如何移动。
选项 2 - 在目标数据库中重新创建一个 activity,其中包含要复制的 activity 的数据。虽然不难,但我觉得这种选择方式不太优雅。 下面是选项 2 的实现。
def copy_activity(activity, target_database=None, target_name=None):
"""
Copy an activity to another database
Args:
activity: Activity to copy
target_database (str):
Name of the database in which to copy the activity default is the database of the activity
target_name (str): Name of the copy, default is the name of the activity
"""
if (target_database is None) and (target_name is None):
raise ValueError('You must specify at least a target database or a target name')
db_name = target_database or activity.key[0]
db = bw.Database(db_name)
activity_copy = db.new_activity(activity.key[1])
for attribute in activity:
activity_copy[attribute] = activity[attribute]
for exchange in activity.exchanges():
if exchange.input == exchange.output:
activity_copy.new_exchange(input=activity_copy, output=activity_copy)
else:
activity_copy.new_exchange(input=exchange.input, output=activity_copy)
activity_copy.save()