1

I am using a lib to get user location by their IPs.
main code:

...

datfile = os.path.join(os.path.dirname(__file__), "ipdb.dat")

class IPv4Database(object):
    def __init__(self, filename=None, use_mmap=True):
        print 'IPv4Database init'
        if filename is None:
            filename = datfile
        with open(filename, 'rb') as f:
            if use_mmap and mmap is not None:

        ...

I know read a file would cost a lot,so I want ipdb = IPv4Database() just call once, then use ipdb in the whole django project.
First thing I thougnt is to set ipdb as a globla variable,but the only way I know is puting ipdb = IPv4Database() to settings.Is it Ok to initiate a object in settings?

Another way ---- cache : Save the file to cache seems not good, __init__ still need to load this file. So as pickle, pickle ipdb and save to cache, then unpickle every time I need it.I afraid it is not good if the file is large.

What should I do?

Mithril
  • 12,947
  • 18
  • 102
  • 153
  • Possibly related: http://stackoverflow.com/questions/6791911/execute-code-when-django-starts-once-only – dhke Jun 11 '15 at 08:38

1 Answers1

0

Just create a variable in your module.

e.g.

in the file appname/ipdb.py

ipdb = IPv4Database()

...

Then where you need it you can do

from appname.ipdb import ipdb

... do something with ipdb

Just make sure you absolutely only need a single instance of you Ip database.

Peter Tillemans
  • 34,983
  • 11
  • 83
  • 114
  • This is is good for Django < 1.7. Django 1.7 and above have [`AppConfig`](https://docs.djangoproject.com/en/1.7/ref/applications/#django.apps.AppConfig) – dhke Jun 11 '15 at 08:41
  • 1
    True, with app config it is more flexible for the site(s) using it and you do not need to depend directly on this module when using it somewhere else. – Peter Tillemans Jun 11 '15 at 08:47