34π
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
11π
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
- [Django]-Define css class in django Forms
- [Django]-CSRF verification failed. Request aborted. on django
- [Django]-How do I get the current date and current time only respectively in Django?
6π
Why donβt you use Django staticfiles inside your view
from django.contrib.staticfiles.views import serve
...
def view_function(request):
return serve(request, 'absolute_path_to_file_name')
- [Django]-POST jQuery array to Django
- [Django]-Get router url name when testing in Django Rest Framework
- [Django]-Django: show/log ORM sql calls from python shell
2π
Why not return an HttpResponseRedirect
to the location of the correct static file?
- [Django]-Returning pure Django form errors in JSON
- [Django]-Django : get_or_create Raises duplicate entry with together_unique
- [Django]-How to obtain and/or save the queryset criteria to the DB?
2π
Serving files directly from a view is very slow. If you are looking for normal file serving see this question: Having Django serve downloadable files
To very easily serve files through a view (for debug purposes, for example) keep reading.
# In your urls.py:
url(r'^test-files/(?P<name>.+)/$', views.test_files, name='test_files'),
# In your views.py:
from django.http.response import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt # (Allows file download with POST requests, can be omitted)
def test_files(request, name):
if name == "myxml":
fsock = open("/djangopath/data/static/files/my.xml", "rb")
return HttpResponse(fsock)
This allows you to download the file from: http://127.0.0.1:8080/app/test-files/myxml/
- [Django]-Django: Query using contains each value in a list
- [Django]-Django logging to console
- [Django]-ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory:
1π
Pass an iterator (such as the result of open()
) to the HttpResponse
constructor.
- [Django]-How to completely uninstall a Django app?
- [Django]-How to concatenate strings in django templates?
- [Django]-How would you create a 'manual' django migration?
1π
you can use below code in your view:
Note:in this function I return images but you can return every thing based your need and set your context_type
from django.http import HttpResponse,Http404
import os
def img_finder(request, img_name):
try:
with open(os.path.dirname(os.path.abspath(__file__)) + '/static/img/' + img_name, 'rb') as f:
return HttpResponse(f.read(), content_type="image/jpeg")
except IOError:
raise Http404
- [Django]-Combining Django F, Value and a dict to annotate a queryset
- [Django]-How to implement followers/following in Django
- [Django]-Received "ValueError: Found wrong number (0) of constraints for β¦" during Django migration
0π
Here the most simple and efficient way to do this.
app/urls.py
from django.urls import re_path
from app import views
urlpatterns = [
re_path(r'^(?P<public_url>.*)$', views.public, name="public"),
]
Warning : put the URL pattern at the end
app/views.py
import os
from django.conf import settings
from django.views.static import serve
def public(request, public_url):
public_folder = os.path.join(str(settings.BASE_DIR), 'folder_path')
return serve(request, public_url, document_root=public_folder)
- [Django]-Django staticfiles not found on Heroku (with whitenoise)
- [Django]-Set language within a django view
- [Django]-Django-debug-toolbar not showing up
-2π
It should be wasteful to use django to serve static content (not to mention, several orders of magnitude slower).
Iβd rather convert the view into a context processor and use the variables in templates to find what blocks to include.
- [Django]-Django : get_or_create Raises duplicate entry with together_unique
- [Django]-How to escape {{ or }} in django template?
- [Django]-How to TRUNCATE TABLE using Django's ORM?