It's very common that an application needs to follow a user's activity, whether to provide a better experience or to check for any unusual activity. The usual mechanism is to use a session identifier that is carried during the conversation between the user and your application. By default, the session ID is passed in a cookie, so the client's browser must have cookies enabled for the application.
We will write a simple application where '<application-name>/' opens the main page which contains the forms for the two methods square and power. We will store the values provided to these functions and use '<application-name>/display' to display the last session.
Save the below code in a file named 'track_act.py'.
import cherrypy
class application:
def index(self):
return """<html>
<head></head>
<body>
<p>Call square function:<br>
<form method="get" action="square">
<input type="text" name="num" placeholder="num"/>
<button type="submit">Submit</button>
</form>
</p>
<p>Call power function:<br>
<form method="get" action="power">
<input type="text" name="num" placeholder="num"/>
<input type="text" name="pow" placeholder="pow"/>
<button type="submit">Submit</button>
</form>
</p>
</body>
</html>"""
def square(self, num=2):
result = int(num)**2
cherrypy.session['function_called'] = 'square'
cherrypy.session['num'] = num
if 'pow' in cherrypy.session:
del(cherrypy.session['pow'])
cherrypy.session['result'] = result
return "The value of {} square is {}".format(num, result)
def power(self, num=2, pow=2):
result = int(num)**int(pow)
cherrypy.session['function_called'] = 'power'
cherrypy.session['num'] = num
cherrypy.session['pow'] = pow
cherrypy.session['result'] = result
return "The value of {} to the power {} is {}".format(num, pow, result)
def display(self):
result = ''
for ele in cherrypy.session.keys():
result += ele
result += ': '
result += str(cherrypy.session[ele])
result += '<br>'
return result
if __name__ == '__main__':
conf = {
'/': {
'tools.sessions.on': True
}
}
cherrypy.quickstart(application(), '/', conf)
Here we can see the methods and the corresponding return values.
We can store the session details by thinking of cherrypy.session as a dictionary.
Notice that the configurations of our application are changed to start session handling and the display method is defined to display last session details in a human-readable form.
Run the code through the Terminal/Command Line as follows:
python3 track_act.py
Now, if we enter http://localhost:8080/ in the address bar of a browser, the output will be something like this
Now if we call our display method, by entering http://localhost:8080/display in the address bar after making a call to square function we will an output similar to this
Similarly, we can call the display method after calling the power method. And the output will be something like this
Comments