我有几个文件:1.html
,2.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
为每个文件设置烧瓶,以便显示相应的图像。
您必须创建静态文件夹,然后必须将所有文件夹与图像一起添加。您可以遵循以下目录结构:
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。
感谢您的努力,但我在同一目录下有文件和静态文件。喜欢的东西:
ls docs
:1.html, 1-directory/1.jpg, 2.html, 2-directory/2.jpg
我可以创建符号链接到目录有static
目录,但它是乏味!请检查
EDIT
零件,我已经检查了代码,它对我来说很好用。让我知道这是否适合您。我可以
<img src="/templates/filename" />
代替使用<img src="{{ url_for('serve_file', filename=file_name) }}" />
吗?