What I know is:
# -*- coding: utf-8 -*-
It is used to declare the encoding of a Python source file, once I set the encoding name, Python parser will interpret the file using the given encoding. I call it "file encoding";from __future__ import unicode_literals
I'm doing my tasks using Python2.7, and I usefrom __future__ import unicode_literals
to change the default type of string from "str" to "unicode". I call it "string encoding";sys.setdefaultencoding('utf8')
But sometimes, I get an error in Django, for example, I stored Chinese in admin, then I visited the releated pagesUnicodeEncodeError at /admin/blog/vulpaper/29/change/
'ascii' codec can't encode characters in position 6-13: ordinal not in range(128)
....the more error information
The string that could not be encoded/decoded was: emcms外贸网站管理系统for this problem, I will write
sys.setdefaultencoding('utf8')
in Django settings file to solve it.
But Actually, I don't know the tech detail of the above.
What make me confused is:
1. Since I set the python source file encoding, why should I set the string encoding to ensure my string's encoding is my favorite encoding?
What's the different between "file encoding" and "string encoding"?
2. Since I set the "file encoding" and "string encoding", why do UnicodeEncodeError still happen?