zoukankan      html  css  js  c++  java
  • 六十八:flask上下文之app上下文和request上下文

    app上下文:

    先看现象

    current_app源码

    手动入栈

    app_context()源码

    with语句入栈

    request上下文

    不在app上下文中

    即使手动入栈也会报错,不在请求上下文中

    url_for()源码

    手动推入请求上下文

    应用上下文和请求上下文都是存放到一个LocalStack的栈中的,和应用app相关的操作就必须用到请求上下文,比如用url_for反转视图函数
    1、在视图函数中,不用担心上下文的问题,因为视图函数要执行,那么肯定是通过访问url方式来执行,这种情况下,flask底层就已经自动把请求上下文和应用上下文都推入到了相应的栈中
    2、如果想要在视图函数外执行相关操作,比如获取当前app(current_app),或者是反转url,则必须手动推入上下文
      1.手动推入app上下文
        第一种方式
          app_context = app.app_context()
          app_context.push()
          print(current_app)
        第二种方式
          with app.app_context():
          print(current_app)
      2.手动推入请求上下文:
      推入请求上下文到栈中,会首先判断有没有应用上下文,如果没有则会先推入应用上下文到栈中,然后再推入请求上下文到栈中
        with app.text_request_context():
          print(current_app)
    3、上下文需要放在栈中的原因
      1.应用上下文
      flask底层是基于werkzeug,werkzeug是可以包含多个app的,所以这个时候用一个栈来保存,如果要使用app1,则app1需在栈的顶部,如果用完了app1,则app1应该从栈中删除,方便其他代码使用下面的app

      2.请求上下文
      如果在写测试代码或者离线脚本的时候,有时候可能需要穿件多个请求上下文,这个时候就需要存放到另一个栈中,使用哪个请求上下文的时候,就把对应的请求上下文放到栈的顶部,用完了就要把这个请求上下文从栈中移除掉

  • 相关阅读:
    LeetCode 623. Add One Row to Tree
    LeetCode 894. All Possible Full Binary Trees
    LeetCode 988. Smallest String Starting From Leaf
    LeetCode 979. Distribute Coins in Binary Tree
    LeetCode 814. Binary Tree Pruning
    LeetCode 951. Flip Equivalent Binary Trees
    LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List
    LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal
    LeetCode 687. Longest Univalue Path
    LeetCode 428. Serialize and Deserialize N-ary Tree
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/11873967.html
Copyright © 2011-2022 走看看