Reputation: 49
I'm exposing web service using python ladon package and SOAP. I'm want to remember state between two method calls. Here is example code:
from ladon.ladonizer import ladonize
import logging
class Sum(object):
sum = 0
FORMAT = '%(name)s %(asctime)s %(levelname)s %(message)s'
logging.basicConfig(filename='/path/to/my/dir/Sum.log', level=logging.DEBUG, format=FORMAT)
logger = logging.getLogger('Sum')
logger.debug("Starting")
@ladonize(int,rtype=int)
def Add(self, num):
Sum.logger.debug("Adding " + str(num))
Sum.sum += num
Sum.logger.debug("sum is now " + str(Sum.sum))
return Sum.sum
Idea is to call method Add with integer parameter which should be added to class sum variable. Since sum is class variable (as oppose to instance variable), the state should be preserved as long as the code is not reloaded by the server or application. Here are log results:
Sum 2013-07-09 15:12:34,303 DEBUG Starting
Sum 2013-07-09 15:12:34,311 DEBUG Adding 5
Sum 2013-07-09 15:12:34,311 DEBUG sum is now 5
Sum 2013-07-09 15:12:36,169 DEBUG Adding 5
Sum 2013-07-09 15:12:36,169 DEBUG sum is now 10
Sum 2013-07-09 15:12:39,404 DEBUG Adding 5
Sum 2013-07-09 15:12:39,405 DEBUG sum is now 15
Sum 2013-07-09 15:12:46,734 DEBUG Starting
Sum 2013-07-09 15:12:46,742 DEBUG Adding 5
Sum 2013-07-09 15:12:46,743 DEBUG sum is now 5
As it can be seen in the logs it works for three consecutive calls of Add method, but at 15:12:46 application recreates class Sum object and sum is reseted to 0. Questions are: is class reloaded by application or wsgi? How to prevent class to be reloaded by the application (or server)? Is there any way to remember state in var between two method calls with ladon framework? I would like to avoid using database.
Upvotes: 1
Views: 221
Reputation: 717
Your Sum object is not persistent, and the sum variable (and all the others) resets to their initial value. You could make persistent the sum value in the filesystem using pikle, something like:
import pickle
@ladonize(int,rtype=int)
def Add(self, num):
Sum.logger.debug("Adding " + str(num))
try:
Sum.sum = pickle.load( open( "sum.p", "rb" ) )
except:
pass
Sum.sum += num
Sum.logger.debug("sum is now " + str(Sum.sum))
pickle.dump( Sum.sum, open( "sum.p", "wb" ) )
return Sum.sum
Upvotes: 1
Reputation: 64
You could save the sum value in a file, but then every request would be incrementing the same base value. The other way is using a Session like beaker. Every requester sends a session_id and the number to add. Your webservice returns session_id and the corresponding sum.
Have a nice day. Gabriel
Upvotes: 0