温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python 3.x - Define static file directory per route (URL) in flask
flask python-3.x static-files

python 3.x - 在烧瓶中按路由(URL)定义静态文件目录

发布于 2020-03-27 16:15:00

我有几个文件:1.html2.html等具有以下内容的文件:

1.html有

<h1>Hello</h1>
<img src="1-directory/image.jpg" />

2.html有

<h1>Hello</h1>
<img src="2-directory/image.jpg" />

等等

因此,每个文件中都有一个图像<i>-directory/i变化:1、2、3,...)。如何将每个文件的图像加载到flask中。

我的路线是:

@app.route('/docs/show/<int:i>')
def show(i):
    with open(i + '.html', 'r') as f:
        content = f.read()
        return render_template('show.html', content = content)

我的模板show.html

{content | safe}

因此,我想<i>-directory为每个文件设置烧瓶,以便显示相应的图像。

查看更多

查看更多

提问者
somenxavier
被浏览
94
Jaldhi Mehta 2020-01-31 21:32

您必须创建静态文件夹,然后必须将所有文件夹与图像一起添加。您可以遵循以下目录结构:

PROJECT NAME
>> static
  >> 1-directory
      >> 1.jpg
  >> 2-directory
      >> 2.jpg
  >> 3-directory
      >> 3.jpg
  >> 4-directory
      >> 4.jpg
>> templates
  >> 1.html
  >> 2.html
  >> 3.html
  >> 4.html
  >> show.html
>> venv folder
>> app.py

您可以将以下代码用于app.py

import flask

app = flask.Flask(__name__)

@app.route('/docs/show/<string:i>', methods=['GET'])
def show(i):
    with open('templates/' + str(i) + '.html', 'r') as f:
        content = f.read()
    return flask.render_template('show.html', content = content)

if __name__=='__main__':
    app.run('0.0.0.0',port=<your_port_name>)

您可以将1.html保留如下:

<h1>Hello</h1>
<img src="/static/1-directory/1.jpg" />

您可以将2.html保留如下:

<h1>Hello</h1>
<img src="/static/2-directory/2.jpg" />

您可以将3.html保留如下:

<h1>Hello</h1>
<img src="/static/3-directory/3.jpg" />

您可以将4.html保留如下:

<h1>Hello</h1>
<img src="/static/4-directory/4.jpg" />

而且,您可以在show.html中显示您的代码显示方式相同):

<html>
<body>{{content | safe}}</body>
</html>

编辑(根据您的评论):

根据您的评论,我以以下方式创建了文件结构:

PROJECT NAME
>> templates
  >> 1-directory
      >> 1.jpg
  >> 2-directory
      >> 2.jpg
  >> 3-directory
      >> 3.jpg
  >> 4-directory
      >> 4.jpg
  >> 1.html
  >> 2.html
  >> 3.html
  >> 4.html
  >> show.html
>> venv folder
>> app.py

您可以像这样app.py编写代码

@app.route('/docs/show/<string:i>', methods=['GET'])
def show(i):
    internal_html = flask.render_template(str(i)+'.html', file_name = str(i)+'-directory/'+str(i)+'.jpg')
    return flask.render_template('show.html', content = internal_html)

@app.route('/serve_file/<path:filename>')
def serve_file(filename):
    return flask.send_from_directory('templates/', filename)

您所有的HTML文件将如下所示:

<h1>Hello</h1>
<img src="{{ url_for('serve_file', filename=file_name) }}" />

另外,您的show.html将与上面的代码相同。在这里,我们使用此send_from_directory,因为烧瓶除了/ static文件夹以外,不提供其他服务。因此,对于外部使用该文件夹,我们必须使用send_from_directory