使用Datastore來保持不同提交數據的自然方法是使用Datastore。
如果爲了鍛鍊而不想使用數據存儲區,則必須將數據傳遞到視圖,並在每個Web請求之間使用一些hidden
字段將其讀回。
讓我們來看看一個簡單的快速&髒例如:一個網頁應用程序,一個一個地求和整數。
application.py
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
class Sum(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'index.html')
template_values = {"total":0}
self.response.out.write(template.render(path, template_values))
def post(self):
value = self.request.get("value")
total = self.request.get("total")
total = int(total) + int(value)
path = os.path.join(os.path.dirname(__file__), 'index.html')
template_values = {"value":value,
"total":total
}
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication(
[('/', Sum),
('/sum', Sum)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
將數據傳遞到index.html
視圖中,template.render函數用於使攜帶結果向視圖字典變量:
template.render(path_to_the_view, template_values)
index.html
<html>
<body>
<form action="/sum" method="post">
<p>
<label for="value">Value to sum:
<input type="text" name="value"><br>
<input type="submit" value="Submit">
<input type="hidden" name="total" value="{{ total }}">
</p>
</form>
Last value submitted: {{ value }}| Total:{{ total }}
</body>
</html>
index.html
視圖使用字典鍵value
和total
來顯示結果並使用hidden
字段將總數提交給控制器。
這裏是結果:
啊!我有一些問題。 1.是否可以用兩個不同的類來做到這一點?我注意到你將兩個類組合成一個... 2.如果您使用數據存儲區跨類進行通信,那麼這將如何工作?看起來如果用戶A提交了一個值 - 比如說「3」並提交了它,那麼總和等於3,並且你會將它存儲在你的數據存儲中。然後,用戶B提交4,並且如預期的那樣,他將返回7,而不是4。你是否還需要爲每個用戶存儲一個唯一的ID? – Jeremy 2011-03-24 22:48:59
@Jeremy 1)是的 - 它所處理的處理程序類並不重要。 2)這正是你已經看過的演示所做的。 – 2011-03-25 02:24:32
@jeremy 1.您可以在滿足您的需求的幾個類中組織您的代碼;它並不重要。 2.如果你想在我的天真例子中使用數據存儲,是的,你應該區分每個用戶。 – systempuntoout 2011-03-25 08:09:29