5

I am implementing a really lightweight Web Project, which has just one page, showing data in a diagram. I use Django as a Webserver and d3.js as plotting routine for this diagram. As you can imagine, there are just a few simple time series which have to be responded by Django server, so I was wondering if I simply could hold this variable in ram. My first test was positive, I had something like this in my views.py:

X = np.array([123,23,1,32,123,1])

@csrf_exempt
def getGraph(request):
    global X
    return HttpResponse(json.dumps(X))

Notice, X is updated by another function every now and then, but all user access is read-only. Do I have to deal with

  1. security issues by defining a global variable?
  2. inconsistencies in general?

I found a thread discussing global variables in Django, but in that case, the difficulty is of handling multiple write-access.

To answer potential questions on why I don't want store data in database: All data I got in my X is already stored in a huge remote database and this web app just needs to display data.

Community
  • 1
  • 1
Milla Well
  • 3,193
  • 3
  • 35
  • 50

1 Answers1

2

Storing it in a variable does indeed have threading implications (and also scalibility - what if you have two Django servers running the same app?). The advice from the Django community is don't!.

This sounds like a good fit for the Django cache system though. Just cache your getGraph view with @cache_page and the job is done. No need to use memcache, the built-in in-memory memory-cache cache-backend* will work fine. Put a very high number as the time-out on the cache (years).

This way you are storing the HTTP response (JSON) not the value of X. But from your code sample, that is not a problem. If you need to re-calculate X you need to re-calculate the JSON, and if you need to re-calculate the JSON you will need to re-calculate X.

https://docs.djangoproject.com/en/dev/topics/cache/?from=olddocs/


1 or just 'built-in memory backend', I couldn't resist

Joe
  • 46,419
  • 33
  • 155
  • 245
  • As a member of the Django community, I wouldn't necessarily say "don't" - I've done a few things very similar myself. But +1 for the cache backend, it's a much better way to solve this problem. – Daniel Roseman Aug 14 '12 at 11:26
  • 1
    @Joe I tried this, and it works fine with normal http requests, but when I call it via `AJAX` it is not cached. I guess, Django considers every single `AJAX`-request to be different from the one before and computes `X` again. How to deal with that? But thanks, again for recommending Django cache system - it seems to be quite more elegant than global vars – Milla Well Aug 14 '12 at 13:16
  • 1
    don't mind! I solved it by using the `The low-level cache API`. It's just perfect. Thanks a lot – Milla Well Aug 14 '12 at 13:27