How can I persist a single value in Django?

In spite of the fact databases regularly store many rows in any given table, having a table with only one row is not especially costly, so long as you don't have (m)any indexes, which would waste space. In fact most databases create many single row tables to implement some features, like monotonic sequences used for generating primary keys. I encourage you to create a regular model for this.


One solution I've used in the past is to use Django's cache feature. You set a value to True with an expiration time of one day (in your case.) If the value is not set, you fetch the feed, otherwise you don't do anything.

You can see my solution here: Importing your Flickr photos with Django


  1. RAM is volatile, thus not persistent: memcached is not what you asked for.
  2. XML it is not the right technology to store a single value.
  3. RDMS is not the right technology to store a single value.
  4. Django cache framework will answer your question if CACHE_BACKEND is set to anything else than file://...

The filesystem is the right technology to "persist a single value".

In settings.py:

 RSS_FETCH_DATETIME_PATH=os.path.join(
     os.path.abspath(os.path.dirname(__file__)),
     'rss_fetch_datetime'
 )

In your rss fetch script:

 from django.conf import settings
 handler = open(RSS_FETCH_DATETIME_PATH, 'w+')
 handler.write(int(time.time()))
 handler.close()

Wherever you need to read it:

 from django.conf import settings
 handler = open(RSS_FETCH_DATETIME_PATH, 'r+')
 timestamp = int(handler.read())
 handler.close()

But cron is the right tool if you want to "run a command every day", for example at 5AM:

 0 5 * * * /path/to/manage.py runscript /path/to/retreive/script

Of course, you can still write the last update timestamp in a file at the end of the retreive script, and use it somewhere else, if that makes sense to you.

Concluding by quoting Ken Thompson:

One of my most productive days was throwing away 1000 lines of code.

Tags:

Django