def get_items_from_cart(self):
""" Fetches items from sessions cart"""
item_list = []
cart_count = self.session.get('add_to_cart_count')
if not cart_count: return None;
for i in range(1, cart_count+1):
item = self.session.get(str(i))
if item:
item_list.append(item)
return item_list
class AddToCartHandler(Handler):
def get(self):
if users.get_current_user():
self.response.headers['Content-type'] = 'application/json'
get_current_add_count = int(self.session.get('add_to_cart_count'))
tshirt_id = self.request.get("tshirt_id")
item_title = self.request.get("item_title")
qty = self.request.get("qty")
size = self.request.get("size")
price = 325
get_current_add_count += 1
self.session[get_current_add_count] = { "qty" : qty, "size" : size ,
"item_title": item_title,
"tshirt_id" : tshirt_id,
"cost" : price * int(qty)}
current_cart_items = int(self.session.get("item_count"))
updated_cart_items = current_cart_items + int(qty)
self.session["item_count"] = updated_cart_items
self.session["add_to_cart_count"] = get_current_add_count
self.write(json.dumps({"status" : 1, "msg" : "Order added. <a href='/cart'><span class='label label-success'>View Cart</span></a>"}))
else:
self.write(json.dumps({"status" : 0, "msg" : "Please <a href='/login'><span class='label label-important'>login</span> </a>to start shopping!"}))
在方法“get_items_from_cart”中,代码描述了获取名为数字的值并附加列表。那些是json编码(我还不知道json)。 我想问一下,python是否允许在会话中将变量命名为number? 如果我在错误的环境中获取代码,请指导我。
答案 0 :(得分:0)
以下是我的问题的答案...... 这段代码工作正常。
import webapp2
from webapp2_extras import sessions
from google.appengine.api import users
class Handle(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)
@webapp2.cached_property
def session(self):
return self.session_store.get_session()
class ValTest(Handle):
def get(self):
user = users.get_current_user()
val = self.session.get("1")
val += 1
self.session["1"] = val
self.response.write('value is: %i' % val)
self.response.write('<form method="get" action="/valTst"><input type="submit" name="btn2" value="Incr"></form>')
class MainHandler(Handle):
def get(self):
self.response.write('Hello world!')
user = users.get_current_user()
self.session["1"] = 10
self.response.write('<form method="get" action="/valTst"><input type="submit" name="btn" value="show"></form>')
### Configuration ###
config = {}
config['webapp2_extras.sessions'] = {
'secret_key': 'my-super-secret-key',
}
app = webapp2.WSGIApplication([
('/', MainHandler),
('/valTst', ValTest)
], debug=True, config=config)