2013-12-21 9 views
6

こんにちは Python Djangoでエンコーディングエラーが発生しました。私のviews.pyで 、私は次のようしている:Python Djangoエンコーディングエラー、 ' xe5'非ASCII文字

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を参照してください。(view.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を含む)では、ファイルがUTF BOMで始まらない限り(デフォルトのエンコーディングはASCIIです)(Microsoftのエディタのように) 2.3-2.6でも、それは通常ASCIIです。以前のバージョンではLatin-1です。 '\xe5\x93\x88\xe5\x93\x88'を解釈しようとすると、あなたが見た例外を除いて失敗します。

+0

ありがとう、abarnert – smallbee

関連する問題