2013-12-21 44 views
6

嗨, 我遇到了Python Django的编码错误。 在我的views.py,我有以下几点:Python Django编码错误,非ASCII字符' xe5'

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) 

我得到了以下错误:在/ hello3_template

的SyntaxError/

非ASCII字符' \ xe5 '文件D:\ WinPython-32bit-2.7.5.3 \ django_test \ article \ views.py在第19行,但没有声明编码;有关详细信息,请参阅 http://www.python.org/peps/pep-0263.html(views.py,第19行)

我查找该链接,但我仍然对如何解决该链接感到困惑。

你能帮忙吗? 谢谢, smallbee

作为拉洛指出,以下行必须是在顶部

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

谢谢所有。

+3

不该'# - * - 编码:UTF-8 - * - '在文件顶部? – lalo

+0

嗨,你好,你是对的。它在我把这条线放在最上面之后起作用。谢谢。 – smallbee

+0

@lalo:将其写为答案;如果你链接到文档并解释它,那几乎肯定是他的问题。 – abarnert

回答

10

好了,你在这里:

# -*- coding: utf-8 -*-文件顶部,它定义德编码。

docs说:

Python will default to ASCII as standard encoding if no other encoding hints are given.

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: 

所以,你的代码必须开始:

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

希望帮助

1

如果你读PEP 263,上面清清楚楚地写着:

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…

(原来的建议说,它是#后的第一线!如果有,但据推测它竟然是容易以“第一条或第二条”规则实施)

对于3.32.7,实际参考文档以不太友好但更严格的方式描述相同的事物。

稍后在文件中出现的“魔术评论”并不神奇,它只是一个评论,误导读者而不影响Python编译器。

对于u'哈哈'的UTF-8是'\xe5\x93\x88\xe5\x93\x88',所以那些是文件中的字节。在最近的Python版本(包括2.7和全部3.x版本)中,默认编码始终是ASCII,除非文件以UTF BOM开头(正如一些Microsoft编辑喜欢的那样);即使在2.3-2.6中通常也是ASCII;在早期版本中,它是Latin-1。尝试解释'\xe5\x93\x88\xe5\x93\x88'将会失败,但您看到的确切例外情况。

+0

谢谢你指出,abarnert – smallbee

相关问题