Google App Engine中的UnicodeDecodeError

时间:2013-01-23 09:00:29

标签: python html google-app-engine jinja2

在我的项目中(使用Python,Html和Jinja2),我有一个带有电影图片的home_page,每张图片都会显示一个包含电影数据的特定页面。当我尝试使用电影数据呈现页面时,我收到以下错误(我尝试删除每个元素,例如删除moving.summary和错误,然后在上面的参数上标记):

    Traceback (most recent call last):
      File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1536, in __call__
        rv = self.handle_exception(request, response, e)
      File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1530, in __call__
        rv = self.router.dispatch(request, response)
      File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1278, in default_dispatcher
        return route.handler_adapter(request, response)
      File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1102, in __call__
        return handler.dispatch()
      File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 572, in dispatch
        return self.handle_exception(e, self.app.debug)
      File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 570, in dispatch
        return method(*args, **kwargs)
      File "C:\Users\User\Desktop\imovie-good\main.py", line 77, in get
        self.response.out.write(template.render(template_values))
      File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 894, in render
        return self.environment.handle_exception(exc_info, True)
      File "C:\Users\User\Desktop\imovie-good\movie_data.html", line 7, in top-level template code
        <td> Movie Name: {{movie_data.name}}</td>
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

这是我的python代码:

    import webapp2
    import jinja2
    import os
    import datetime
    import time
    import cgi
    from google.appengine.ext import db
    from google.appengine.api import users
    from google.appengine.api import images


    jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

    class Movie(db.Model):
        name = db.StringProperty()
        release_date = db.StringProperty()
        duration = db.StringProperty()
        director = db.StringProperty()
        actors = db.StringProperty(multiline=True)
        summary = db.StringProperty(multiline=True)
        picture = db.BlobProperty()
        trailer = db.StringProperty(multiline=True)
        date = db.DateTimeProperty(auto_now_add=True)

    class Movie_Data(webapp2.RequestHandler):
        def get(self):
            movie_key = self.request.get('movie_key')
            movie_data = Movie.get(movie_key)

    template_values = {'movie_data': movie_data}
            template = jinja_environment.get_template('movie_data.html')
            self.response.out.write(template.render(template_values))

    class Image(webapp2.RequestHandler):
        def get(self):
            movie = db.get(self.request.get('img_id'))
            if movie.picture:
                self.response.headers['Content-Type'] = 'image/jpeg'
                self.response.out.write(movie.picture)
            else:
                self.response.out.write("No Image")

    class Main(webapp2.RequestHandler):
        def get(self):
            movies = db.GqlQuery("SELECT * "
                                "FROM Movie "
                                "ORDER BY release_date DESC LIMIT 5")
            template_values = { 'movies': movies}                                   
            template = jinja_environment.get_template('home_page.html')
            self.response.out.write(template.render(template_values))

    class Admin(webapp2.RequestHandler):
        def get(self):
            template_values = {}
            template = jinja_environment.get_template('admin.html')
            self.response.out.write(template.render(template_values))


        def post(self):
            name = self.request.get('name')
            release_date = self.request.get('release_date')
            c = time.strptime(release_date,"%m/%d/%Y")
            release_date = time.strftime("%m%d%Y",c)
            duration = self.request.get('duration')
            director = self.request.get('director')
            actors = self.request.get('actors')
            summary = self.request.get('summary')
            picture = self.request.get('img')
            trailer = self.request.get('trailer')

            movie = Movie(key_name = name)
            movie.release_date = release_date
            movie.duration = duration
            movie.director = director
            movie.actors = actors
            movie.summary = summary
            movie.picture = db.Blob(picture)
            movie.trailer = trailer
            movie.put()
            self.redirect('/')



    app = webapp2.WSGIApplication([('/admin', Admin), ('/', Main), ('/img', Image), ('/movie_data', Movie_Data)], debug=True)

这是我的home_page的html:

    <html>
    <body>
        <table>
            <th>Top Movies</th>

            {% for movie in movies %}
            <tr>
                <td>{{movie.key().name() }} &nbsp</td>
            </tr>
            <tr>
                <td><a href = "/movie_data?movie_key = {{movie.key()}}"> <img src = "/img?img_id={{movie.key()}}"> </td>


            </tr>

            {% endfor %}

            <a href = "/admin">admin</a>

        </table>
    </body>
</html>

这是我的movie_data html代码:

  <html>
    <body>
        <div>
            <table>
                <tr>
                    <td rowspan ="6">{{ movie_data.picture }}</td>
                    <td> Movie Name: {{movie_data.name}}</td> 
                </tr>
                <tr>
                    <td> Release Date: {{movie_data.release_date}}</td> 
                </tr>
                <tr>
                    <td> Duration (minutes): {{movie_data.duration}}</td> 
                </tr>
                <tr>
                    <td> Director: {{movie_data.director}}</td> 
                </tr>
                <tr>
                    <td> Actors: {{movie_data.actors}}</td> 
                </tr>
                <tr>
                    <td> Summary: {{movie_data.summary}}</td> 
                </tr>
                <tr>
                    <td colspan ="2"> {{movie_data.trailer}} </td>
                </table>
        </div>      
    </body>
</html>

2 个答案:

答案 0 :(得分:1)

我不认为取决于字符串movie_data.name。创建错误的实体更可能是movie_data.image。根据{{​​3}}检查您的相关代码。

实际上,您需要一个单独的处理程序来提供图像,请参阅serving blob documentation中的示例或只替换:

{{ movie_data.picture }} 

<img src='data:image/png;base64,{{movie_data.picture.encode("base64")}}'>

答案 1 :(得分:0)

Jinja2仅限unicode:You have to pass unicode objects or bytestrings that only consist of ASCII characters to the render function

所以我猜你的movie.name是一个包含非ascii字符的字节字符串。

我建议你:

a)将unicode存储在数据库中,或

b)转换为模板内的unicode(我不确定这是否可以在Jinja2中使用)。如果可能,则此语法类似于:

<td> Movie Name: {{unicode(movie_data.name, "utf8")}}</td>

我强烈建议采用方法a)。如果使用b)(如果该语法在jinja模板中甚至是合法的),则需要知道字节串的编码。

一般的Python提示是始终使用unicode字符串。含义:

  1. 尽快将外部字符串输入转换为unicode(下面是HTML表单处理的示例)。这称为解码。 unicode(my_byte_string, encoding)(或my_byte_string.decode(encoding))。 encoding可以是'ascii','utf8'等。
  2. 尽可能晚地将unicode转换为字节字符串(如果有的话)。如果需要通过网络传输unicode或写入文件,通常需要转换为字节字符串。这称为编码。 my_unicode_string.encode(encoding)
  3. 在源代码中使用unicode文字。使用movie.name = u"Iron Man"代替movie.name = "Iron Man"
  4. 修改

    看起来您将电影保存到Admin.post方法内的数据库中。要在数据存储区中存储unicode值,请使用以下代码:

    name = unicode(self.request.get('name'), "utf8")
    # and so on for all the StringProperty values
    

    编辑2

    根据Python 2.7, Appengine Data Store & Unicode,您在使用webapp或webapp2时无需解码self.request.get("...")

    我会在post方法中放入一些断言,以检查从请求中获取的值是否实际上是unicode:

    assert isinstance(self.request.get("name"), unicode)
    

    还要检查从数据存储中获取的对象属性是否为unicode(在Main.get中):

    movies = db.GqlQuery("...")
    assert all(isinstance(movie.name, unicode) for movie in movies)