When using Django to do web development on Ubuntu, I encountered the problem that Chinese saved to Cookie can't be resolved, and finally solved the problem after several steps:
- modifying The/usr/lib/python3.4/wsgiref/headers.py file, forcing the use of UTF-8 encoding
- Encode the value stored in the cookie to convert the string into a byte array
- Use JavaScript to decode the value of the cookie that needs to be read when the page loads
Here are the specific steps:
Modify/usr/lib/python3.4/wsgiref/headers.py file, forcing the use of UTF-8 encoding
Locate headers.py, open file, and modify the following:
def __bytes__ (self): return str (self). Encode ('iso-8859-1')
Change to:
def __bytes__ (self): return str (self). Encode ('utf-8')
With this operation, cookies can be logged properly when running manager.py runserver locally. However, when deployed directly to Apache, it will return 500 error when it comes to saving a Chinese cookie. The following error message is displayed in Apache log:
... Mod_wsgi (pid=5603): Exception occurred processing Wsgi script '/.../wsgi.py '.
Then the second step to solve the problem of Web page open.
encode the value stored in the cookie to convert the string into a byte array
The following encoding conversions are required where the cookie is set in Django:
def Setcookies (response, Key, querycollection): if key in QueryCollection:response.set_cookie (Key.lower (), bytes ( Querycollection[key], " utf-8 "). Decode ( " iso-8859-1 " ) ) else : Response.set_cookie (Key.lower (), )
This step is complete, the problem of saving cookies is solved, when you open the Web page, you can receive the normal content from the server.
Then proceed to the third step to solve the problem of garbled cookies.
use JavaScript to decode the value of the cookie that needs to be read when the page loads
In the corresponding JavaScript code, make the following conversions:
functionReadcookie (name) {varNameeq = name + "="; varCA = Document.cookie.split ('; ')); for(varI=0;i < ca.length;i++) { varc =Ca[i]; while(C.charat (0) = = ") c = c.substring (1, c.length); if(C.indexof (Nameeq) = = 0)return decodeuricomponent (Escape (C.substring (nameeq.length,c.length). Replace (/"/g," "))); } return NULL;}
Ok! The problem with Chinese cookies is solved. :-)
Django Chinese cannot be converted to a latin-1 encoded solution