Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django vars in ram

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.

like image 274
Milla Well Avatar asked Nov 04 '22 18:11

Milla Well


1 Answers

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

like image 139
Joe Avatar answered Nov 12 '22 10:11

Joe