将 img 路径从客户端传递到服务器烧瓶

时间:2021-04-15 08:51:42

标签: python html flask

我是 Web 开发的新手,尤其是 Flask 和 Python。我正在尝试创建一个站点,您可以在其中浏览图像,一旦您单击一个,该图像将显示在另一个名为 image.html 的页面上。我的问题是我不知道如何传递 img src,然后在服务器端获取它,并将其传递回渲染模板。

(图片存放在/static文件夹下) 应用程序.py:

from flask import Flask, render_template, request, Response, redirect
import os


app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/image/<id>', methods=['GET', 'POST'])
def image(id):

    #fetch image based on id?
    return render_template('image.html', id=id)

if __name__=='__main__':
    app.run(debug=True)

index.html:

{% extends 'base.html' %}


{% block content %}

<a href="/image/123">
    <img src="static/123.jpg" id="123" alt="" width="400" height="400">
</a>


{% endblock %}

image.html:

{% extends 'base.html' %}


{% block content %}

<img src="{{ url_for('static',filename='{{ id }}') }}" id="123" alt="" width="400" height="400">

{% endblock %}

2 个答案:

答案 0 :(得分:1)

仅使用 Flask 就很有可能实现您的既定目标,而且您已经走上了通往解决方案的可能道路。

以下路由基于您的代码。此外,静态目录中的所有文件都列在 index 中并传输到模板中。

from flask import Flask, render_template
import os

app = Flask(__name__)

@app.route('/')
def index():
    # Alternatively use app.static_folder here!
    files = os.listdir(os.path.join(app.root_path, 'static'))
    return render_template('index.html', files=files)

@app.route('/image/<path:id>')
def image(id):
    return render_template('image.html', id=id)

在模板本身中,您可以遍历文件名列表并使用 url_for 来引用第二个路由并将文件名作为路由的变量以及文件本身传输在 img 元素中。另见"Variable Rules""Static Files"
在锚点内,可以简单地输入相同的信息来引用图片。但是,如果您想将图像嵌入到另一个页面中,我建议您将完整的文件名作为路径传递。

{% extends 'base.html' %}
{% block content %}
  {% for file in files %}
    <a href="{{ url_for('image', id=file) }}">
      <img src="{{ url_for('static', filename=file) }}" alt="{{ file }}" width="400" height="400" />
    </a>
  {% endfor %}
{% endblock %}

由于您已经位于 url_for 规范的代码块的表达式中,因此您不需要任何其他大括号,只需将传递给模板的变量作为文件名传递即可。

{% extends 'base.html' %}
{% block content %}
<img src="{{ url_for('static', filename=id) }}" width="400" height="400">
{% endblock %}

我建议您将所有图像放在一个子文件夹中,以便更容易将它们与其他文件分开。程序保持不变,只是路径细节不同。

因为我认为您也有兴趣将新图像上传到服务器,所以我推荐 thisthis 教程。在最后提到的页面上,您会找到我认为是框架的excellent introduction 以及有关与flask 相关的各种主题的有用文章。

答案 1 :(得分:0)

如果我理解您的问题,您可以解决在索引模板中放置一个指向图像功能的简单链接...

<a href="{{url_for('.image', id=123)}}">
    <img src="static/123.jpg" id="123" alt="" width="400" height="400">
</a>