【问题标题】:Is there a way to set a cookie in @before.request?有没有办法在@before.request 中设置 cookie?
【发布时间】:2019-06-27 09:12:50
【问题描述】:

我希望我的应用程序能够检测用户的语言以向他们提供相应的页面。我的想法是使用@before.request 读取Accepted-Languages 标头,将其与应用程序支持的语言进行匹配,并在需要时设置cookie,但似乎最后一步无法实现。 这是代码:

@app.before_request
def before_request_callback():
    if request.cookies.get('lang'):
        pass
    else:
        lang = request.accept_languages.best_match(supported_languages)
        print(lang)
        #I would like to set the cookie here

我考虑直接在装饰器 (resp.set_cookie()) 中设置响应对象中的 cookie,因此将我的应用程序中的所有返回重新格式化为如下所示

@app.route("/")
def hello():
    resp = make_response(render_template('index.html'))
    return resp

也许能够获取 cookie 并将其附加到此响应中,但由于响应是随后在 endpoitn 函数中创建的,所以我也不知道该怎么做。

我也想过直接在装饰器中创建响应,但是由于我需要返回条件,我不知道这是否可能

【问题讨论】:

    标签: python python-3.x flask


    【解决方案1】:

    我认为您在不需要时尝试使用 cookie。如您所述,您只能在响应中设置 cookie。您在响应中send the browser cookies,然后在任何后续请求中将它们重新发送给您。但它已经向您发送了Accept-Language。所以在请求上设置cookie是没有意义的。它已经到了,并且已经包含了您需要的东西。

    不必纠结于设置 cookie,只需在生成响应时查询请求,以确保所提供的内容采用适当的语言。

    from flask import request
    
    @app.route("/")
    def hello():
        lang = request.accept_languages.best_match(supported_languages)
        return render_template(f'{lang}/index.html')
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 2014-10-07
      • 2020-06-12
      • 2020-10-04
      相关资源
      最近更新 更多