我构建了一个视图,允许用户输入一些信息,并使用Pyramid框架将该信息作为新记录插入到我的数据库中。代码是这样的:
def orderplace_view(request):
user = User.get(authenticated_userid(request))
cart = Cart.get_by_user(user)
if cart.itemtypes == None: # cat is empty
request.session.flash(u'Empty cart')
raise HTTPFound(location = request.route_url('cart'))
placeorderform = PlaceOrderForm(request.POST)
placeorderform.address.query = UserAddress.query_by_user(user)
if request.POST and placeorderform.validate():
# create order
order = Order()
order.address = placeorderform.address.data
# fill order with other attributes...
user.orders.append(order)
# IMPORTANT LINE!!!
raise HTTPFound(location = request.route_url('order_list'))
return {'user': user,
'title': 'place order',
'cart': cart,
'placeorderform': placeorderform}
这是奇怪的事情:如果我注释掉“raise HTTPFound()”行,一切正常,新订单将被插入到数据库中。但是,如果我保留将用户重定向到订单列表页面的那一行,则不会插入订单!为什么会这样?
答案 0 :(得分:3)
如果正在使用Pyramid事务中间件,它将在视图函数引发异常时中止包含事务:http://docs.pylonsproject.org/projects/pyramid_tm/en/latest/#transaction-usage
明确提交transaction.commit()
,或者更好的是,返回HTTPFound
而不是提升它。