Pergunta

I want to define a constant variable in my settings.py file, that will be available in the entire app.
i.e. if I do in my settings.py, for example:
VAR = [1,2,3]

then in my view I can access it like:
var = settings.VAR

But, I want that VAR will be fetched from a database.
means, when my app starts, SQL is performed and loads the answer to VAR.

So I've attempted to create a function in views.py that does that:

in views.py:

def loadVAR():  
... # perform sql 
return VAR

and in settings.py:

import myapp.views  
VAR = myapp.views.loadVAR() 

But it does not work and I get an "500 Internal server error" I also haven't managed to perform the SQL directly in settings as well.

How can I achieve this ?

Foi útil?

Solução

You can achieve this using middleware before touching the view,

class ModelMiddleware(object):
    """
        Model data
    """
    def process_request(self, request):

        # Fetch your data
        # Append var data to request
        request.META['VAR'] = [1, 2, 3]
        return None

You can get the VAR in view using request,

def veiw_data(request, ):
    print request.META['VAR']

Here is How to set django middleware in settings file

Update:

If you want to call the sql only first time project loads use this way,

I imagined my project structure this way,

mysite/
   mysite/
     __init__.py --> Add the logic in this file,
     urls.py
     settings.py
     test.py
   manage.py

__init__.py

from catalog.models import Product
import settings

settings.VAR = Product.objects.all()

Done. You can access the VAR in your project. Hope this may be helpful

Outras dicas

settings.py is not meant to be used that way, if you want to store some settings in a database, consider using some external package which was designed for that, here is the list of some of them.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top