3

I have an application and a database. The application initially was written in python without django. What seems to be the problem is that it makes too many connections with the database and that slows it down. What I want to do is load whatever data is going to be used in python dictionary and then share that object with everybody(something like singletone object). What django seems to do is create a new instance of application each time a new request is made. How can I make it share the same loaded data?

khajvah
  • 4,889
  • 9
  • 41
  • 63

3 Answers3

1

You can use any fast key-value storages such as memcached or LevelDB to share objects between application instances. You can use JSON to serialize and deserialize these objects.

Pavel Reznikov
  • 2,968
  • 1
  • 18
  • 17
1

Contrary to your assertion, Django does not reinitialize on every request. Actually, Django processes last for many requests, and anything defined at module level will be shared across all requests handled by that process. This can often be a cause of thread safety bugs, but in your case is exactly what you want.

Of course a web site normally runs several processes concurrently, and it is impossible to share objects between them. Also, it is up to your server to determine how many processes to spawn and when to recycle them. But one object instantiation per process is better than one per request for your use case.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

You no need any magic to do singleton-like object in python. Just write module, for example shared.py inside your django project. Put your dictionary initialization here and import it from anywhere.

Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
  • I tried it but it is importing for every django request, so it is creating the object every time. – khajvah Feb 03 '15 at 08:05
  • Maybe you done something wrong? You need define variable in module which hold your object instance and import this variable from another parts of your application. – Eugene Soldatov Feb 03 '15 at 08:19
  • Pay attention on this question http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python – Eugene Soldatov Feb 03 '15 at 08:20
  • I see, I had some problems with importing, which most probably was the problem, it now works. – khajvah Feb 03 '15 at 08:35