You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需eval/字典,如何实现服务器任务名到函数的通用代码流控制?

Alternatives for Routing Request Tasks to Functions

Great question! Let's walk through some safer, more scalable alternatives to eval() (which you should absolutely avoid—more on that in a sec) and basic dictionary mappings for routing requests to functions.

First, a quick critical note: eval() is a huge security risk. If an attacker sends a malicious TestName like "__import__('os').system('rm -rf /')", it can execute arbitrary code and wreck your system. So let's focus on secure, maintainable options instead.

1. Use globals()/locals() (with strict guardrails)

You can access functions directly from the global or local namespace, but always validate the input to avoid calling unintended objects:

def din(): print("din")
def david(): print("david")
request = {"TestName": "din"}

test_name = request['TestName']

# Validate first: check if the name exists and is a callable function
if test_name in globals() and callable(globals()[test_name]):
    globals()[test_name]()
else:
    print(f"Task '{test_name}' not found or isn't a valid function")

⚠️ Caveat: globals() includes all global objects (like built-ins and modules), so for extra safety, filter functions by a naming convention (e.g., only functions starting with task_) or maintain a whitelist of allowed task names.

2. Auto-register functions with decorators (top pick for scalability)

This approach lets you automatically add functions to a registry as you define them—no need to manually update a dictionary every time you add a new task. It's clean and scalable for larger codebases:

# Initialize a registry to hold task names and their functions
task_registry = {}

# Create a decorator to register tasks
def register_task(task_name):
    def decorator(func):
        task_registry[task_name] = func
        return func
    return decorator

# Register functions with the decorator
@register_task("din")
def din(): print("din")

@register_task("david")
def david(): print("david")

# Handle the request
request = {"TestName": "din"}
test_name = request['TestName']

if test_name in task_registry:
    task_registry[test_name]()
else:
    print(f"Task '{test_name}' isn't registered")

This is my go-to because it keeps your task definitions and registration logic tightly coupled—no more forgetting to update a dictionary when you add a new function.

3. Organize tasks in a class with getattr()

If your tasks share related logic or need state management, grouping them in a class and using getattr() to fetch the method is a clean way to organize code:

class TaskHandler:
    @staticmethod
    def din():
        print("din")
    
    @staticmethod
    def david():
        print("david")

request = {"TestName": "din"}
test_name = request['TestName']

try:
    # Fetch the method from the class
    task_func = getattr(TaskHandler, test_name)
    if callable(task_func):
        task_func()
except AttributeError:
    print(f"Task '{test_name}' doesn't exist in TaskHandler")

If you need to maintain state between tasks (e.g., shared connections or configuration), use instance methods instead of static methods and create an instance of TaskHandler.

4. Pre-bind arguments with functools.partial (for parameterized tasks)

If your tasks require arguments, use functools.partial to pre-bind parameters to functions, making them callable without additional arguments from the request:

from functools import partial

def greet(name):
    print(f"Hello, {name}!")

# Pre-bind arguments to create task-specific functions
task_registry = {
    "greet_din": partial(greet, "din"),
    "greet_david": partial(greet, "david")
}

request = {"TestName": "greet_din"}
task_registry[request['TestName']]()  # Output: Hello, din!

Final Takeaways

  • Avoid eval() at all costs: It’s a critical security vulnerability if request data isn’t fully trusted.
  • Basic dictionary mappings work for small projects, but decorators or class-based organization are better for growing codebases.
  • Always add validation (check if the task exists and is callable) to prevent runtime errors.

内容的提问来源于stack exchange,提问作者Yoni Sade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:26:58