2

I am trying to list all the files and sub-directories in particular directory("/data/file/transfer").
Now I have this problem only getting this file which is in the second level sub-directory. I am using Jinja template to view the page.

Directory structure looks like :

/data/
 ----file/
 --------transfer/
 -------------first/
 ----------------second/
 -------------------get_this_file.txt


the file get_this_file.txt is in /data/file/transfer/first/second/ directory.

#! /usr/bin/env python

from flask import Flask,render_template, send_file
import os
import sys

app = Flask(__name__)

@app.route("/list_data", defaults={'req_path': ''})
@app.route('/<path:req_path>')
def incident_data(req_path):
    base_dir = "/data/file/transfer/"
    abs_path = os.path.join(base_dir, req_path)
    if os.path.isfile(abs_path):
        return send_file(abs_path)
    final_files = []
    if os.path.isdir(abs_path):
        files = os.listdir(abs_path)
        for file in files:
            temp_file = req_path + "/" + file
            print temp_file
            final_files.append(temp_file)

    return render_template('files.html', files=final_files)

if __name__ == "__main__":

    app.config.update(dict(
        DEBUG=True,
        SECRET_KEY=b'_isecret/'
    ))

    app.run(host="0.0.0.0", port=8080)


my templates/files.html is below:

<ul>
    {% for file in files %}
    <li><a href="{{ file }}">{{ file }}</a></li>
    {% endfor %}
</ul>


OUTPUT:
on chrome:
192.168.168.xxx:8080/first/second

first/second/get_this_file.txt <--- (when clicked) 192.168.168.xxx:8080/first/first/second/get_this_file.txt

Cant understand why href for get_this_file.txt is wrong.
Any help is appreciated. Struggling from a long time on this.

Susan M
  • 53
  • 1
  • 6

1 Answers1

3

You should add relative path by adding / Forward slash at the start of an href. So it resolve the domain like starting from the root of your domain.

<a href="/{{ file }}">{{ file }}</a>

And then

OUTPUT: 
on chrome: 
192.168.168.xxx:8080/first/second 

first/second/get_this_file.txt <--- (when clicked) 
192.168.168.xxx:8080/first/second/get_this_file.txt

Updated:

Try using url_for that will resolve all the href problems for you.

<li><a href="{{ url_for('incident_data', req_path=file) }}">{{ file }}</a></li>
Raja Simon
  • 10,126
  • 5
  • 43
  • 74
  • +1 for making the href problem go away... Thanks Raja Simon, I added forward slash as you mention, that did resolve the problem of href. But when I go to //192.168.168.xxx:8080/list_data, It shows me "/first" and after clicking on /first, it goes to DNS address could not found error. the link on page goes to "first/" . – Susan M Aug 01 '17 at 05:50
  • I have updated my question. let me know... – Raja Simon Aug 01 '17 at 05:57
  • Perfect!. Works for me. thanks a lot Raja Simon!!! :) – Susan M Aug 01 '17 at 06:01