[Python]mysql data cache to Redis to remove time encoding problem

Source: Internet
Author: User
Tags mysql query

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.