Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask : How to serve static files from template directory?

I am developing a SAAS application using Flask and I want users to be able to create/upload/use their own custom templates. This is how my directory structure is right now :

/flaskapp
    /application.py
    /static
        /style.css
    /templates (site & admin templates goes here)
        /hello.html
    /userdata
        /user1
            /template1
                 hello.html
            /template2
                 hello.html
        /user2
            /template1
                 hello.html
            /template2
                 hello.html

I am able to serve user specified templates using a solution found through this stackoverflow question : How to dynamically select template directory to be used in flask? but how do I serve static files from template directory. Instead of serving static files from /flaskapp/static/ I want to serve static files using /flaskapp/userdata/<user>/<current-template>/static/ directory where and will be determined dynamically at run time. How to do this?

like image 557
anujkk Avatar asked Nov 12 '22 14:11

anujkk


1 Answers

Presumably you're using a web server in front of Flask. One way to solve this (which I generally use when using Apache + mod_wsgi for custom WSGI apps) is to just serve the directory straight from disk via the web server. On Apache, I just use an Alias directive for this.

If you want to vary the file served under a given URL per user, you would have to pipe the file through Flask. You'd have to figure out how to properly route the request; after that, you might be able to use wsgi.file_wrapper to send the correct file (though I'm not sure how you'd get at this through Flask).

like image 78
djc Avatar answered Nov 15 '22 04:11

djc