使用Python,Flask&提供和打开目录神社

时间:2017-02-06 07:46:49

标签: python html flask directory jinja2

我搜索过但找不到答案。

我是python的新手,确切地说是1周,并且我正在使用带有Flask的python来提供包含文件和文件夹的Web目录。

我可以下载文件,但在尝试打开目录时会获得404。你能帮忙吗?

views.py:

  while ((n = read(fd, buf, sizeof(buf))) > 0) {
    write (ptrDump, buf, n);
                         ^
                        note

模板/ index.html中:

from flask import Flask, render_template, send_from_directory, send_file
#from app import app
import os
from pprint import pprint
import magic
import urllib
import sys

reload(sys)
sys.setdefaultencoding('utf8')

app = Flask(__name__)
mime = magic.Magic(mime=True)

"""
Config
"""
# To list the current directory
#base_directory = os.path.dirname(os.path.abspath(__file__))
base_directory = "/var/www/html/test"
# directories not to be listed
ignored_dirs = ["venv"]
ignore_dotfiles = True  
ignore_dollarfiles = True
omit_folders = False
omit_files = False

""" The base route with the file list """
@app.route("/")
def home():
    files = []
    dirs = []

    meta = {
        "current_directory": base_directory
    }

    for (dirpath, dirnames, filenames) in os.walk(base_directory):
            for name in filenames:
            if omit_files == True:
                break

            for ign in ignored_dirs:
                if ign in dirnames:
                    dirnames.remove(ign)

            nm = os.path.join(dirpath, name).replace(base_directory, "").strip("/").split("/")
            fullpath = os.path.join(dirpath, name)

            if os.path.isfile(fullpath) == False:
                continue

            size = os.stat(fullpath).st_size

            if len(nm) == 1:
                name_s = name.split(".")
                if ignore_dotfiles == True:
                    if name_s[0] == "" or name_s[0] == None:
                        continue

                files.append({
                    "name": name,
                    "size": str(size) + " B",
#                       "mime": mime.from_file(fullpath),
                    "fullname": urllib.quote_plus(fullpath)
                })

        for dirname in dirnames:
            if omit_folders == True:
                break

            fullpath = os.path.join(dirpath, dirname)

            if ignore_dotfiles == True:
                name_split = dirname.split(".")
                if name_split[0] == "" or name_split[0] == None:
                    continue

            if ignore_dollarfiles == True:
                name_split = dirname.split("$")
                if name_split[0] == "" or name_split[0] == None:
                    continue

            dirs.append({
                "name": dirname,
                "size": "/",
#                   "mime": mime.from_file(fullpath)
            })

    return render_template("index.html", files=sorted(files, key=lambda k: k["name"].lower()), folders=dirs, meta=meta)

@app.route("/download/<filename>")
def download(filename):
    filename = urllib.unquote(filename)
    if os.path.isfile(filename):
        if os.path.dirname(filename) == base_directory.rstrip("/"):
            return send_file(filename, as_attachment=True)
            else:
            return render_template("no_permission.html")
    else:
            return render_template("not_found.html")
    return None

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

1 个答案:

答案 0 :(得分:0)

而不是:

<a href="download/{{ file.fullname|urlencode }}" class="label label-success">

尝试做:

<a href="{{url_for('download', filename=file.fullname|urlencode)}}" class="label label-success">

See this for a practical.