问题
In configuration file:
config.add_route('lang', '/lang-{code}')
In views:
@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'])
The mechanism is simple: there is a dropped down menu item with languages and clicking on anyone must refresh site with new locale.
Runs without errors, but no cookie set up... What I did wrong?
Thanks!
回答1:
HTTPFound takes a headers parameter. Try something like return HTTPFound(location='foo', headers=response.headers)
回答2:
This answer is excellent. Another option is usage of the HTTPFound
instance as a 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
回答3:
Set cookie by using render_to_response
@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)
来源:https://stackoverflow.com/questions/8746087/pyramid-how-to-set-cookie-without-renderer