0

If you wanted to make a very simple file browser, let's say /some/folder on server, and let the flask app run and handle any requests for /here/ to be /some/folder/here and then dig deeper? Because flask has that @app.route(('/') so each request is mapped to a function, but here you would like one function, say browse to handle all requests, and block requests for /../../, for example.

Is flask not well suited for this? Should I look for something else?

ЯegDwight
  • 24,821
  • 10
  • 45
  • 52
rapadura
  • 5,242
  • 7
  • 39
  • 57

1 Answers1

3

This is quite doable. See http://flask.pocoo.org/snippets/57/ for an example.

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return 'You want path: %s' % path

You should handle everything after the / as a path into your folder. You can then simply open that file name using open and write it as the Flask response.

E.g.

 my_path = os.path.join(my_folder, path)
 with open(my_path) as the_file:
     # do stuff

You might need to massage the path so that it is platform independent, using os.path.separator and os.path.join etc.

Also, you will need determine the mimetype for the file you are returning and . This can be done using the module mimetypes.

Also, see this link for the mechanics of returning a file directly, without having to read and return it. In python using Flask, how can I write out an object for download?

Community
  • 1
  • 1
Hans Then
  • 10,935
  • 3
  • 32
  • 51
  • I didnt pose my question well enough I guess. I can do that opening path, list dirs and open those and so on. But how do you make one function to handle it all? because flask has @app.route('/this/path'): to some function, but I need a route for all possible folders and files in one function. is there a default route -> function map? And how do I avoid passing in a request like /smoe/path/../../../../etc/passwd for example – rapadura Sep 17 '12 at 10:42
  • I have added an extra code snippet to clarify that part. – Hans Then Sep 17 '12 at 11:32
  • To check whether your users try to get files outside of the allowed directory, you could normalize the path first and then see if the resulting path is still below your allowed directory. – Hans Then Sep 17 '12 at 11:34