0

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()
   ....
4
  • are you requesting data with json header? Commented Apr 6, 2016 at 11:23
  • jithin, no. I create api(which is wrapper) object and run methods in it. Commented Apr 6, 2016 at 11:25
  • 1
    The session has nothing to do with global objects and is not an appropriate place to do this. Can you explain a bit more about the object? Is it per-user? Commented Apr 6, 2016 at 11:28
  • @daniel-roseman, yes, one user has only one api_auth_instance Commented Apr 6, 2016 at 11:39

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.