0

Is it possible to set a thread or something alike to store a value among each server request?

I understand that values from threads or globals are get/set only during each server request, also this values cannot be changed out of context because everything is done inside "mapped" classes.

Eventhough I am just being curious out of this because it would be great to set a value and manipulate it over each request, I don't know it may be a variable stored in memory so that it may be referenced later.

I am saying this because sessions, cookies and everthing related to a web application is manipulated only through each GET/POST request. o far this is what I have:

import web
import threading


threadlocal = threading.local()

def set_value():
    setattr(threadlocal, 'mythread', 'threadvalue')


def get_value():
    return getattr(threadlocal, 'mythread', None)




urls = (
    "/set_thread_value", "set_thread_value",
    "/get_thread_value", "get_thread_value"
)


app = web.application(urls, globals())



t_globals = {
    'template_thread': get_value()
}    
render = web.template.render('templates', globals=t_globals)



class set_thread_value:
    def GET(self):

        set_value()

        return get_value()




class get_thread_value:
    def GET(self):

        return get_value()

As you can see when you call "set_thread_value" you set the thread value and it is displayed on screen, but when you call "get_thread_value" you will get None instead.

You may also have noticed that I want to pass the thread to a template so that it can be displayed with its updated value.

Edit:I don't want to use mysql, mongodb or any other storing system to set the value from the thread.

Thanks in advance.

Uuid
  • 2,506
  • 5
  • 28
  • 37
  • Are you aware application is normally hosted on many threads? What you want to do is plain wrong. What is your use case excatly? – Krzysztof Szularz Nov 25 '12 at 19:52
  • I want to set that value so that it can be displayed on the template, I have found something that aproaches to what I want to do: http://stackoverflow.com/a/6688459/1747721 – Uuid Nov 25 '12 at 19:55
  • 2
    Use memcache or something similar - that's what it's there for – Timmy O'Mahony Nov 25 '12 at 20:15
  • Hey @TimmyO'Mahony you are right man with memcache I can store the value and keep on memory so I can use it later, how can I choose your answer? – Uuid Nov 25 '12 at 20:25

1 Answers1

3

You should user something like memcache (or redis) to store content and values which you need to persist in memory across requests. Here's a related question regarding globals:

Python Django Global Variables

Community
  • 1
  • 1
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177