[Flask] A routing question

Adam Steer Adam.Steer at anu.edu.au
Thu Mar 17 20:38:12 EDT 2016

Hi all

I am working on a small application that is essentially flask-autoindex with some bells and whistles - it is meant to easily expose files for download, and allow a user to select multiple files to zip and download using checkboxes. It essentially looks like Autoindex (https://pythonhosted.org/Flask-AutoIndex/), and the reason I didn’t use autoindex is that I could not figure out how to expose the lists of files and directories to other functions in my flask app. Which I need to do in order to allow users to select a bunch of files to download at once.

Things are mostly working - but I’m stuck on routing. I want my flask app to navigate a directory tree which it builds on the fly, and then download files which are clicked on.

This routing works for navigating a directory tree:
@app.route('/', methods=['GET', 'POST'])
@app.route('/<path:path>/', methods=['GET', 'POST'])
def render_page(path=None):
     return render_template(page.html, files=files,dirs=dirs)
…where files are listed in page.html using:

 {% for f in files %}
                {{ f.0.name }}
                [<a href="{{ request.base_url + '/' + f.0.name }}">http download</a>]
              <td>{{ f.0.size|filesizeformat }}</td>
 {% endfor %}

…but if I click on the file link in my browser, flask sees the file name as a directory name. Links to directories have the same structure, loop through a list and show links with the format:

  <a href="{{ request.base_url[:-1] + '/' + d.name }}">{{ d.name }}</a>

Adding another endpoint:

def getthefile(filename):
    return send_from_directory(app.config['ROOT'], filename,as_attachment=True)

…lets me download files at the root level of my directory tree, changing the file link to  <a href=“{{ url_for(‘getthefile’, f.0.name) }}” >http download</a> in my template.

…but gives a 404 if I try to navigate to a directory. 

SO, I am clearly confusing how Flask routes to things. I want to treat directories one way, and files another, but using the same route.

The endpoint of the app has the app living in /var/www/…, but the file tree that flask is displaying starting at some arbitrary point (right now /home/user/data/). So I guess I’m trying to serve static files from a dynamically built tree.

…and I’m pretty much blundering my way through flask and trying things out. This is the first real hangup so far! 

Any advice you can offer will be greatly appreciated. I’m sure it’s something very simple that I’m just not getting.



More information about the Flask mailing list