我有几个文件: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
。
我不知道可以在“烧瓶中”完成此操作的任何方式。我可以想到两种方法,无论如何您都想手动执行此操作(验证,授权,安全性)。
但是要回答这个问题,有多种方法可以解决,这取决于您希望解决方案如何“神奇”。 (我假设如果您想让烧瓶来处理它,那么您就需要魔术)]
一个解决方案是装饰器,将加载的代码片段作为新参数注入到视图函数中。
import functools
def inject_snippet(func):
@functools.wraps(func)
def wrapper(i, *args, **kwargs):
filepath = f"{i}-directory/{i}.html"
with open(filepath) as f:
snippet = f.read()
return func(snippet, *args, **kwargs)
return wrapper
@app.route('/docs/show/<int:i>')
@inject_snippet
def show(snippet):
return render_template('show.html', content=snippet)