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

如何根据参数动态调用Python模块函数生成请求JSON数据?

Dynamic Function Calls in Python for Your REST API Client

Hey there! The problem you're hitting is that Python doesn't recognize the string you pass as the condition parameter as a reference to a function in condition_template. When you try condition_template.condition(app_id), it's looking for a function literally named condition instead of the function whose name matches the value of your condition argument.

Here's a clean, safe way to fix this using Python's built-in getattr() function, which lets you fetch objects (like functions) from a module using a string name:

Modified post_condition Function

def post_condition(api_key, app_id, policy_id, condition):
    headers = { 'X-api-key': api_key }
    api_url = '{0}/urlfor_api/{1}.json'.format(API_URL_BASE, policy_id)
    
    # Fetch the target function from condition_template
    try:
        condition_builder = getattr(condition_template, condition)
    except AttributeError:
        # Handle invalid condition names gracefully
        raise ValueError(f"Error: No condition function named '{condition}' exists in condition_template.py")
    
    # Generate the JSON payload by calling the retrieved function
    request_payload = condition_builder(app_id)
    
    response = requests.post(api_url, headers=headers, json=request_payload)
    if response.status_code == 201:
        return json.loads(response.content.decode('utf-8'))
    else:
        # Keep your existing error handling logic here
        print(f"Request failed with status code {response.status_code}")
        # ... rest of your error handling

How This Works

  • getattr(condition_template, condition): This looks up the function in the condition_template module whose name exactly matches the string passed in the condition parameter. For example, if you pass "alert_condition_user_score", it grabs the alert_condition_user_score function.
  • The try/except block: This catches cases where someone passes a condition name that doesn't exist in your template module. Instead of a vague AttributeError, you get a clear, user-friendly error message.

Example Usage

When you call post_condition, just pass the exact name of the function from condition_template.py as the condition argument:

# Use the alert_condition_user_score function
result = post_condition("my_api_key", "app_123", "policy_456", "alert_condition_user_score")

# Use another condition function from your template (e.g., alert_condition_session_count)
another_result = post_condition("my_api_key", "app_123", "policy_456", "alert_condition_session_count")

Quick Note

Make sure the string you pass for condition matches the function name in condition_template.py exactly—Python is case-sensitive, so Alert_Condition_User_Score won't work if your function is named alert_condition_user_score.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:10:01