如何在html页面中添加flask自动索引

Joh*_*Doe 6 python flask flask-autoindex

我想在包含更多内容的 HTML 页面中插入 AutoIndex...类似这样

<html>
<body>
//HTML Content here like IMG, DIV, Table
// Autoindex here
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我正在使用这样的自动索引,但它覆盖了整个页面

import os.path
from flask import Flask
from flask_autoindex import AutoIndex


app = Flask(__name__)

return AutoIndex(app, browse_root='templates/computer1')

if __name__ == '__main__':
    app.run()
Run Code Online (Sandbox Code Playgroud)

Luc*_*len 2

我通过执行以下操作来解决此问题:

创建您的定制.html模板

# mytemplate.html
{% extends '__autoindex__/autoindex.html' %}

{% block meta %}
  {{ super() }}
  <link rel="stylesheet"
    href="{{ url_for('static', filename='main.css') }}" />
    <!-- Here you can specify your own .css -->
{% endblock %}

{% block header %}
  <div style="width: 500px; margin: 30px auto;">
    <h2>My Application</h2>
{% endblock %}

{% block footer %}
  </div>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

(这是文档中显示的模板,您可以自定义它)

在 python 中,为了在该模板上运行 AutoIndex:

# faicustom.py
from flask import Flask
from flask_autoindex import AutoIndex
app = Flask(__name__)

spath = "/" # Update your own starting directory here, or leave "/" for parent directory

files_index = AutoIndex(app, browse_root=spath, add_url_rules=False)

@app.route('/files')
@app.route('/files/<path:path>')
def autoindex(path='.'):
    return files_index.render_autoindex(path, template='mytemplate.html')
    # Here is where you specify your template

# And if you want:
if __name__ == '__main__':
    app.run()
Run Code Online (Sandbox Code Playgroud)

然后启动 Flask 应用程序,并且应该能够在您自己的自定义站点上运行 AutoIndex(在本例中为/files

有关该render_autoindex功能的更多信息,请查看注释的源代码