简体   繁体   中英

global variable in django (singleton)

I have django app. App - client for site with authorization App contains some methods which run periodically, but all methods created auth objects, for example: method runs 10 times, with 10 re-autorization. I tried session to store that object but get error:

def get_api_instance(request):
    if 'api' not in request.session: 
        api = auth()
        request.session['api'] = api
    return request.session['api']


<****api.api.Api object at 0x7fe30d155550> is not JSON serializable

Can you recommend something?

UPD: in simple python script i can create global variable:

api_var = None

def get_api():
   if not api_var:
      api_var = auth()
   return api_var

def periodic():
   api = get_api_var()
   ....

You can add a function to the User object to get the Auth class instance, you can also use propery caching to only create it once:

from django.contrib.auth.models import User

def user_get_auth(self):
    # Initialze the Auth class here

    return Auth()


User.add_to_class("get_auth", property(user_get_auth))

in the views.py or templates you can get the Auth class by:

request.user.get_auth.some_method()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM