How would I return the same exact JSON data from one class to another?
Code:
class Class1(webapp.RequestHandler):
def get(self):
random_id = str(uuid.uuid1())
time_now = int(time.time())
info = {
id: random_id,
now: time_now
}
json_info = json.dumps(info)
print json_info
self.response.write(info)
class Class2(webapp.RequestHandler):
def get(self):
getting_info = self.Class1()
getting_info_time = getting_info['now']
print getting_info_time
Error:
class1_info = self.Class1()
AttributeError: ‘Class2’ object has no attribute ‘Class1’
Edit (more details):
One part of my application needs the whole JSON output while the other part needs just the now
value from the info dictionary. And both classes would be using the same exact data from the info dictionary.
I’ve been trying to get the now
output but I just get error messages.
Attempt:
Note: using @Alex’s answer (with @snakecharmerb recommendation of memcache)
Code:
from google.appengine.api import memcache
class Class1(webapp.RequestHandler):
def generate_data(self):
random_id = str(uuid.uuid1())
time_now = int(time.time()))
id_cached = memcache.add(key=random_id, value=random_id, time=600)
get_id_cached = memcache.get(key=random_id, value=random_id, time=600)
time_cached = memcache.add(key=time_now, value=time_now, time=600)
get_time_cached = memcache(key=time_now)
info = {
id: get_id_cached,
now: get_time_cached
}
json_info = json.dumps(info)
return json_info
def get(self):
self.response.write(generate_data())
class Class2(webapp.RequestHandler):
def get(self):
getting_info = Class1().generate_data()
print getting_info
Result:
{“id”: “9d752605-a20d-11e7-8bfd-bfe81b332704”, “time”: “1506356501”}
{“id”: “9b95e899-a20d-11e7-b137-bfe81b332704”, “time”: “1506356498”}
2
Answers
It would help to know more about what you’re trying to do, but based on your code snippet, this should do it.
Another route would be having Class2 inherit Class1, another route would be moving the ‘perform’ function outside at the file level. It’s hard to give a more appropriate answer without more context.
Edit:
Creating a ‘BaseHandler’ that both classes inherit seems more appropriate then. Check for existence of the cached ID, if None, create & add.
If both handlers need to access the same data, delegate the data generation to a function.
This approach will work if the data is newly generated for each request. If you need to return the same data for each request then you need to store it for example in the datastore, memcache or a session so that it can be retrieved.