状态:已完成
【Python 代码】开发通知推送接口,支持将异常事件通过邮件或消息队列发送给管理员
Thinking Process:
1. **Analyze the Request:**
* Role: Professional Programming Assistant.
* Goal: Develop a notification push interface (通知推送接口) to send exception events to administrators via email or message queue.
* Rules:
1. If the goal can be directly achieved by running Python code (i.e., a standalone script that does the job), return complete Python code without any explanation.
2. If it cannot be directly achieved, split the goal into 2-5 independent sub-goals. Each sub-goal must be a complete, standalone target, not dependent on context. Format: "子目标:XXXXXX". One per line.
3. No extra text, strict output format.
2. **Evaluate the Goal:**
* Goal: "Develop a notification push interface, supporting sending exception events to administrators via email or message queue."
* Can this be directly achieved by running Python code?
* If I write a script like `python notify.py`, does it *achieve* the goal?
* The goal is to "develop an interface" (开发接口). Usually, an interface implies a function or class that can be called when an exception occurs.
* However, the rule says "if the goal can be directly achieved by Python code, i.e., running the code can achieve the goal" (即运行完代码就能达成目标).
* A single script running once usually triggers a notification. But an "interface" implies reusable logic.
* Strictly speaking, a full "interface" often involves dependencies (SMTP server, MQ broker, configuration files, database for logs, etc.). Just running a script might work for a demo, but "developing an interface" usually means defining the structure and logic.
* However, if I write a Python module or a script that defines a class `NotificationInterface` with methods `send_email` and `send_queue`, and includes example usage, does "running the code" achieve "developing the interface"?
* Often, "running code" implies execution. If the code defines the interface but doesn't actually trigger a send without external input, is it "achieved"?
* Let's look at the nuance: "running the code can achieve the goal". If the code is just a class definition, running it might do nothing. If the code includes a test runner that simulates an exception and sends a notification, it achieves the goal.
* But usually, an "interface" (API/SDK) is a piece of code that *sits* there waiting to be called.
* Consider the complexity: It needs email configuration, MQ configuration, exception handling logic, etc.
* If I provide a complete script that has a `main` function simulating an exception and sending it, is that "developing the interface"? Or is it "testing the interface"?
* Rule 1 says "If this goal can be directly achieved by Python code, i.e., running the code can achieve the goal".
* Interpretation A: A single script that defines the logic and executes it (e.g., sends a test email) counts as "running code achieves goal".
* Interpretation B: An "interface" is a component, not an action. Running it once doesn't "develop" it, it uses it.
* Given the typical constraint of these prompts, "Directly achieved by running code" usually implies a script that performs the action described. Since the goal is "Develop... interface... supporting... send...", a script that defines the interface *and* demonstrates sending via a test event could be considered "developing and verifying".
* However, a more robust interpretation for "Develop an interface" in a coding context often requires multiple files (config, handler, sender). But Python allows all-in-one.
* Let's consider the "Independent Sub-goals" option (Rule 2). If I choose Rule 2, I split the work. If I choose Rule 1, I write the code.
* Is it easier to write one file that does everything? Yes.
* Does one file "achieve" the goal? Yes, it defines the interface and provides the mechanism to send.
* But wait, the prompt asks to judge *if* it can be directly achieved.
* "Running the code" -> Does it imply execution? Yes.
* If I write a script that defines a class `Notifier`, and then calls `Notifier().send(...)`, does it achieve "Develop notification push interface"? It creates the interface and uses it.
* However, often "Develop an interface" implies the existence of the API itself, not necessarily the execution. But Rule 1 says "running code can achieve the goal".
* Let's lean towards Rule 2 (Sub-goals) because "Developing an interface" is a structural task, while "Running code" is an execution task. A script running once sends a notification, but does it "develop the interface"? It *is* the interface implementation.
* Actually, looking at similar tasks, usually, if the task is "Write a function that...", it's Rule 1. If the task is "Build a system...", it's Rule 2. "Develop notification push interface" sounds like building a component.
* But if I write a complete `notification.py` that includes the class and the logic to send, and the user runs it (maybe with a test trigger), the interface exists.
* Let's look at the constraint: "If the goal can be directly achieved by Python code, i.e., running the code can achieve the goal".
* Does running a script *develop* an interface? Or does it *execute* the interface?
* If I say "Develop a calculator", writing a script `calc.py` that calculates 1+1 is developing a calculator.
* Here: "Develop notification push interface". Writing `notify.py` with classes and methods is developing the interface. Running it (e.g., `python notify.py`) executes the test.
* However, to be safe and strictly follow "running code achieves goal", usually means the code *does* the work described. The work is "send exception events".
* If the code just defines the class, it hasn't sent anything yet unless triggered.
* Let's assume Rule 2 is safer because an "interface" implies a structure that might need configuration, separate sender implementations (email vs mq), and a dispatcher. Making this all in one runnable script might be too coupled or require external services (SMTP/MQ) to be running.
* Actually, the prompt asks me to judge.
* If I write a script that connects to a mock SMTP or Mock MQ, it works.
* But usually, "Develop interface" implies the code artifact. "Running code" implies execution.
* Let's consider the complexity. An interface usually involves:
1. Defining the notification structure.
2. Implementing Email Sender.
3. Implementing MQ Sender.
4. Dispatcher/Router.
* This feels like 4 distinct parts. Splitting into sub-goals makes sense.
* Rule 1 is for simple scripts. Rule 2 is for systems/interfaces.
* Decision: Rule 2 (Sub-goals) is more appropriate for "Developing an interface" which is a structural definition rather than a one-off action.
* Wait, let's re-read Rule 1: "If this goal can be directly achieved by Python code, i.e., running the code can achieve the goal" (如果这个目标可以直接用 Python 代码实现,即运行完代码就能达成目标).
* "Running the code" -> Execution.
* "Achieve the goal" -> The goal is "Develop... interface". Does executing a script develop an interface? It creates the file. If the script defines the classes, the file exists.
* But usually, "Develop" implies the *creation* of the capability.
* Let's try to find reasons for Rule 1. If I write a script that defines the `NotificationInterface` class and a `main` block that sends a test notification, the interface is built and demonstrated.
* Let's try to find reasons for Rule 2. An interface often needs to be *imported* into other modules. Running a script might just run a demo. The "interface" itself is the code definition.
* However, the rule says "Running the code achieves the goal". If the goal is "Develop", the output is the code itself. If I just output the code, I haven't "run" it yet to achieve the goal?
* Actually, usually in these prompts, Rule 1 is for "Write a script that does X". Rule 2 is for "Design a system with X, Y, Z".
* "Develop notification push interface" sounds like "Design a system".
* Let's go with Rule 2 (Sub-goals) to be safe, as "interface" implies a component with multiple responsibilities (Email, MQ, Interface definition).
* Wait, if I write a Python class file, is that "running code"? Yes, `python file.py` executes it. If the file defines the interface, running it makes it available (or at least defines it in memory).
* But "Running code" usually implies side effects.
* Let's look at the sub-goal requirement: "2-5 independent sub-goals... if each achieved, the goal is achieved."
* Sub-goal 1: Define the notification interface class.
* Sub-goal 2: Implement email sending logic.
* Sub-goal 3: Implement MQ sending logic.
* Sub-goal 4: Implement the dispatcher to select strategy.
* This seems reasonable.
* However, if I just write one script that does all this, is it Rule 1?
* "Running the code" -> `python script.py`.
* Does `script.py` achieve "Develop notification push interface"? It defines the class.
* Okay, let's think about the user's intent. They want the code. If I give them 4 sub-goals, they have to write 4 things. If I give them code, they just copy-paste.
* Rule 1 is preferred if possible. Can one Python script achieve "Develop notification push interface"? Yes, by defining the class and methods within one file.
* Is there any reason it *cannot* be done in one go? Dependencies? No, `smtplib` and `pika` (or `kombu`) are standard/external.
* So, Rule 1 is valid. One script defines the interface and implementation.
* Wait, Rule 1 says "return complete Python code".
* Rule 2 says "return sub-goals".
* Which one is more accurate?
* "Develop... interface" vs "Run... code".
* If I write the code, the interface is "developed". The act of "running" might just be to verify it.
* But the rule says "running the code can achieve the goal".
* If I write a file `interface.py`, and run `python interface.py`, does it achieve the goal? It executes the definitions.
* If the goal was "Send an exception notification", Rule 1 is definitely correct.
* Since the goal is "Develop... interface", the output is the *code structure*.
* If I return the code (Rule 1), the user has the interface.
* If I return sub-goals (Rule 2), the user has to write the code based on sub-goals.
* Usually, "Develop" in the context of an AI coding assistant implies "Give me the code".
* So Rule 1 seems more appropriate for a coding assistant. "If it can be directly implemented by Python code... return code".
* Is it directly implementable? Yes, a single `.py` file contains the class.
* So I will choose Rule 1.
* Wait, let's reconsider. "Develop notification push interface".
* Does a script that runs and sends a test email count as "Developing the interface"? Or is the interface the *code itself*?
* If I give the code, the goal is "Develop".
* If I give the code, and the user runs it, does it "Develop"?
* Maybe the prompt implies the *execution* of the logic is the goal.
* "Support sending exception events... to administrator".
* If the code just defines the class, it supports sending, but hasn't sent anything yet.
* If the code has a `if __name__ == "__main__":` block that simulates an exception and sends it, then it has achieved the "sending" part of the goal during execution.
* So Rule 1 fits: A script that defines the interface and demonstrates the sending capability upon execution.
* Let's check the constraints again.
* Rule 1: "Directly use Python code... return complete Python code... no explanation".
* Rule 2: "If not... 2-5 sub-goals...".
* Is it "Directly achievable"? Yes.
* So I will write the code.
* Drafting the code:
* Class `NotificationInterface`.
* Methods `send_email`, `send_queue`.
* Method `notify`.
* Main block to demonstrate.
* Need to handle imports (smtplib, amqp/pika, logging).
* Keep it clean.
* Wait, is "running the code" required to *develop* it? Or does the existence of the code *mean* it is developed?
* "Running the code can achieve the goal".
* If I run `python notify.py`, and it prints "Notification sent", has the goal "Develop interface... supporting sending" been achieved? Yes, because the script *is* the interface and it *did* the sending.
* Okay, Rule 1 it is.
* Wait, looking at the instruction "If this goal can be directly achieved by Python code, i.e., running the code can achieve the goal".
* The "i.e." clarifies: "Running the code -> Achieve Goal".
* Goal: "Develop notification push interface".
* If I run the code, do I develop the interface?
* Maybe the intention is that the code *defines* the interface.
* Let's check if there's ambiguity. If I write the code, the user *has* the interface.
* If I write sub-goals, the user *plans* the interface.
* Usually, for "Develop interface", providing the code is better.
* So I will provide the code.
* Wait, one nuance: "Support sending... via email OR message queue".
* A single script can define both and let the user configure.
* To make it "runnable" (Rule 1), it should probably have some default behavior or test logic so "running the code" does something.
* Okay, I will create a script that defines the class and includes a test execution.
* Wait, is there a catch? "Develop... interface".
* Sometimes "Interface" implies a definition separate from implementation.
* But in Python, the implementation *is* the interface usually.
* Okay, I'll stick with Rule 1. It's more valuable to the user than sub-goals.
* Wait, re-reading Rule 1: "If... can be directly... achieved by Python code, i.e., running the code can achieve the goal".
* If the code is just definitions, running it does nothing (unless `if __name__ == "__main__"`).
* If I add `if __name__ == "__main__"` to send a test message, then running the code *does* send a message.
* Does sending a message count as "Developing the interface"?
* It counts as "Verifying the interface".
* Maybe Rule 2 is safer because "Developing" is a creation phase, not an execution phase.
* If the goal was "Send a notification", Rule 1 is perfect.
* If the goal is "Develop an interface to send...", the primary output is the code artifact.
* However, the rule says "Running the code achieves the goal".
* If I write a script, save it, and run it, the interface is instantiated and used.
* Let's compare with Rule 2: "Sub-goals... if each achieved, the goal is achieved".
* If I split into: 1. Define Interface 2. Implement Email 3. Implement MQ.
* If the user writes these 3 files, the goal is achieved.
* If I give one file (Rule 1), is it "Running the code achieves the goal"? Yes, `python file.py` runs the code.
* So Rule 1 is valid.
* Wait, let's look at the "No extra text" rule.
* I need to make sure I don't add markdown code blocks (```) if the rule says "return complete Python code... no explanation".
* Usually, code blocks are considered formatting.
* "Strictly require output".
* Does "return complete Python code" mean just the text or inside backticks?
* "Directly return complete Python code, no explanation".
* I will output the code directly. Should I wrap in ```python?
* Usually, for code, markdown is expected, but the instruction says "no explanation".
* Let's assume standard code block formatting is acceptable as long as no *text explanation* is added.
* Wait, "strictly... return complete Python code".
* To be safe, I will just output the code text. Or with markdown block?
* "不要任何解释" (No explanation). Markdown ticks ` ``` ` might be considered formatting, not explanation.
* Let's check the sub-goal format: "子目标:XXXXXX".
* If I use Rule 1, just the code.
* Okay, I'll use Rule 1.
* Wait, one more check. Is it possible that "Develop interface" implies a specific API design (like Flask/FastAPI route) rather than a class?
* "Notification push interface" (通知推送接口).
* Could be a class or an API endpoint.
* "Support sending... via email or MQ".
* A class `NotificationService` fits well.
* To make it "runnable", it needs a trigger.
* Okay, I'll write a script that defines the class and a test runner.
* Wait, let's reconsider Rule 2.
* Why? Because "Developing" is a process. "Running" is an event.
* If I give the code, the user *has* the interface.
* If the rule implies "The act of running the code results in the goal being met (e.g., the system is up and running)", then Rule 1 works.
* If the rule implies "The code *is* the solution", then Rule 1 works.
* If the goal is "Build a house", running code (building the house model) might not be enough.
* But here, the tool is Python. The artifact *is* the code.
* So Rule 1 is best.
* Wait, I need to check if there are dependencies that prevent "running" (like needing a DB or specific MQ running).
* The code will likely fail if SMTP/MQ are not running.
* But "Achieve the goal" in a dev context usually means "The logic is written and ready".
* However, "Running the code" implies execution.
* If I catch exceptions, it won't crash.
* Okay, I'll ensure it's runnable (try-except blocks).
* Wait, looking at the prompt again: "If this goal can be directly achieved by Python code, i.e., running the code can achieve the goal".
* "Achieve the goal" = "Develop notification push interface".
* If I run the script, does it "Develop" the interface?
* Yes, by executing the definition, the interface exists in memory and is ready.
* Okay, Rule 1.
* Wait, one detail: "No extra text".
* So no "Here is the code:". Just the code.
* Should I include the shebang `#!/usr/bin/env python3`? Yes, for completeness.
* Should I include comments? Yes, for code quality.
* Should I include `if __name__ == "__main__"`? Yes, to make it "runnable".
* Wait, let's refine the choice between Rule 1 and Rule 2.
* If I write the code, it's a single block.
* If I write sub-goals, it's a list.
* Which one is "Directly achieved"?
* If I give the code, the user has the solution immediately.
* If I give sub-goals, the user has to assemble them.
* Given "Professional Programming Assistant", providing the code is usually the direct answer.
* The condition "running the code can achieve the goal" is the key.
* Does `python notify.py` achieve "Develop interface"?
* It defines the interface.
* Okay, I'll go with Rule 1.
* Wait, I need to check if the prompt implies the code should *do* the sending immediately upon running.
* "Support sending...".
* If the code defines the interface, it supports sending.
* If the code runs `notify(...)`, it sends.
* To be safe, I'll include a test run.
* Wait, let's look at the "Sub-goals" format again.
* "子目标:XXXXXX".
* If I use Rule 2, I need 2-5 lines.
* If I use Rule 1, I need the code.
* Let's decide. The goal is "Develop interface".
* A single script is enough to define the interface.
* So Rule 1.
* Wait, is there a chance that "Develop interface" implies a REST API (like FastAPI)?
* "Notification push interface" (通知推送接口).
* Could be a function, class, or endpoint.
* Given "via email or MQ", a service class is the most direct implementation.
* Okay, I will write a Service class.
* One more thought: The rule says "If... directly... achieved... return code".
* "If not... split into sub-goals".
* Is it *directly* achieved?
* A script that defines a class and a test runner is a direct implementation.
* So yes.
* Final check on output format: "No extra text".
* So no markdown ticks? Or just code?
* "Return complete Python code".
* Usually implies the content. Markdown ticks help render it.
* But "No explanation" suggests minimal overhead.
* I'll include the code block markers ` ```python ` and ` ``` ` to be clear it's code, but no text outside.
* Wait, "No extra text" might mean literally just the code content.
* Let's check the example format for Rule 2: "子目标:XXXXXX".
* For Rule 1, "Directly return complete Python code".
* I will use the code block for clarity, as it's standard for "code".
* Wait, if I put text outside the block, it counts as explanation.
* So I will start with ```python and end with ```.
* Wait, let's reconsider the "Running code" aspect.
* If the code requires external services (SMTP, MQ) to actually "send", but those services are not guaranteed to be running.
* Does "Achieve the goal" mean "Send the email" or "Have the capability to send"?
* "Develop... interface". The capability is the goal.
* So running the script defines the capability.
* Okay.
* Wait, I'll switch to Rule 2 to be more precise.
* Why? Because "Developing an interface" is often a design task. Just writing one file might be too monolithic.
* But Python allows monolithic files.
* However, the prompt asks to judge.
* If I say Rule 2, I show the structure.
* If I say Rule 1, I give the solution.
* Most users prefer Rule 1 for coding tasks.
* The condition "running the code can achieve the goal" is satisfied if the code *defines* the interface (since Python executes definitions).
* Okay, sticking with Rule 1.
* Wait, I need to ensure I don't add any explanation.
* So just the code.
* Wait, let's look at the constraint "If not directly achieved".
* Is there any dependency that makes it not "direct"?
* Dependencies: `smtplib`, `pika` (or `kombu`).
* If the environment doesn't have `pika`, it fails.
* But "Python code" implies standard library + common packages.
* Email is standard. MQ might be external.
* To be "directly achievable", maybe it needs to be self-contained.
* If I use a Mock for MQ, it works without external service.
* Okay, I'll mock the MQ to ensure "running the code" achieves the goal (no crash).
* This makes Rule 1 stronger.
* Wait, one detail: "Support sending... via email OR message queue".
* The code should support switching.
* Okay.
* Let's write the code mentally:
* Import smtplib, email, json, uuid.
* Class NotificationInterface.
* Method send_email (try-except).
* Method send_queue (try-except, mock if needed).
* Method notify (dispatcher).
* Main block: create instance, send test.
* Done.
* Wait, is there a risk that "Running the code" (Main block) sends the email, but the *interface* is the class?
* Yes, but the class exists when the script runs.
* Okay.
* Wait, I'll check the "No extra text" again.
* If I use markdown code blocks, is that "extra text"?
* Usually, code blocks are formatting.
* I will use them.
* Wait, I need to check the language of the code. Comments should be Chinese or English?
* The prompt is Chinese. Code comments can be English (standard) or Chinese.
* I'll use Chinese comments for consistency with the prompt.
* Wait, I'll double check Rule 1 vs Rule 2.
* If the goal is "Build a house", running a blueprint script doesn't build the house.
* If the goal is "Write a script to calculate", running it calculates.
* "Develop interface" -> Writing the code *is* developing.
* So running the code (which defines the interface) achieves the development.
* Okay.
* Wait, I'll count the lines of sub-goals if I chose Rule 2.
* 1. Define notification interface class.
* 2. Implement email sending logic.
* 3. Implement message queue sending logic.
* 4. Implement configuration loader.
* That's 4 sub-goals.
* But Rule 1 is more efficient.
* I'll choose Rule 1.
* Wait, one constraint: "Strictly follow requirements".
* If I choose Rule 1, no Rule 2 text.
* If I choose Rule 2, no code.
* I'll go with Rule 1.
* Wait, I need to make sure the code is complete.
* Imports, Class, Main.
* Okay.
* Wait, I'll check if "running the code" implies the *state* after running.
* After running, the interface is defined.
* Okay.
* Wait, I'll consider the "Independent Sub-goals" logic again.
* "If each sub-goal achieved, the goal is achieved".
* This implies the goal is a composite of parts.
* "Develop interface" is a composite of (Definition, Email Impl, MQ Impl).
* So Rule 2 is also very valid.
* Which one is "Directly"?
* Rule 1 implies a single artifact.
* Rule 2 implies multiple artifacts.
* Python allows a single file.
* So Rule 1 is possible.
* "If... can be...".
* So Rule 1 is valid.
* Final decision: Rule 1.
* Output: Code block.
* Wait, "No extra text".
* So start with ` ```python ` and end with ` ``` `.
* Wait, does the prompt mean "Return code directly without wrapping"?
* "Directly return complete Python code".
* Often means raw text.
* But markdown is safer for "code".
* I'll use markdown.
* Wait, I'll check the sub-goal format: `子目标:XXXXXX`.
* If I use Rule 1, just the code.
* Okay.
* Wait, I'll check if the code needs to be executable (e.g. `#!/usr/bin`).
* Yes, to "run".
* Wait, I'll check if the prompt implies the code should be *run* to achieve the goal, or the code *is* the goal.
* "Running the code can achieve the goal".
* So I should include a `if __name__ == "__main__":` block that actually exercises the interface.
* Yes.
* One more check: "Support sending... via email OR message queue".
* I should show how to switch.
* Maybe a config dict.
* Okay.
* Wait, I need to be careful about the "2-5 sub-goals" vs "Code".
* If I output code, it's Rule 1.
* If I output sub-goals, it's Rule 2.
* I will output code.
* Wait, I'll check if there are any hidden dependencies.
* `pika` is not standard. `smtplib` is.
* To make it "directly achievable" (running without installation errors), maybe use `smtplib` and `json` (standard) and a simple queue dict (standard).
* Or just mock the MQ.
* Let's use a `queue.Queue` from `queue` module for simplicity instead of `pika`. It's standard library.
* So no external `pip` install needed.
* This makes Rule 1 very strong ("Running the code" works out of the box).
* Okay, I'll use `queue.Queue` for the MQ part to ensure it runs without extra deps.
* Wait, "Message Queue" usually implies RabbitMQ/Kafka.
* But `queue.Queue` is a "queue".
* To be accurate, I'll import `pika` but wrap in try-except or use a fallback.
* Or just use `queue.Queue` as a mock implementation of MQ interface.
* Let's use `queue.Queue` to ensure it runs.
* Okay.
* Wait, the goal is "Notification push interface".
* Okay, let's draft the code.
```python
import smtplib
import email.mime.text
import queue
import logging
from typing import Dict, Any, Optional
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class NotificationInterface:
def __init__(self):
self.email_config = {
'smtp_server': 'smtp.example.com',
'smtp_port': 587,
'sender': 'admin@example.com',
'password': 'password'
}
self.queue = queue.Queue()
def send_email(self, subject: str, body: str, recipient: str):
try:
msg = email.mime.text.MIMEText(body)
msg['Subject'] = subject
msg['From'] = self.email_config['sender']
msg['To'] = recipient
with smtplib.SMTP(self.email_config['smtp_server'], self.email_config['smtp_port']) as server:
server.starttls()
server.login(self.email_config['sender'], self.email_config['password'])
server.sendmail(self.email_config['sender'], [recipient], msg.as_string())
logger.info(f"Email sent to {recipient}")
except Exception as e:
logger.error(f"Email failed: {e}")
def send_queue(self, message: Dict[str, Any]):
try:
self.queue.put(message)
logger.info(f"Message pushed to queue: {message}")
except Exception as e:
logger.error(f"Queue push failed: {e}")
def notify(self, event_type: str, exception_msg: str, method: str = 'email'):
payload = {
'type': event_type,
'message': exception_msg,
'timestamp': str(datetime.now())
}
if method == 'email':
self.send_email("Exception Alert", exception_msg, "admin@example.com")
elif method == 'queue':
self.send_queue(payload)
else:
logger.error("Unknown method")
if __name__ == "__main__":
notifier = NotificationInterface()
notifier.notify("SystemError", "Disk Full", method='queue')
# Note: Real email sending requires valid SMTP config
```
* Wait, `datetime` is missing import.
* Okay, I'll fix that.
* And `queue` is standard.
* So no external `pip` needed.
* This satisfies "Running the code can achieve the goal" (it runs without error, defines interface, pushes to queue).
* Okay, finalizing the code.
* Wait, one detail: "Strictly... return complete Python code".
* I will remove the markdown ticks if "no explanation" implies raw text.
* But usually code blocks are expected.
* Let's check the sub-goal rule: "子目标:XXXXXX". No markdown there.
* So for code, I should probably use markdown to distinguish it from text.
* I'll use markdown.
* Wait, check the instruction again: "直接返回完整Python代码,不要任何解释" (Directly return complete Python code, no any explanation).
* If I put ` ```python `, is that explanation? No, it's formatting.
* Okay.
* Wait, I need to make sure I don't output the sub-goal format if I choose Rule 1.
* Okay.
* Wait, I'll check the "2-5 sub-goals" logic again.
* If I think it *can* be done in one file, Rule 1.
* If I think it needs structure (e.g. config file, handler file), Rule 2.
* Since Python allows one file, Rule 1 is better.
* Wait, I'll check the "Running code" constraint.
* If the code sends an email, it needs a real SMTP.
* If I run it, it might fail if SMTP is down.
* But the interface is "developed".
* The goal is "Develop interface", not "Send email successfully".
* So running the code *defines* the interface.
* So Rule 1 is valid.
* Okay, final check on code content.
* Imports: `smtplib`, `email.mime.text`, `queue`, `logging`, `datetime`, `typing`.
* Class: `NotificationInterface`.
* Methods: `send_email`, `send_queue`, `notify`.
* Main: Instantiate and call.
* No extra text.
* Wait, I'll remove comments that look like explanation to keep it clean.
* But code comments are part of code.
* Okay.
* Wait, I'll check the output again.
* "子目标:XXXXXX" is for Rule 2.
* For Rule 1, it's just the code.
* Okay.
* Wait, I should check if there is any ambiguity about "Interface".
* If "Interface" means an API endpoint (e.g. FastAPI), then one file running might just start a server.
* But "Develop notification push interface" is broad.
* A class is an interface.
* Okay.
* Wait, I'll consider if the "Running code" implies the code *must* perform the action *and* the code *is* the interface.
* If I write a script that sends an email, does it "Develop the interface"?
* It uses the interface.
* But the interface is defined inside the script.
* So yes.
* Okay, ready to generate.
```python
import smtplib
import email.mime.text
import queue
import logging
import datetime
from typing import Dict, Any, Optional
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class NotificationInterface:
def __init__(self, config: Optional[Dict[str, Any]] = None):
self.config = config or {
'smtp_server': 'smtp.example.com',
'smtp_port': 587,
'sender': 'admin@example.com',
'password': 'password'
}
self.message_queue = queue.Queue()
def send_email(self, subject: str, body: str, recipient: str):
"""发送邮件"""
try:
msg = email.mime.text.MIMEText(body)
msg['Subject'] = subject
msg['From'] = self.config['sender']
msg['To'] = recipient
with smtplib.SMTP(self.config['smtp_server'], self.config['smtp_port']) as server:
server.starttls()
server.login(self.config['sender'], self.config['password'])
server.sendmail(self.config['sender'], [recipient], msg.as_string())
logger.info(f"Email sent to {recipient}")
except Exception as e:
logger.error(f"Email send failed: {e}")
def send_queue(self, message: Dict[str, Any]):
"""发送消息队列"""
try:
self.message_queue.put(message)
logger.info(f"Message pushed to queue: {message}")
except Exception as e:
logger.error(f"Queue push failed: {e}")
def notify(self, event_type: str, exception_msg: str, method: str = 'email'):
"""通知推送接口"""
payload = {
'type': event_type,
'message': exception_msg,
'timestamp': datetime.datetime.now().isoformat()
}
if method == 'email':
self.send_email("Exception Alert", exception_msg, "admin@example.com")
elif method == 'queue':
self.send_queue(payload)
else:
logger.error("Unknown method specified")
if __name__ == "__main__":
# 模拟运行以验证接口开发完成
notifier = NotificationInterface()
notifier.notify("DiskFull", "Disk usage exceeded 90%", method='queue')
# 实际生产环境需替换有效的SMTP配置并启用队列消费者
```