I have a method that returns the following error message (the problem is in the accents)
urlopen error [Errno 10061] A connection cannot be established because the destination computer expressly denied the connection
When trying to do json.dumps in python I get the error:
'ascii' codec can't decode byte .....
I know it's not a json error because it marks the same thing when calling the print method, but I haven't been able to
I tried:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
variable.encode("utf8")
How can I get the string with the accents and be able to use json.dumps()
?
After reading a lot about unicode and django I realize that:
I have to change the first string to unicode, which I do with the following code:
With this I have it in unicode with the latin1 character set
As what I want is a json response in django in json.dumps I pass the parameter ensure_ascii=False, and then I execute the encode
If you can upgrade to Python 3.x, the standard encoding is utf-8 and all strings are unicode by default, so you won't have that problem.
In python 2.x the standard encoding is ascii, which means it will give you errors with accents, signs, etc... You can change the default encoding to whatever you want by including the following code (Assuming you want utf-8 ):
In a file that is in the Python search path
sitecustomize.py
and that must be called, necessarily, . This file may or may not already be created, depending on your distribution and circumstances, so search your system first and create/edit it accordingly.