[Python] python flask browsing through directory with files

Discussão em 'Python' iniciado por Stack, Fevereiro 3, 2025.

  1. Stack

    Stack Membro Participativo

    Is it possible to use flask to browse through a directory with files?

    My code never seems to work correctly as weird appending between strings happens.

    Also I don`t know how to implement a kind of check whether the path is a file or a folder.

    Here is my Flask app.route:

    @app.route('/files', defaults={'folder': None,'sub_folder': None}, methods=['GET'])
    @app.route('/files/<folder>', defaults={'sub_folder': None}, methods=['GET'])
    @app.route('/files/<folder>/<sub_folder>', methods=['GET'])

    def files(folder,sub_folder):
    basedir = 'files/'
    directory = ''

    if folder != None:
    directory = directory + '/' + folder

    if sub_folder != None:
    directory = directory + '/' + sub_folder

    files = os.listdir(basedir + directory)

    return render_template('files.html',files=files,directory=basedir + directory,currdir=directory)


    and here is my html template, if anyone could give me some pointers it would be greatly appreciated!

    <body>
    <h2>Files {{ currdir }}</h2> </br>
    {% for name in files: %}
    <A HREF="{{ directory }}{{ name }}">{{ name }}</A> </br></br>
    {% endfor %}
    </body>s.html',files=files,directory=basedir + directory,currdir=directory)

    Continue reading...

Compartilhe esta Página