Python UnicodeDecodeError:';ascii';编解码器可以';t解码字节0xe2序号不在范围内(128)

Python UnicodeDecodeError:';ascii';编解码器可以';t解码字节0xe2序号不在范围内(128),python,google-app-engine,ascii,asciiencoding,Python,Google App Engine,Ascii,Asciiencoding,我正试图用Python在Google app Engine中编写我的第一个应用程序(应用程序链接:-它只是一个实验应用程序)。整个代码如下 但是,当我提交数据时,我得到了这个错误(显示在日志上): 第265行在该if块中: self.response.out.write(yourcontract % {"resident":geted_resident_name, "nacionality":geted_user_nac

我正试图用Python在Google app Engine中编写我的第一个应用程序(应用程序链接:-它只是一个实验应用程序)。整个代码如下

但是,当我提交数据时,我得到了这个错误(显示在日志上):

第265行在该if块中:

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
                                      })
我试着做些改变,读一些类似的文章(比如或),但没有任何帮助。我不知道这段代码出了什么问题。有人能找出导致这种错误的原因以及如何修复它吗

我正在使用Python 2.7

提前感谢您的帮助

# -*- 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 webapp2

    form = """

    <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)s

    In consideration of the agreements of the Resident(s), known as: %(resident)s The owner hereby rents them the dwelling located at %(residentAdress)s, for the period commencing on the %(dateStarts)s, and monthly thereafter until the last day of %(dateEnds)s, 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)s - Resident

    ___________________________________________________
    %(owner)s – owner

    ___________________________________________________
    %(witness)s – Witness

      </body>
    </html>

    """

    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):
           self.response.out.write(form %{"resident": "",
                                           "SSN": "",
                                           "driverLicense": "",
                                           "email":"",
                                           "resident_error": "",
                                           "SSN_error": "",
                                           "driverLicense_error": "",
                                           "email_error": ""})

        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)
#-*-编码:utf-8-*-
#-*-编码:utf-8-*-
#!/usr/bin/env python
#
#版权所有2007谷歌公司。
#
#根据Apache许可证2.0版(以下简称“许可证”)获得许可;
#除非遵守许可证,否则不得使用此文件。
#您可以通过以下方式获得许可证副本:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#除非适用法律要求或书面同意,软件
#根据许可证进行的分发是按“原样”进行分发的,
#无任何明示或暗示的保证或条件。
#请参阅许可证以了解管理权限和权限的特定语言
#许可证下的限制。
#
导入webapp2
form=”“”
与Python签订合同
.label{text align:right}
.错误{颜色:红色}
与Python签订合同
居民
%(常驻错误)s
民族性
许可证
SSN
%(SSN_错误)s
电子邮件(可选)
%(电子邮件错误)s

合同类型 房屋租赁合同 汽车租赁合同 其他


主人 房主 车主 其他所有者


目击者 卡尔·萨根 圣雄甘地

""" 您的合同:“”” 第二单元报名 %(合同类型)s 考虑到居民(称为:%(居民)s)的协议,业主特此将位于%(居民地址)s的住宅出租给他们,租期自%(日期开始)s开始,此后每月租期至%(日期结束)s的最后一天,届时本协议终止,考虑到业主允许其占用上述财产,特此同意以下条款: 租金:每月支付$(rentalSum)作为租金,从每月的第一天起提前到期支付。如果未能在到期时支付租金,业主将立即采取法律行动将住户驱逐出房屋并没收保证金。 滞纳金:本月1日后收到的租金将收取10%的滞纳金,外加每天(3.00)美元。 在(本地合同)接受此(日期合同)。 ___________________________________________________ %(居港)s-居港 ___________________________________________________ %(所有者)s–所有者 ___________________________________________________ %(证人)s–证人 """ 进口稀土 USER_RE=RE.compile(r“^[a-zA-Z0-9_u-]{3,20}$”) def有效_常驻(常驻): 返回用户匹配(常驻) PASS_RE=RE.compile(r“^.{3,20}$”) def有效\u SSN(SSN): 回程通行证重新匹配(SSN) 电子邮件\u RE=RE.compile(r“^[\S]+@[\S]+\.[\S]+$”) def有效电子邮件(电子邮件): 返回匹配的电子邮件(电子邮件) def escape_html:
对于((“&”、“&”)、(“>”、“>”)中的(i,o),(“您应该真正使用一个合适的模板系统。AppEngine附带了Jinja2

然而,与此同时,您的问题是您的模板是ASCII,而您的数据不是(无法判断它是utf-8还是unicode)。简单的解决方案是在每个模板字符串前面加上
u
,使其成为unicode

但是,您确实应该使用适当的模板系统。

这里是解决方案

解码(“utf-8”) 你没有 >>>“\x81”。解码(“utf-8”) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 文件“encodings/utf_8.py”,第7799行,解码 UnicodeDecodeError:“utf8”编解码器无法解码位置0中的字节0x81:意外的代码字节 >>>“a\x81b”。解码(“utf-8”,“替换”)#这将以正确的方式更好地解码。 u'a\ufffdb'
在代码顶部设置默认编码器

在appcfg.py中,它位于/google/appengine/tools/appcfg.py中

第73行添加

import sys
reload(sys)
sys.setdefaultencoding("ISO-8859-1")

检查此项:您是否尝试过编码('utf-8'),这可能会解决你的问题嗨,@Daniel Roseman,我开始使用jinja2,但是,你知道,我被这个错误绊住了:你能提供一些帮助吗?再次感谢!你的例子中的编码没有更好。你所取得的一切就是用替换非ASCII字符。我无法想象询问者会希望这个字符出现在他/她的dat中a、 这是唯一对我有效的解决方案,我尝试了另外两个,但都不起作用。谢谢。同样,将此添加到
import sys
reload(sys)
sys.setdefaultencoding("ISO-8859-1")