搜尋

首頁  >  問答  >  主體

python的jinja中中文問題

# -*- coding: utf-8 -*-
import shelve
from datetime import datetime
from flask import Flask, render_template, redirect, request, escape, Markup

app = Flask(__name__)

DATA_FILE = 'message'

def save_data(name, comment, create_at):
    """保存提交的数据"""
    database = shelve.open(DATA_FILE)
    if 'message_list' not in database:
        message_list = []
    else:
        message_list = database['message_list']

    message_list.insert(0, {
        'name': name,
        'comment': comment,
        'create_at': create_at,
    })
    database['message_list'] = message_list
    database.close()

def load_data():
    """返回已提交的数据"""
    database = shelve.open(DATA_FILE)
    message_list = database.get('message_list', [])
    database.close()
    return message_list

def post():
    """用于提交评论的URL"""
    name = request.form.get('name')
    comment = request.form.get('comment')
    create_at = datetime.now()

    save_data(name, comment, create_at)
    return redirect('/')

@app.route('/')
def index():
    message_list = load_data()
    return render_template('index.html', message_list=message_list)

@app.template_filter('nl2br')
def nl2br_filter(s):
    return escape(s).replace("\n", Markup('<br>'))

@app.template_filter('datetime_fmt')
def datetime_fmt_filter(dt):
    return dt.strftime('%Y-%m-%d %H:%M:%S')

if __name__ == '__main__':
    app.run('127.0.0.1', 8001, debug=True)
{% for message in message_list %}
        <h3>{{ message.name }} 的消息 ({{ message.create_at | datetime_fmt }}):</h3>
        <p>
            {{ message.comment | nl2br }}<p>
        </p>
{% endfor %}

執行程式錯誤提示:

UnicodeDecodeError

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 16: ordinal not in range(128)

就是有中文的這一行出錯了,請問怎麼處理呢

代言代言2720 天前1011

全部回覆(1)我來回復

  • 怪我咯

    怪我咯2017-06-14 10:54:27

    報錯應該是你python程序那邊報吧, 試下把你python那邊的中文編碼處理下, 或者試下全部用unicode吧, 參考下面:

    with open('test_%s.html' % date, 'w') as f:
            f.write(a.render(
                {
                    'date': date,
                    'total': 30,
                    'title': u'报告' % date,  
                    u'project_list': project_info
                }).encode('utf8')
            )
    

    回覆
    0
  • 取消回覆