Pyramid: how to set cookie without renderer?

情到浓时终转凉″ 提交于 2019-12-08 16:15:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!