【问题标题】:Generate a link with utf-8 values and passing it to a Flask route [closed]生成带有 utf-8 值的链接并将其传递给 Flask 路由 [关闭]
【发布时间】:2018-09-30 10:12:47
【问题描述】:

我如何确保以下 html url 链接会以utf-8 编码返回自身?

<meta http-equiv="REFRESH" content="5; URL=http://superhost.gr/files/download?filename={{ filename }}">

就像现在一样,虽然文件名的值是从 Flask 中以utf-8 检索的,但它并没有形成 URL 链接也为utf-8

这是我获取此值并尝试使用它来下载文件的方式。

# Prepare selected file for download...
if request.args:
    filename = request.args.get('filename')         # value comes from template url link
    filepath = '/static/files/'
    return send_from_directory( filepath, filename, as_attachment=True )

我正在尝试在 Apache/WSGI mod 下生成与 Jinja2 / Flask 的链接。

也许是 mod_wsgi 下的 Apache 导致了这个问题?!

我在浏览器中看到的错误是:

Bad Request
The browser (or proxy) sent a request that this server could not understand.

根据 Chrome 的开发者工具/网络选项卡为具有混合文件名(希腊语 + 英语)的测试文件生成的链接是:

http://superhost.gr/files/download?filename=%CE%94%CE%B7%CE%BC%CE%B9%CE%BF%CF%85%CF%81%CE%B3%CE%AF%CE%B1%20Win10%20Bootable%20Flash%20Disks.txt

【问题讨论】:

  • 我看不懂,你想得到{{ filename }}的值吗?
  • 我想将该值传递给使用 unicode 编码的链接,因为它包含希腊字母。
  • 我写了代码,但我不知道为什么不起作用。检查jsfiddle.net/skv89cnz也许对你有帮助
  • 我在这里看到你传递了这个值Νικόλαοςτο 参数。在我的情况下,该值是从具有正确编码的 Bottle 框架中检索的,但不幸的是,当 &lt;meta http-equiv="REFRESH" content="5; URL=http://superhost.gr/files/download?file={{ filename }}"&gt; 形成时,它不会重定向到使用 utf-8 编码的 url。我能保证吗?
  • 您可以使用框架中的代码并更改其中的filename 或在{{ filename }} 中设置值然后运行代码

标签: python-3.x flask wsgi


【解决方案1】:

我正在尝试重现您的问题,但我认为您应该提供更多信息。

我尝试了以下设置,/redirect/ 正确返回了名为 Νικόλαος Βέργος.pdf 的文件。

app.py

from flask import render_template
from flask import Flask
from flask import request, send_from_directory
app = Flask(__name__)

@app.route('/')
def home():
    filename='Νικόλαος Βέργος.pdf'
    return render_template('home.html', filename=filename)

@app.route('/redirect/')
def redirect():
    if request.args:
        filename = request.args.get('filename')
        filepath = '/static/files/'
        return send_from_directory(filepath, filename, as_attachment=True)

templates/home.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="REFRESH" content="5; URL=http://127.0.0.1:5000/redirect/?filename={{ filename }}">
    <title>title</title>
  </head>
  <body>
  </body>
</html>

【讨论】:

  • 在您的示例中,您使用的是 Flask 的嵌入式 Web 服务器,而在我的示例中,我使用的是 Apache Web 服务器,在我的示例中返回 encoding error。您能否尝试使用 Apache,看看它是否适用于您,或者它是否返回 enocding errorbad request
  • 如果是 Apache 配置问题,请参阅 stackoverflow.com/questions/913869/… 可能会有所帮助
  • @ΝικόλαοςΒέργος:请将这些详细信息添加到您的问题中。这听起来像是 Apache / WSGI 设置问题,而不是 Flask 问题。
  • @Shine Zhang:我查看了这个链接并通过在 httpd.conf 中添加 AddDefaultCharset utf-8 进行了测试,但问题仍然存在。
  • @Martijn Pieters:我也倾向于这样认为,这可能是一个 Apache/WSGI 问题,但我不知道如何解决它。按照您的建议,我将这些详细信息添加到我原来的问题中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2021-04-12
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
相关资源
最近更新 更多