簡體   English   中英

Python Django 編碼錯誤,非 ASCII 字符 '\\xe5'

[英]Python Django Encoding Error, Non-ASCII character '\xe5'

嗨,我在使用 Python Django 時遇到了編碼錯誤。 在我的 views.py 中,我有以下內容:

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/ 處的語法錯誤

第 19 行文件 D:\\WinPython-32bit-2.7.5.3\\django_test\\article\\views.py 中的非 ASCII 字符 '\\xe5',但未聲明編碼; 有關詳細信息,請參閱http://www.python.org/peps/pep-0263.html(views.py ,第 19 行)

我查找了那個鏈接,但我仍然對如何解決它感到困惑。

你能幫忙嗎? 謝謝,小蜜蜂

正如 lalo 指出的,以下行必須在頂部

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

謝謝你們。

好吧,你來了:

# -*- coding: utf-8 -*-放在文件頂部,它定義了編碼。

文檔說:

如果沒有給出其他編碼提示,Python 將默認使用 ASCII 作為標准編碼。

 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
...

希望有幫助

如果您閱讀PEP 263 ,它清楚地說明:

要定義源代碼編碼,必須將魔術注釋作為文件的第一行或第二行放入源文件中……

(最初的提議說它必須是#! 之后的第一行,如果有的話,但據推測,使用“第一行或第二行”規則更容易實現。)

對於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'將失敗,並顯示您看到的確切異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM