Python UnicodeDecodeError:“utf8”编解码器无法解码字节...意外的代码字节

2024-01-23

Python 新手构建他的第一个 Web 应用程序的旅程(应用程序链接:http://contractpy.appspot.com/ http://contractpy.appspot.com/- 这只是一个实验性应用程序)。

遵循a的建议堆栈溢出用户 https://stackoverflow.com/questions/10934184/python-unicodedecodeerror-ascii-codec-cant-decode-byte-0xe2-ordinal-not-in-r,我开始使用模板系统:Jinja2(我使用的是Python 2.6),但现在我遇到了这个错误:

2012-06-17 11:44:39 Running command: "['C:\\Python26\\pythonw.exe', 'C:\\Program Files (x86)\\Google\\google_appengine\\dev_appserver.py', '--admin_console_server=', '--port=8084', 'C:\\Users\\CG\\Documents\\udacity\\contract']"
Warning: You are using a Python runtime (2.6) that is older than the production runtime environment (2.7). Your application may be dependent on Python behaviors that have changed and may not work correctly when deployed to production.
WARNING  2012-06-17 14:44:41,993 datastore_file_stub.py:518] Could not read datastore data from c:\users\cg\appdata\local\temp\dev_appserver.datastore
WARNING  2012-06-17 14:44:42,005 dev_appserver.py:3401] Could not initialize images API; you are likely missing the Python "PIL" module. ImportError: No module named _imaging
INFO     2012-06-17 14:44:42,025 dev_appserver_multiprocess.py:647] Running application dev~contractpy on port 8084: http://localhost:8084
INFO     2012-06-17 14:44:42,025 dev_appserver_multiprocess.py:649] Admin console is available at: http://localhost:8084/_ah/admin
WARNING  2012-06-17 14:44:47,171 py_zipimport.py:139] Can't open zipfile C:\Python26\lib\site-packages\setuptools-0.6c11-py2.6.egg-info: IOError: [Errno 13] file not accessible: 'C:\\Python26\\lib\\site-packages\\setuptools-0.6c11-py2.6.egg-info'
ERROR    2012-06-17 14:44:47,674 wsgi.py:189] 
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 187, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 225, in _LoadHandler
    handler = __import__(path[0])
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 676, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 1858, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 676, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 1722, in FindAndLoadModule
    description)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 676, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 1665, in LoadModuleRestricted
    description)
  File "C:\Users\CG\Documents\udacity\contract\main.py", line 60, in <module>
    class MainHandler(webapp2.RequestHandler):
  File "C:\Users\CG\Documents\udacity\contract\main.py", line 71, in MainHandler
    template = jinja_environment.get_template('index.html')
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 719, in get_template
    return self._load_template(name, self.make_globals(globals))
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 693, in _load_template
    template = self.loader.load(self, name, globals)
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\loaders.py", line 115, in load
    source, filename, uptodate = self.get_source(environment, name)
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\loaders.py", line 169, in get_source
    contents = f.read().decode(self.encoding)
  File "C:\Python26\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 3403: unexpected code byte
INFO     2012-06-17 14:44:47,713 dev_appserver.py:2891] "GET / HTTP/1.1" 500 -
INFO     2012-06-17 14:44:47,801 dev_appserver.py:2891] "GET /favicon.ico HTTP/1.1" 200 -
ERROR    2012-06-17 14:52:18,345 wsgi.py:189] 
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 187, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 225, in _LoadHandler
    handler = __import__(path[0])
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 676, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 1858, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 676, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 1722, in FindAndLoadModule
    description)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 676, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 1665, in LoadModuleRestricted
    description)
  File "C:\Users\CG\Documents\udacity\contract\main.py", line 60, in <module>
    class MainHandler(webapp2.RequestHandler):
  File "C:\Users\CG\Documents\udacity\contract\main.py", line 71, in MainHandler
    template = jinja_environment.get_template('index.html')
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 719, in get_template
    return self._load_template(name, self.make_globals(globals))
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 693, in _load_template
    template = self.loader.load(self, name, globals)
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\loaders.py", line 115, in load
    source, filename, uptodate = self.get_source(environment, name)
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\loaders.py", line 169, in get_source
    contents = f.read().decode(self.encoding)
  File "C:\Python26\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 3403: unexpected code byte
INFO     2012-06-17 14:52:18,378 dev_appserver.py:2891] "GET / HTTP/1.1" 500 -
INFO     2012-06-17 14:52:18,470 dev_appserver.py:2891] "GET /favicon.ico HTTP/1.1" 200 -

我正在使用 PyScripter 并将其设置为以 utf-8 进行编码:

我在 stackoverflow 上进行了搜索,发现了很多问题,但我不明白我的情况出了什么问题以及如何修复它。

预先感谢您的任何帮助!

这是我的代码:

# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os

import webapp2

import jinja2

jinja_environment = jinja2.Environment(autoescape=True,
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))

import re

USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
def valid_resident(resident):
    return USER_RE.match(resident)

PASS_RE = re.compile(r"^.{3,20}$")
def valid_SSN(SSN):
    return PASS_RE.match(SSN)

EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
def valid_email(email):
    return EMAIL_RE.match(email)

def escape_html(s):
    for (i,o) in (("&","&"), (">",">"), ("<","<"), ('"','"')):
        s = s.replace(i,o)
        return s

import time

import datetime

def dateToday():
    today = datetime.datetime.today()
    todayDay = str(today.day)
    todayMonth = str(today.month)
    monthExt = {'1':' January ', '2':'February', '3':' March ', '4':'April', '5':'May', '6':'June', '7 ':' July ', '8':'August', '9':'September', '10':'October', '11':'November ', '12':'December'}
    todayYear = str(today.year)
    return(todayDay + ' of  ' + monthExtenso[todaymonth] + ' of ' + todayYear)

class MainHandler(webapp2.RequestHandler):
    def get(self):
       template_values = {"resident": "",
                                       "SSN": "",
                                       "driverLicense": "",
                                       "email":"",
                                       "resident_error": "",
                                       "SSN_error": "",
                                       "driverLicense_error": "",
                                       "email_error": ""}

    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))

    def write_form(self, text_write):
       self.response.out.write(text_write)

    def post(self):
        resident_name = self.request.get(escape_html("resident"))
        user_nacionality = self.request.get("nacionality")
        user_SSN = self.request.get(escape_html('SSN'))
        user_email = self.request.get(escape_html('email'))
        user_driverLicense = self.request.get(escape_html('driverLicense'))
        resident_error = ""
        SSN_error = ""
        driverLicense_error = ""
        contract_type = self.request.get("contractType")
        owner = self.request.get("owner")
        witness  = self.request.get("witness ")

        if (resident_name and valid_resident(resident_name)) \
        and (user_SSN and valid_SSN(user_SSN)) \
        and ((not user_email) or (user_email and valid_email(user_email))):
            self.redirect('/yourcontract?resident=%s&nacionality=%s&SSN=%s&driverLicense=%s&email=%s&witness=%s&owner=%s' % (resident_name, user_nacionality, user_SSN, user_driverLicense, user_email,
witness, owner))
        else:
            if not valid_resident(resident_name):
                resident_error = "Oh no!!! this resident name isn't valid!"
            if not valid_SSN(user_SSN):
                SSN_error = "Oh no!!! SSN isn't valid!"
            if user_email and not valid_email(user_email):
                email_error = "Oh no!!! e-mail isn't valid!"
            self.write_form(form % {"resident":resident_name,
                                      "resident_error":resident_error,
                                      "SSN":user_SSN,
                                      "SSN_error":SSN_error,
                                      "driverLicense":user_driverLicense,
                                      "email":user_email,
                                      })

class yourcontractHandler(webapp2.RequestHandler):
    def get(self):
        geted_resident_name = self.request.get('resident')
        geted_user_nacionality = self.request.get("nacionality")
        geted_user_SSN = self.request.get('SSN')
        geted_user_email = self.request.get('email')
        geted_user_driverLicense = self.request.get('driverLicense')
        geted_resident_error = ""
        geted_SSN_error = ""
        geted_driverLicense_error = ""
        #geted_contract_type = self.request.get("contractType")
        geted_owner = self.request.get("owner")
        geted_witness  = self.request.get("witness")
        geted_contractType = self.request.get("contractType")



        self.response.out.write(yourcontract % {"resident":geted_resident_name,
                                      "nacionality":geted_user_nacionality,
                                      "SSN":geted_user_SSN,
                                      "SSN_error":geted_SSN_error,
                                      "driverLicense":geted_user_driverLicense,
                                      "email":geted_user_email,
                                      "witness ":geted_witness ,
                                      "owner":geted_owner,
                                      "contractType":geted_contractType
                                      })


app = webapp2.WSGIApplication([('/', MainHandler), ('/yourcontract', yourcontractHandler)],
                              debug=True)

这是我的模板代码:

<!DOCTYPE html>

<html>
  <head>
    <title>Contract with Python</title>
    <style type="text/css">
      .label {text-align: right}
      .error {color: red}
    </style>

  </head>

  <body>
    <h2>Contract with Python</h2>
    <form method="post">
      <table>
        <tr>
          <td class="label">
            resident
          </td>
          <td>
            <input type="text" name="resident" 

value= "%(resident)s">
          </td>
          <td class="error"> 

%(resident_error)s

          </td>
        </tr>

         <tr>
          <td class="label">
            nacionality
          </td>
          <td>
            <input type="text" 

name="nacionality" value= " ">
          </td>
        </tr>

        <tr>
          <td class="label">
            License
          </td>
          <td>
            <input type="text" 

name="driverLicense" value="">
          </td>
        </tr>

        <tr>
          <td class="label">
            SSN
          </td>
          <td>
            <input type="text" name="SSN" 

value="%(SSN)s">
          </td>
          <td class="error"> %(SSN_error)s
          </td>
        </tr>


        <tr>
          <td class="label">
            Email (optional)
          </td>
          <td>
            <input type="text" name="email" 

value="%(email)s">
          </td>
          <td class="error"> %(email_error)s

          </td>
        </tr>
      </table>

<br>
        <td class="label">
          Contract Type
          <select name = "contractType">
              <option>House  Rental 

Contract</option>
              <option>Car Rental 

Contract</option>
              <option>Other</option>
          </select>
          </td>
<br>
<br>

<br>
          owner
          <select name = "owner">
              <option>House owner</option>
              <option>Car owner</option>
              <option>Other owner</option>
          </select>
<br>
<br>

<br>
          Witness
          <select name = "witness">
              <option>Carl Sagan</option>
              <option>Mahatma Gandhi</option>
          </select>
<br>
<br>

      <input type="submit">
    </form>
  </body>

</html>
"""

yourcontract = """
<html>
  <head>
    <title>Unit 2 Signup</title>
  </head>

  <body>

{{contractType}}

In consideration of the agreements of the 

Resident(s), known as: {{resident}} The owner 

hereby rents them the dwelling located at 

{{residentAdress}}, for the period commencing 

on the {{dateStarts}}, and monthly thereafter 

until the last day of {{dateEnds}}, at which 

time this Agreement is terminated. Resident

(s), in consideration of owners permitting 

them to occupy the above property, hereby 

agrees to the following terms:

RENT: To pay as rental the sum of $ 

{{rentalSum}} per month, due and payable in 

advance from the first day of every month. 

Failure to pay rent when due will result in 

the owner taking immediate legal action to 

evict the Resident from the premises and seize 

the security deposit.
LATE FEE: Rent received after the first of the 

month will be subject to a late fee of 10% 

plus (3.00) dollars per day.

ACCEPTED THIS {{dateContract}}, at 

{{localContract}}.

______________________________________________

_____
{{resident}} - Resident

______________________________________________

_____
{{owner}} – owner

______________________________________________

_____
{{witness}} – Witness

</body>
</html>

Your index.html文件不是 UTF-8 有效的。使用代码编辑器打开该文件,然后另存为 UTF-8。您可以从异常回溯中跟踪错误:

  [...]
  File "C:\Users\CG\Documents\udacity\contract\main.py", line 71, in MainHandler
    template = jinja_environment.get_template('index.html')
  [...]
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\loaders.py", line 169, in get_source
    contents = f.read().decode(self.encoding)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 3403: unexpected code byte
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python UnicodeDecodeError:“utf8”编解码器无法解码字节...意外的代码字节 的相关文章

  • 在 python 程序中合并第三方库的最佳实践是什么?

    下午好 我正在为我的工作编写一个中小型Python程序 该任务需要我使用 Excel 库xlwt and xlrd 以及一个用于查询 Oracle 数据库的库 称为CX Oracle 我正在通过版本控制系统 即CVS 开发该项目 我想知道围
  • OpenCV Python cv2.mixChannels()

    我试图将其从 C 转换为 Python 但它给出了不同的色调结果 In C Transform it to HSV cvtColor src hsv CV BGR2HSV Use only the Hue value hue create
  • 如何在flask中使用g.user全局

    据我了解 Flask 中的 g 变量 它应该为我提供一个全局位置来存储数据 例如登录后保存当前用户 它是否正确 我希望我的导航在登录后在整个网站上显示我的用户名 我的观点包含 from Flask import g among other
  • gcloud.app.deploy 错误响应:[9] 应用程序启动错误:[email protected] start /app 节点 app.js

    我对收到的错误消息感到好奇 环境 谷歌应用引擎 Nodejs 弹性环境 没有安装 Express 服务器 设置 app yaml 包含标准信息 server js 已创建但为空 此时此刻 app js 已创建 但目前为空 错误 错误 gcl
  • 通过最小元素比较对 5 个元素进行排序

    我必须在 python 中使用元素之间的最小比较次数来建模对 5 个元素的列表进行排序的执行计划 除此之外 复杂性是无关紧要的 结果是一个对的列表 表示在另一时间对列表进行排序所需的比较 我知道有一种算法可以通过 7 次比较 总是在元素之间
  • Flask 会话变量

    我正在用 Flask 编写一个小型网络应用程序 当两个用户 在同一网络下 尝试使用应用程序时 我遇到会话变量问题 这是代码 import os from flask import Flask request render template
  • Python 函数可以从作用域之外赋予新属性吗?

    我不知道你可以这样做 def tom print tom s locals locals def dick z print z name z name z guest Harry print z guest z guest print di
  • 如何加速Python中的N维区间树?

    考虑以下问题 给定一组n间隔和一组m浮点数 对于每个浮点数 确定包含该浮点数的区间子集 这个问题已经通过构建一个解决区间树 https en wikipedia org wiki Interval tree 或称为范围树或线段树 已经针对一
  • 如何使用 OpencV 从 Firebase 读取图像?

    有没有使用 OpenCV 从 Firebase 读取图像的想法 或者我必须先下载图片 然后从本地文件夹执行 cv imread 功能 有什么办法我可以使用cv imread link of picture from firebase 您可以
  • BeautifulSoup 中的嵌套标签 - Python

    我在网站和 stackoverflow 上查看了许多示例 但找不到解决我的问题的通用解决方案 我正在处理一个非常混乱的网站 我想抓取一些数据 标记看起来像这样 table tbody tr tr tr td td td table tr t
  • 类模板参数推导 - clang 和 gcc 不同

    下面的代码使用 gcc 编译 但不使用 clang 编译 https godbolt org z ttqGuL template
  • Pandas:merge_asof() 对多行求和/不重复

    我正在处理两个数据集 每个数据集具有不同的关联日期 我想合并它们 但因为日期不完全匹配 我相信merge asof 是最好的方法 然而 有两件事发生merge asof 不理想的 数字重复 数字丢失 以下代码是一个示例 df a pd Da
  • 在本地 SDK 服务器上工作时,实时 Google App Engine 上出现 404

    我已经在GAE标准环境上部署了几个PHP应用程序 一切正常 现在我正在部署一个新应用程序 该应用程序位于由gcloudSDK按预期工作 终端命令 dev appserver py log level warning app yaml 问题是
  • 使用 Python 绘制 2D 核密度估计

    I would like to plot a 2D kernel density estimation I find the seaborn package very useful here However after searching
  • Python:如何将列表列表的元素转换为无向图?

    我有一个程序 可以检索 PubMed 出版物列表 并希望构建一个共同作者图 这意味着对于每篇文章 我想将每个作者 如果尚未存在 添加为顶点 并添加无向边 或增加每个合著者之间的权重 我设法编写了第一个程序 该程序检索每个出版物的作者列表 并
  • 发送用户注册密码,django-allauth

    我在 django 应用程序上使用 django alluth 进行身份验证 注册 我需要创建一个自定义注册表单 其中只有一个字段 电子邮件 密码将在服务器上生成 这是我创建的表格 from django import forms from
  • 在 Qt 中自动调整标签文本大小 - 奇怪的行为

    在 Qt 中 我有一个复合小部件 它由排列在 QBoxLayouts 内的多个 QLabels 组成 当小部件调整大小时 我希望标签文本缩放以填充标签区域 并且我已经在 resizeEvent 中实现了文本大小的调整 这可行 但似乎发生了某
  • 从列表指向字典变量

    假设你有一个清单 a 3 4 1 我想用这些信息来指向字典 b 3 4 1 现在 我需要的是一个常规 看到该值后 在 b 的位置内读写一个值 我不喜欢复制变量 我想直接改变变量b的内容 假设b是一个嵌套字典 你可以这样做 reduce di
  • NotImplementedError:无法将符号张量 (lstm_2/strided_slice:0) 转换为 numpy 数组。时间

    张量流版本 2 3 1 numpy 版本 1 20 在代码下面 define model model Sequential model add LSTM 50 activation relu input shape n steps n fe
  • Statsmodels.formula.api OLS不显示截距的统计值

    我正在运行以下源代码 import statsmodels formula api as sm Add one column of ones for the intercept term X np append arr np ones 50

随机推荐