2013-12-21 47 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

相關問題