Cache Session in Python

Asked

Viewed 213 times

0

I have a script Python running a Tornado application. Inside the onmessage I have several variables that will keep an equal value always, so there is no need to fill them in whenever a new message for Tornado arrives.

Currently I do as follows: save the variable as global and define a value to it; in this way as the script is always running, the value persists.

I would like to know if there is any library that manages a cookie or a session so I can save these variables.

Follow an example of how the code is now:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

var1 = ""
def teste():
    global var1
    if var1 == "":
        var 1 = "texto que vai persistir"
    print var1
    return var1

class WSMesa(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
    def on_message(self, message):
        retorno = teste()
        self.write_message(retorno)
    def on_close(self):
        print 'connection closed'
    def check_origin(self, origin):
        return True

application = tornado.web.Application([
    (r'/mesa', WSMesa)
])

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(9999)
    tornado.ioloop.IOLoop.instance().start()

  • Would the idea be to store these values in a cookie? But won’t the process of reading the cookie be more costly than setting the value of the variable itself? If they don’t vary, you can define them as constant, both in the overall scope, if it makes sense to do so, or in the scope of the class, as class attributes. It will be easier to understand what you want to do if you [Edit] the question and add that snippet of code.

  • I put an example code where I need to only give the value to "var1" once, of course it is only an example but the logic is completely the same... The way it works well but I don’t think it’s the most elegant way to do it (I don’t know what I think)

1 answer

0

Why you do not store in the class itself, so you will be able to use an attribute that can be seen between all instances of the same class.

class WSMesa(tornado.websocket.WebSocketHandler):
    var1 = 'word' # atributo de classe

    def open(self):
        print 'new connection'

    def on_message(self, message):
        retorno = self.var1 #acessa atributo de classe
        self.write_message(retorno)

    def on_close(self):
        print 'connection closed'

    def check_origin(self, origin):
        return True

And everything else continues, only abolishes the test function and the global variable var1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.