记一次Zabbix微信报警Python脚本发送中文乱码问题
The joys of working with non-ASCII characters in Python! ??As a Zabbix enthusiast, I'm sure you're familiar with the importance of correctly handling Chinese characters (and other non-ASCII characters) when sending alerts via WeChat. Unfortunately, this can be a common pitfall, especially when using Python scripts to send notifications.
To set the stage, let's dive into what happened and how we can resolve this issue.
The Problem
You had written a Python script to send Zabbix alerts to WeChat using the `requests` library. The script was working fine until you started receiving garbled Chinese characters in your WeChat messages. ??After some investigation, you discovered that the issue was related to encoding. Specifically, the default encoding used by Python's `requests` library is UTF-8, which can lead to character encoding issues when dealing with non-ASCII characters like Chinese.
The Cause
When sending data over HTTP, the encoding of the data matters. In this case, the Zabbix server was expecting Unicode (UTF-8) encoded text, but your Python script was sending ASCII-encoded text instead. This mismatch caused the garbled characters to appear in WeChat.
To illustrate this, let's consider an example:
Suppose you want to send a simple alert message containing the Chinese character "" (the word "hello" in Simplified Chinese). In UTF-8 encoding, this character would be represented as `0xE5` followed by `0x98` and `0xAC`. However, if your Python script sends ASCII-encoded text, it would only transmit the raw bytes `0xE598AC`, which wouldn't be correctly interpreted by WeChat.
The Solution
To fix this issue, you can use the `ensure_ascii=False` parameter when sending requests with the `requests` library. This tells Python to encode the request body using UTF-8, ensuring that non-ASCII characters are properly represented.
Here's an updated version of your Python script:
```pythonimport requests ... (rest of the script remains the same)
requests.post(
' headers={'Content-Type': 'application/json'},
data=json.dumps({
Your alert message with Chinese characters 'text': '你好' Hello in Simplified Chinese }),
ensure_ascii=False)
```
By setting `ensure_ascii=False`, you're telling Python to encode the request body using UTF-8, which ensures that non-ASCII characters like Chinese are correctly represented.
Additional Tips
When working with non-ASCII characters in Python:
1. Use Unicode-aware libraries: Make sure the libraries you use (e.g., `requests`) support Unicode encoding.
2. Specify encoding: When sending data over HTTP, specify the encoding using parameters like `ensure_ascii=False` or `encoding=utf-8`.
3. Verify character encodings: Double-check that your Python script and the receiving end (in this case, WeChat) are using compatible character encodings.
By following these best practices, you'll be well on your way to sending accurate and readable Chinese characters in your Zabbix alerts via WeChat! ??