Keep API connected

Hi,

I am new to Django and I have a question regarding to use of an API. The API I wanto to use, connects to a Webserver and give me responses when I call some functions, like so:

api = API('name','password')
api.connect()
api.get_total_value() #This returns me a number

So, I want to connect to this API once and leave it connected, so everytime if, for example, I click a button on my view, this button click returns me api.get_total_value().

I thought about using Singleton and I use something similar to this:

class Singleton:
_instance = None
def instance(self):
if self._instance is None:
self._instance = API('name', 'password')
self.connect()
return self._instance

But I don’t know if this is the best solution, first because I don’t know if Django will leave the instance really connected, and then because when I try to access get_total_value() from the Singleton class, obviously, the method does not exists on Singleton and do not allows me access it.

Any tip how to keep the API connected when I have my page open?

It makes a huge difference depending upon this “API” object that you’re using.

The whole concept of a “connection” to a web server is somewhat nebulous and flexible.

In the traditional “tcp socket” sense, a connection isn’t maintained, except for the half-dozen exceptions where it is.

So, whether or not this is going to do you any good at all really depends upon the specifics of the service to which you are connecting and what it supports in the way of a persistent connection.

Also keep in mind that when you’re running Django in a server environment, you may have multiple instances of the server process running that wouldn’t be sharing state. Your singleton would exist as once per instance. To manage a truly global connection, you’d need to have a singular instance running in a persistent process outside the Django environment, that a Django instance could connect to locally.