buzul 2017-04-05 10:32 采纳率: 0%
浏览 955

flask写tag页面,URL中有中文访问就出错。flask运行在windows2012 iis8下

flask写tag页面,URL中有中文访问就出错。flask运行在windows2012 iis8下。在linux就没有这种问题

感觉的是编码的问题,可是各种编码解码都上了,还是出错。
图片说明

 @app.route('/s/<string:name>')
@app.route('/s/<string:name>/<int:pn>')
def tags(name,pn=1):
    es = es.search(index="xxxx", body={'query':{'match':{'title':name}}}, size=20)
    res = res['hits']['hits']
    return render_template('tags.html', res=res)
  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-05 16:30
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    你使用了<而不是&lt;作为HTML实体,这是导致问题的原因。你应该将你的HTML中的&lt;替换为<。如果你正在使用Python Flask框架,并且你想处理URL中包含中文的情况,你可以尝试以下方法:

    1. 使用正则表达式来解析和过滤URL中的中文字符。
    import re
    
    # 假设你的URL是这样的:http://example.com/s/%E5%9B%A0%E7%9F%B3
    url = "http://example.com/s/%E5%9B%A0%E7%9F%B3"
    
    # 将URL中的中文字符转换为Unicode字符串
    unicode_url = url.encode("utf-8")
    
    # 使用正则表达式来匹配和提取中文字符
    matches = re.findall(r'[\u4e00-\u9fa5]', unicode_url.decode())
    
    for match in matches:
        # 替换中文字符以去除它们
        url = url.replace(match, "")
    
    print(url)  # 输出:http://example.com/s/鬼吹灯
    
    1. 使用Flask的render_template函数来渲染带有中文显示的文字模板。例如,你可以创建一个名为tags.html的文件,其中包含以下内容:
    {% for item in res %}
    <div>
        <h3>{{item.title}}</h3>
    </div>
    {% endfor %}
    

    然后,在你的Flask应用中,你可以使用res变量来传递数据给这个模板,如下所示:

    from flask import render_template
    
    @app.route('/s/<string:name>/<int:pn>')
    def tags(name, pn=1):
        es = es.search(index="xxxx", body={'query':{'match':{'title':name}}}, size=20)
        res = res['hits']['hits']
    
        # 使用正则表达式来过滤掉中文字符
        matches = [match.replace("\u4e00", "").replace("\u9fa5", "") for match in res]
    
        return render_template('tags.html', res=matches)
    

    现在,当你的URL中包含中文时,这些字符将被正确地移除并显示在页面上。

    评论

报告相同问题?