优化下这段代码: def confirm_audit_rolled_back(self, audit): action_plan_filters = {'audit_id': audit.id} action_plans = objects.ActionPlan.list( self.context, filters=action_plan_filters, eager=True) if not action_plans: return # The last action_plan should be of type rollback and the execution is # complete while (action_plans[-1].strategy.name != 'rollback' or (action_plans[-1].strategy.name == 'rollback' and action_plans[-1].state in [ objects.action_plan.State.RECOMMENDED, objects.action_plan.State.PENDING, objects.action_plan.State.ONGOING])): LOG.info("audit %s waiting for rolled back", audit.uuid) time.sleep(WAIT_SECONDS) action_plans = objects.ActionPlan.list( self.context, filters=action_plan_filters, eager=True) LOG.info("audit %s already rolled back", audit.uuid)
时间: 2024-02-14 15:26:32 浏览: 111
这段代码可以进行一些优化。首先,可以使用一个循环来替代while循环,以避免重复获取action_plans。
```python
while True:
action_plans = objects.ActionPlan.list(
self.context, filters=action_plan_filters, eager=True)
if not action_plans:
return
last_action_plan = action_plans[-1]
if (last_action_plan.strategy.name == 'rollback' and
last_action_plan.state not in [
objects.action_plan.State.RECOMMENDED,
objects.action_plan.State.PENDING,
objects.action_plan.State.ONGOING]):
break
LOG.info("audit %s waiting for rolled back", audit.uuid)
time.sleep(WAIT_SECONDS)
```
这样,每次循环只需要获取一次action_plans列表,而不需要多次重复获取。同时,使用一个if条件判断语句来检查最后一个action_plan是否满足条件,如果满足条件则跳出循环。
最后,可以将LOG.info语句移动到循环外部,以便在确认回滚完成后打印日志。
```python
LOG.info("audit %s already rolled back", audit.uuid)
```
通过这些优化,可以减少代码的重复执行和冗余判断,提高执行效率。
阅读全文