本文介绍了Python UnicodeDecodeError:'ascii'编解码器无法解码字节0xe2序号不在范围内(128)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Python在Google App Engine中编写我的第一个应用程序(应用程序链接: - 这只是一个实验性应用程序)。整个代码是波纹管。

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

 (...)第265行,获取contractType:geted_contractType 
UnicodeDecodeError:'ascii'编解码器无法解码位置949中的字节0xe2:序号不在范围内(128 )

第265行在这个块中:

  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,
c ontractType:geted_contractType
})

我尝试进行更改,读取类似awnswers 或),但没有任何帮助。我无法弄清楚这段代码出了什么问题。有人可以找出是什么导致这样的错误,以及如何解决它?



我使用Python 2.7。



在此先感谢您的帮助!

 # -  *  - 编码:utf-8  -  *  -  
# - * - 编码:utf-8 - * -
#!/ usr / bin / env python

#版权所有2007 Google Inc.根据Apache许可证版本2.0(许可证)许可的


#除遵守许可证外,您不得使用此文件。
#您可以在

#http://www.apache.org/licenses/LICENSE-2.0

#中获得许可证副本除非根据适用法律要求或书面同意,根据许可分发的软件
#以原样基础,
#分发,不附有任何形式的明示或暗示保证或条件。
#请参阅许可证以了解许可证下特定语言的管理权限和
#限制。


导入webapp2

form =

< html>
< head>
< title>与Python签订合约< / title>
< style type =text / css>
.label {text-align:right}
.error {color :red}
< / style>

< / head>

< body>
< h2> h2>
< form method =post>
< table>
< tr>
< td class =label>
居民
< / td>
< td>
< input type =textname =residentvalue =%(resident)s>
< / td>
< td class =error>%(resident_error)s

< / td>
< / tr>

< tr>
< td class =label>
nacionality
< / td>
< td>
< input type =textname =nacionalityvalue =>
< / td>
< / tr>

< tr>
< td class =label>
许可
< / td>
< td>
< input type =textname =driverLicensevalue =>
< / td>
< / tr>

< tr>
< td class =label>
SSN
< / td>
< td>
< input type =textname =SSNvalue =%(SSN)s>
< / td>
< td class =error> %(SSN_error)s
< / td>
< / tr>


< tr>
< td class =label>
电子邮件(可选)
< / td>
< td>
< input type =textname =emailvalue =%(email)s>
< / td>
< td class =error> %(email_error)s

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

< br>
< td class =label>
合约类型
< select name =contractType>
< option>房屋租赁合约< / option>
< option>租车合约< / option>
< option>其他< / option>
< / select>
< / td>
< br>
< br>

< br>
所有者
< select name =owner>
< option>房主\\ lt; / option>
< option>车主< / option>
< option>其他所有者< / option>
< / select>
< br>
< br>

< br>
见证人
< select name =witness>
< option> Carl Sagan< / option>
< option>圣雄甘地< / option>
< / select>
< br>
< br>

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

< / html>


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

< body>

%(contractType)s

考虑到居民的协议,被称为:%(居民)s所有者在此向其租赁位于%(residentAdress)s在%(dateStarts)开始的时间段内,以及此后的每月直到%(dateEnds)s的最后一天,此时该协议终止。居民在考虑到业主允许他们占用上述财产时,特此同意以下条款:

租金:作为租金支付每月$(rentalSum)从每个月的第一天起提前支付。未能在到期时支付租金将导致业主立即采取法律行动将房屋从房屋中驱逐出去并扣押保证金。
后续费用:本月首日后收到的租金将收取每天10%(3.00美元)的滞纳金。

在(localContract)处接受此(dateContract)。

___________________________________________________
%(居民)s - 居民

___________________________________________________
%(所有者) - 所有者 - 所有者

___________________________________________________ b $ b%(证人)s - 见证人

< / body>
< / html>



import re

USER_RE = re.compile(r^ [a-zA-Z0-9 _-] {3 ,20} $)
def valid_resident(驻留):
返回USER_RE.match(居民)

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)
$ b $ def escape_html(s) ((&,&),(>,>),(<,<), '''''''')):
s = s.replace(i,o)
返回s

导入时间

导入日期时间

def dateToday():
today = datetime.datetime.today()
todayDay = str(today.day)
todayMonth = str(today.month)
monthExt = {'1':'一月','2':'二月','3':'三月','4':'四月', 5':'五月','6':'六月','7':'七月','八':'八月','9':'九月','十''十月' :'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和valid_resident(resident_name))\
和(user_SSN和valid_SSN(user_SSN))\
和((不是user_email)或(user_email和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,
证人,所有者))
else:
如果不是valid_resident(resident_name):
resident_error =哦,不!这个居民的名字是无效的!
如果不是valid_SSN(user_SSN):
SSN_error =哦,不! SSN无效!
如果user_email而不是valid_email(user_email):
email_error =哦,不!电子邮件无效!
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_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)


解决方案

适当的模板系统。 Jinja2包含在AppEngine中。



然而,同时你的问题是你的模板是ASCII但你的数据不是(不能分辨是utf-8还是unicode )。简单的解决方案是在每个模板字符串前加上 u 使其成为Unicode。



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

I'm trying to write my first app in Google App Engine with Python (link of the app: http://contractpy.appspot.com/ - it's just an experimental app). The entire code is bellow.

But, when I submit the data, I'm getting this error (showed on logs):

(...) line 265, in get "contractType":geted_contractType
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 949: ordinal not in range(128)

Line 265 is in this if block:

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

I tried to make changes, read similar awnswers (like this or this), but nothing helped. I can't figure out in this code what is going wrong. Can someone figure out what is causing such error and how to fix it?

I'm using Python 2.7.

Thanks in advance for any help!

# -*- 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)
解决方案

You should really use a proper templating system. Jinja2 is included with AppEngine.

However in the meantime your problem is that your templates are ASCII but your data is not (can't tell if it's utf-8 or unicode). Easy solution is to prefix each template string with u to make it Unicode.

But, you should really use a proper templating system.

这篇关于Python UnicodeDecodeError:'ascii'编解码器无法解码字节0xe2序号不在范围内(128)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:47