Django Python coding error, non-ASCII character '\ xe5'

Hi, I encountered a coding error with Python Django. In my views.py, I have the following:

from django.shortcuts import render from django.http import HttpResponse from django.template.loader import get_template from django.template import Context # Create your views here. def hello(request): name = 'Mike' html = '<html><body>Hi %s, this seems to have !!!!worked!</body></html>' % name return HttpResponse(html) def hello2(request): name = 'Andrew' html = '<html><body>Hi %s, this seems to have !!!!worked!</body></html>' % name return HttpResponse(html) # -*- coding: utf-8 -*- def hello3_template(request): name = u'ε“ˆε“ˆ' t = get_template('hello3.html') html = t.render(Context({'name' : name})) return HttpResponse(html) 

I got the following error:

Syntax Error at / hello3_template /

The non-ASCII character '\ xe5' in the file D: \ WinPython-32bit-2.7.5.3 \ django_test \ article \ views.py on line 19, but no encoding is declared; see http://www.python.org/peps/pep-0263.html for details (views.py, line 19)

I am browsing this link, but I am still puzzled by how to resolve it.

Could you help me? Thanks, smallbee

As Lalo points out, the next line should be at the top

 # -*- coding: utf-8 -*- 

Thank you all.

+6
source share
2 answers

Well, here you are:

Put # -*- coding: utf-8 -*- at the top of the file, it will determine the encoding.

docs says:

Python will use ASCII as the default encoding by default unless encoding hints are given otherwise.

 To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: 

So you should start the code:

 # -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse from django.template.loader import get_template ... 

Hope helps

+10
source

If you read PEP 263 , it clearly states:

To determine the encoding of the source code, the magic comment must be placed in the source files either on the first or second line in the file ...

(The original sentence said that this should be the first line after # !, if there is one, but apparently it turned out to be easier to implement using the "first or second line" rule.)

Actual reference documents describe the same thing in a less friendly but more rigorous way, for 3.3 and 2.7 .

The "magic comment" that appears later in the file is not magical, it is just a comment that misleads you without affecting the Python compiler.

UTF-8 for u'ε“ˆε“ˆ' is '\xe5\x93\x88\xe5\x93\x88' , so these are bytes in the file. In recent versions of Python (including 2.7 and all 3.x), the default encoding is always ASCII if the file does not start with the UTF specification (as some Microsoft editors do); even in 2.3-2.6 it is usually ASCII; in earlier versions it is Latin-1. Attempting to interpret '\xe5\x93\x88\xe5\x93\x88' will fail with the exact exception that you saw.

+1
source

All Articles