Referencing file in Django views.py - python

I am building a Django web interface (overkill - I know!) for a few small python functions. One of these transforms a txt file stored in Django root. Well it aims to.
I have the following setup in a few places:
with open('file.csv','r') as source:
...
However, without setting the entire directory on my machine (e.g. /home/...), it cannot find the file. I have tried putting this in the Static directory (as ideally I would like people to be able to download the file at a later stage) but same problem.
How do you work with files within Django? What is best practice to solve the above allowing someone to download it later?

If you only need the path:
import os
from django.conf import settings
file_path = os.path.join(settings.STATIC_ROOT, 'file.txt')
with open(file_path, 'r') as source:
# do stuff
Please notice that you need to put your file in a directory like this: my_app/static/my_app/file.txt
for more information you can refer to Django docs.

Related

Django folder structure for created file, static? media? or another one?

I want to create the file(.wav) by django and let it be downloaded by user.
Currently I create the file under /myproj/static directory.
However it is mixed with the other jpg/img files, so,, it's not good design?
then, I read the document about /myproj/media directory but it is said used for user upload files.
So,,, how is the good directory design for server created file?
Should I create such as /myproj/create_wav?
but how can user access this url in template?
Thank you for any idea or helps.
According to Django's documentation,
By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. (...) However, Django provides ways to write custom file storage systems that allow you to completely customize where and how Django stores files.
So, in OP's shoes I'd simply use the media folder, since that's used not only for user uploads but also for user downloads.

Store static files on S3 but staticfiles.json manifest locally

I have a Django application running on Heroku. To store and serve my static files, I'm using django-storages with my S3 bucket, as well as the standard Django ManifestFilesMixin. I'm also using django-pipeline.
In code:
from django.contrib.staticfiles.storage import ManifestFilesMixin
from storages.backends.s3boto import S3BotoStorage
from pipeline.storage import PipelineMixin
class S3PipelineManifestStorage(PipelineMixin, ManifestFilesMixin, S3BotoStorage):
pass
The setup works, however the staticfiles.json manifest is also stored on S3. I can see two problems with that:
My app's storage instance would have to fetch staticfiles.json from S3, instead of just getting it from the local file system. This makes little sense performance-wise. The only consumer of the manifest file is the server app itself, so it might as well be stored on the local file system instead of remotely.
I'm not sure how significant this issue is since I suppose (or hope) that the server app caches the file after reading it once.
The manifest file is written during deployment by collectstatic, so if any already-running instances of the previous version of the server application read the manifest file from S3 before the deployment finishes and the new slug takes over, they could fetch the wrong static files - ones which should only be served for instances of the new slug.
Note that specifically on Heroku, it's possible for new app instances to pop up dynamically, so even if the app does cache the manifest file, it's possible its first fetch of it would be during the deployment of the new slug.
This scenario as described is specific to Heroku, but I guess there would be similar issues with other environments.
The obvious solution would be to store the manifest file on the local file system. Each slug would have its own manifest file, performance would be optimal, and there won't be any deployment races as described above.
Is it possible?
Some time ago I read this article which I believe fits your case well.
In there at the last paragraph exists the following:
Where is staticfiles.json located?
By default staticfiles.json will reside in STATIC_ROOT which is the
directory where all static files are collected in.
We host all our static assets on an S3 bucket which means staticfiles.json by default would end up being synced to S3. However, we wanted it to live in the code directory so we could package it and ship it to each app server.
As a result of this, ManifestStaticFilesStorage will look for
staticfiles.json in STATIC_ROOT in order to read the mappings. We had
to overwrite this behaviour, so we subclassed ManifestStaticFilesStorage:
from django.contrib.staticfiles.storage import
ManifestStaticFilesStorage from django.conf import settings
class KoganManifestStaticFilesStorage(ManifestStaticFilesStorage):
def read_manifest(self):
"""
Looks up staticfiles.json in Project directory
"""
manifest_location = os.path.abspath(
os.path.join(settings.PROJECT_ROOT, self.manifest_name)
)
try:
with open(manifest_location) as manifest:
return manifest.read().decode('utf-8')
except IOError:
return None
With the above change, Django static template tag will now read the
mappings from staticfiles.json that resides in project root directory.
Haven't used it myself, so let me know if it helps!
The answer of #John and Kogan is great but doesn't give the full code needed to make this work: As #Danra mentioned you need to also save the staticfiles.json in the source folder to make this work. Here's the code I've created based on the above answer:
import json
import os
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage
from whitenoise.storage import CompressedManifestStaticFilesStorage
# or if you don't use WhiteNoiseMiddlware:
# from django.contrib.staticfiles.storage import ManifestStaticFilesStorage
class LocalManifestStaticFilesStorage(CompressedManifestStaticFilesStorage):
"""
Saves and looks up staticfiles.json in Project directory
"""
manifest_location = os.path.abspath(settings.BASE_DIR) # or settings.PROJECT_ROOT depending on how you've set it up in your settings file.
manifest_storage = FileSystemStorage(location=manifest_location)
def read_manifest(self):
try:
with self.manifest_storage.open(self.manifest_name) as manifest:
return manifest.read().decode('utf-8')
except IOError:
return None
def save_manifest(self):
payload = {'paths': self.hashed_files, 'version': self.manifest_version}
if self.manifest_storage.exists(self.manifest_name):
self.manifest_storage.delete(self.manifest_name)
contents = json.dumps(payload).encode('utf-8')
self.manifest_storage._save(self.manifest_name, ContentFile(contents))
Now you can use LocalManifestStaticFilesStorage for your STATICFILES_STORAGE. When running manage.py collectstatic, your manifest will be saved to your root project folder and Django will look for it there when serving the content.
If you have a deployment with multiple virtual machines, make sure to run collectstatic only once and copy the staticfiles.json file to all the machines in your deployment as part of your code deployment. The nice thing about this is that even if some machines don't have the latest update yet, they will still be serving the correct content (corresponding to the current version of the code), so you can perform a gradual deploy where there is a mixed state.
There is Django ticket #27590 that addresses this question. The ticket has a pull request that implements a solution, but it has not been reviewed yet.

