1

I'm making an upload/download service just for fun but am struggling to serve files that are outside of static directory, which causes an issue because anyone could visit www.mysite.com/static and view the contents.

This is what I have so far. Forgive the ugly paths of my network storage :)

if not os.path.exists('\\ATTILA\\Development\\GIT\\MyCloud\\static\\'+ session['username']):
        os.makedirs('\\\\ATTILA\\Development\\GIT\\MyCloud\\static\\'+ session['username'])

    #Download links for all files
    pathing = []
    my_path = '\\\\ATTILA\\Development\\GIT\\MyCloud\\static\\'+ session['username'] + '\\'
    os.chdir('\\\\ATTILA\\Development\\GIT\\MyCloud\\static\\'+ session['username'])
    for myfile in glob.glob('*'):
        downs = my_path + myfile
        pathing.append(tuple([downs, myfile]))

In my template I have a simple for loop

{% for myfile, name in pathing %}
    <a href='{{ myfile }}' download>{{ name }}</a><br>
{% endfor %}

So my view looks like this:

enter image description here

As it stands my files are downloadable, however if I change the file paths for the downloads to a folder outside of 'static' then instead of download links I get 404 errors that point to the URL + the file path like so www.mysite.com\ATTILLA\Development\some_other_folder any suggestions?

BrettJ
  • 1,176
  • 2
  • 17
  • 33
  • 1
    I asked and asked this question so many times. BrettJ if you didn't figure it out, check out my GitHub example I did https://github.com/arilaverty/Get-Files-Outside-of-Flask-Static-Folder – Ari Jun 30 '19 at 07:22
  • Thank you actually! It seems on every project I end up doing this a different way... – BrettJ Jul 05 '19 at 09:22

1 Answers1

2

If you want place your app in production you need use solutions like a nginx for serving you static files. Usually in development stage Flask work with regulary static files (css, js and another) self. It's normal. If you want hide some private data or uploaded files you need use something like this:

from flask import Flask, make_response
...
@app.route('/file_downloads/<filename>')
def file_downloads(filename):
    headers = {"Content-Disposition": "attachment; filename=%s" % filename}
    with open('../tmp/you_private_file.zip', 'r') as f:
        body = f.read()
    return  make_response((body, headers))
erroia
  • 378
  • 3
  • 10