Search code examples
pythonflaskjinja2

Python displaying contents of file on browser using Flask


I am working on a Python project using Flask which has the following directory structure -

MyProject
|
+-- app
    |
    +-- init.py
    +-- views.py
    +-- downloads
        |
        +-- myFile.txt
    +-- static
        |
        +-- css
            |
            +-- style.css
        +-- img
            |
            +-- flask.jpg
        +-- js
            |
            +-- app.js
    +-- templates
        |
        +-- index.html  
+-- run.py

I would like to display the contents of downloads/myFile.txt on the web browser. How can it be done?

When I manually tried executing the url http://<ip>:<port>/static/css/style.css, the browser displays the contents of the css file (also the js file).

But when I try to execute the url http://<ip>:<port>/downloads/myFile.txt, it says Not Found.

What am i missing here?


Solution

  • You can see the style.css file correctly because it is contained in the static folder, which is managed by default by flask to return static files, like in your case a style sheet.

    In the case of the second link, Not Found is returned since that path is not managed by the routes of your application. To handle it you should do something like this:

    from flask import Flask, send_file
    from os.path import join as join_path
    from magic import Magic
    #...
    
    @app.route('/download/<file_name>')
    def download_file(file_name):
        #load abs file path from file name (in your case search for the file in your download folder) -> full_file_path
        full_file_path = join_path(<your_download_folder>, file_name)
        #get mime_type of the file -> mime_type
        mime = Magic(mime=True)
        mime_type = mime.from_file(full_file_path)
        return send_file(full_file_path, mime_type)
    

    Magic is a python library to read the mime type of a file.

    Through the send_file method of flask it is possible to directly return a file from it's path. Specifying the mimetype your browser will know how to interpret the response returned from the server and correctly display the returned file.