I need to return css files and js files according to specific logic. Clearly, static serve does not perform what I need. I have a view, whose render method uses logic to find the proper file, but then I have to return it. Technically, I can just read the file and stuff it into a HttpResponse object with the proper mime type, but I was wondering if there was a better strategy. (like fpassthru() in php)
collectstatic. Collects the static files into STATIC_ROOT . Duplicate file names are by default resolved in a similar way to how template resolution works: the file that is first found in one of the specified locations will be used. If you're confused, the findstatic command can help show you which files are found.
"STATIC_ROOT" sets the absolute path to the folder where static files used for the apps and admin in a django project are stored and this command below creates the folder and collects static files from the apps and admin in a django project into the folder (*Setting "STATIC_ROOT" never ever influence to static file URL ...
Static files are files that don't change when your application is running. These files do a lot to improve your application, but they aren't dynamically generated by your Python web server. In a typical web application, your most common static files will be the following types: Cascading Style Sheets, CSS.
This is what I used:
test_file = open('/home/poop/serve/test.pdf', 'rb') response = HttpResponse(content=test_file) response['Content-Type'] = 'application/pdf' response['Content-Disposition'] = 'attachment; filename="%s.pdf"' \ % 'whatever' return response
What webserver software are you using?
At least for Apache and NginX, there is a module enabling you to use the X-SendFile
HTTP header. The NginX website says Lighty can do this, too.
In your wrapper view:
... abspath = '/most_secret_directory_on_the_whole_filesystem/protected_filename.css' response = HttpResponse() response['X-Sendfile'] = abspath response['Content-Type'] = 'mimetype/submimetype' # or let your webserver auto-inject such a header field # after auto-recognition of mimetype based on filename extension response['Content-Length'] = <filesize> # can probably be left out if you don't want to hassle with getting it off disk. # oh, and: # if the file is stored via a models.FileField, you just need myfilefield.size response['Content-Disposition'] = 'attachment; filename=%s.css' \ % 'whatever_public_filename_you_need_it_to_be' return response
Then you can connect the view via http://mysite.com/url_path/to/serve_hidden_css_file/
.
You can use it anytime you need to do something upon a file being requested that should not be directly accessible to users, like limiting who can access it, or counting requests to it for stats, or whatever.
For Apache: http://tn123.ath.cx/mod_xsendfile/
For NginX: http://wiki.nginx.org/NginxXSendfile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With