Where to run Python Code in Django once the file is uploaded?

My django application has a file uploader which uploads to a specific location in my local system.
It redirects to a new html page which shows successful message after upload is done.
Once the file is uploaded I need to do some processing of csv files.
I have a python code which does the processing.
Now my question is, where do I put the python file in the django project and how do i call it to be run once the upload is done?
Any help is appreciable
Thanks in advance
You can place it anywhere you like, it's just Python. Maybe in a csv_processing.py if it fits in a single module, or as a completely independent library if it's more. Django doesn't have an opinion on this.
The best way to run it is by doing it asynchronously using Celery.
Make sure the file is within a python package, you do this by adding init.py to the directory, documentation here. In accordance to Django convention; you would place the file within the app that needs to use it, or within another app you would name utils, documentation here.
Question:
I need the file to be run completely after the application uploads the file.
Answer:
new = Storage()
new.file = request.FILES['file']
new.save()
Now we have the database id. (When file object saved into database it emits the id).
originalObj = Storage.objects.get(pk=new.id)
Now you can import the csv file and do modification here.

Is it possible to access static files within views.py?

I am able to access the static file in question via direct url (localhost:8000/static/maps/foo.txt), so I guess I have it all working well. But I can't do the following: I want to open that text file in views.py. It's because I'm working on a simple web browser adventure game and I wanted to store maps in static/maps and load those maps using f=open('/static/maps/' + mapname + '.txt', 'r'). I get the IOError: no such file or directory. I really don't understand it, because there is such directory when I search for it in address.
Can it be done somehow?
You need to use the place they are stored on disk, which is probably in settings.STATIC_ROOT or settings.STATICFILES_DIRS, not the place they are being served by the web app.
Note however that if you are modifying these files programmatically, they aren't (by definition) static files. You'd be better off using the MEDIA_ROOT location. Also note that Django has helpers to do this sort of thing - see the documentation on Managing files.

Downloading from a dynamic list of files in Django Admin

I currently have a django app which generates PDFs and saves them to a specific directory. From the admin interface I want to have some way to view the list of files within that directory (similar to models.FilePathField()), but also be able to download them. I realize that django was never intended to actually serve files, and I have been tinkering with django-sendfile, as a possible option. It just doesn't seem like there is any way to create a dynamic list of files other than with FilePathField (which I don't believe can suite my purposes).
Would this project fit your needs? http://code.google.com/p/django-filebrowser/
I ended up realizing that I was going about the problem in a more complicated manner than was necessary. Using two separate views trivializes the issue. I was just under the impression that the admin interface would include such a basic feature.
What I did was create a download_list view to display the files in the directory, and a download_file view which uses django-sendfile to serve the file to the end-user. Download_file simply parses through the directory with listdir(), checks if the extension is valid and sends the complete file path to the download_file function (after the user selects one).
Are the files in a directory that is served by your webserver? If all you want to do is list and download the files, it may be easier just to have a link to the directory with all the files in it and let the webserver take care of listing and serving the files. I understand this may not be the ideal solution for you, but it does avoid having Django serve static files, which is a task best left to the webserver.

Categories