MCPcopy
hub / github.com/pmh1314520/WebRPA / set_variable

Method set_variable

backend/app/executors/base.py:409–482  ·  view source on GitHub ↗

设置变量值

(self, name: str, value: Any)

Source from the content-addressed store, hash-verified

407 return self.variables.get(name, default)
408
409 def set_variable(self, name: str, value: Any):
410 """设置变量值"""
411 import json
412 from datetime import datetime
413
414 # 记录旧值
415 old_value = self.variables.get(name)
416
417 # 设置新值
418 self.variables[name] = value
419
420 # 记录变量追踪信息
421 try:
422 # 尝试序列化值用于显示
423 def serialize_value(v):
424 if v is None:
425 return None
426 elif isinstance(v, (str, int, float, bool)):
427 return v
428 elif isinstance(v, (list, dict)):
429 try:
430 # 尝试JSON序列化
431 json.dumps(v)
432 return v
433 except Exception:
434 return str(v)
435 else:
436 return str(v)
437
438 tracking_record = {
439 "timestamp": datetime.now().isoformat(),
440 "variable_name": name,
441 "old_value": serialize_value(old_value),
442 "new_value": serialize_value(value),
443 "node_id": self._current_node_id,
444 "node_name": self._current_node_name or "未知模块",
445 "operation": "create" if old_value is None else "update",
446 "value_type": type(value).__name__
447 }
448 # 限制追踪记录数量上限,防止长循环导致内存爆炸
449 _MAX_TRACKING = 5000
450 self._variable_tracking.append(tracking_record)
451 if len(self._variable_tracking) > _MAX_TRACKING:
452 # 删除最早的 1/4 记录(避免每次都做截断的开销)
453 drop = _MAX_TRACKING // 4
454 del self._variable_tracking[:drop]
455 except Exception as e:
456 print(f"记录变量追踪失败: {e}")
457
458 # 通知变量更新
459 if self._variable_update_callback:
460 import asyncio
461 try:
462 # 在异步上下文中调用回调(仅当存在运行中的事件循环)
463 try:
464 asyncio.get_running_loop()
465 # 保存任务引用避免被 GC,并通过 done_callback 处理异常
466 task = asyncio.create_task(self._variable_update_callback(name, value))

Callers 15

_capture_proxyMethod · 0.80
_capture_browserMethod · 0.80
capture_taskMethod · 0.80
executeMethod · 0.80
executeMethod · 0.80
executeMethod · 0.80
executeMethod · 0.80
executeMethod · 0.80
executeMethod · 0.80
executeMethod · 0.80
executeMethod · 0.80

Calls 3

create_taskMethod · 0.80
addMethod · 0.80
getMethod · 0.45

Tested by 1