在配置文件中:
config.add_route('lang', '/lang-{code}')
观点:
@view_config(route_name='lang')
def lang(request):
code = request.matchdict['code']
response = Response()
response.set_cookie('lang', value=code, max_age=31536000) # max_age = year
return HTTPFound(location=request.environ['HTTP_REFERER'])
机制很简单:有一个带有语言的下拉菜单项,点击任何人都必须使用新的语言环境刷新站点。
运行没有错误,但没有设置cookie ... 我做错了什么?
谢谢!
答案 0 :(得分:12)
This answer很棒。另一种选择是将HTTPFound
实例用作Response
:
@view_config(route_name='lang')
def lang(request):
code = request.matchdict['code']
response = HTTPFound(location=request.environ['HTTP_REFERER'])
response.set_cookie('lang', value=code, max_age=31536000) # max_age = year
return response
答案 1 :(得分:10)
HTTPFound采用headers参数。尝试类似return HTTPFound(location='foo', headers=response.headers)
答案 2 :(得分:0)
使用render_to_response
设置cookie@view_config(route_name='index')
def index_view(request):
lang = 'bn'
template = '../templates/index.jinja2'
request.response.set_cookie('lang', lang)
return render_to_response(template, {'user_id':user_id}, request=request)