Flask 深入上下文作用域

比如说你有一个应用函数返回用户应该跳转到的 URL 。想象它总是会跳转到 URL 的 ​next​ 参数,或 HTTP referrer ,或索引页:

from flask import request, url_for

def redirect_url():
    return request.args.get(next) or 
           request.referrer or 
           url_for(index)

如你所见,它访问了请求对象。当你试图在纯 Python shell 中运行这段代码时, 你会看见这样的异常:

>>> redirect_url()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: NoneType object has no attribute request

这有很大意义,因为我们当前并没有可以访问的请求。所以我们需要制造一个 请求并且绑定到当前的上下文。 ​test_request_context​ 方 法为我们创建一个 ​RequestContext​:

>>> ctx = app.test_request_context(/?next=http://example.com/)

可以通过两种方式利用这个上下文:使用 with 声明或是调用 ​push()​ 和 ​pop()​ 方法:

>>> ctx.push()

从这点开始,你可以使用请求对象:

>>> redirect_url()
uhttp://example.com/

直到你调用 pop:

>>> ctx.pop()

因为请求上下文在内部作为一个栈来维护,所以你可以多次压栈出栈。这在实现 内部重定向之类的东西时很方便。

作者:andy,如若转载,请注明出处:https://www.web176.com/flask/20469.html

(0)
打赏 支付宝 支付宝 微信 微信
andy的头像andy
上一篇 2023年5月16日
下一篇 2023年5月16日

相关推荐

发表回复

登录后才能评论