如何根据参数动态调用Python模块函数生成请求JSON数据?
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 thecondition_templatemodule whose name exactly matches the string passed in theconditionparameter. For example, if you pass"alert_condition_user_score", it grabs thealert_condition_user_scorefunction.- The
try/exceptblock: This catches cases where someone passes a condition name that doesn't exist in your template module. Instead of a vagueAttributeError, 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

