Description:A Web service, the original business logic is to cache the results of the MySQL query in Redis for one hours, speeding up the response of the request. One problem now is that the response of the corresponding encoding is returned based on the specified encoding of the request.
The first is to modify the response of the body encoding, because MySQL is going out is Unicode, so directly use "content = Content.encode (charset)
"To convert, and then include the character encoding in the request header.
Solution:But this test down, some requests can return the correct encoding format, some or garbled, and finally guess is the data type in the Redis problem
Cached data taken out of the #redis type (content) <type ' str ' >import chardetchardet.detect (content) {' confidence ': 0.99, ' encoding ': ' Utf-8 '} #编码还是utf -8#msyql field data type (content) <type ' Unicode ' >
One way to do this is to store Unicode encoding in Redis, and when the cache is Unicode, why is STR being taken out of Redis? You may need special treatment. One way is to deal with the content judgment type, respectively.
The final resolution fragment:
If Isinstance (content, Unicode): content = Content.encode (charset) elif isinstance (content, str): content = Content.decode ("Utf-8"). Encode (CharSet)
Reference: Http://www.pythonclub.org/python-basic/codec
This article is from the "Orangleliu Notebook" blog, reproduced please be sure to keep this source http://blog.csdn.net/orangleliu/article/details/41445947
Author Orangleliu using Attribution-NonCommercial-sharing protocol in the same way
[Python]mysql data cache to Redis to remove time encoding problem