|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 qiuyouzhi 于 2020-3-11 14:02 编辑
Flask学习笔记2:请求-响应循环1
程序和请求上下文
Flask从客户端接收到请求时,要让视图函数能访问一些对象,
这样才能处理请求。请求对象就封装了客户端所发送的HTTP请求。
要想访问这个对象,可以把它当成视图函数的参数,但是这样会导致
每个视图函数都增加一个参数,函数就会变得很繁琐,而且
还有可能会处理其他的请求,整个程序就会一团糟。
Flask为了避免这样的情况,搞出了一个叫做上下文
的东西,可以临时把某个对象变成全局可访问。
有了上下文,我们就可以这样写:
- from flask import request
- @app.route('/')
- def index():
- user_agent = request.headers.get('User-Agent')
- return "<p>Your Browser is %s</p>" % user_agent
复制代码
看,我们把这个request临时设置成了全局变量,但request不可能是全局变量。
试想,在多线程服务器中,多个线程要处理不同客户端发来的不同请求,
而每个线程看到的request肯定是不一样的。
Flask使用上下文让特定的变量在一个线程中全局可访问,同时不会
影响其他的线程。
在Flask中有两种上下文,一种是程序上下文,一种是请求上下文。
current 程序上下文 当前激活程序的程序实例
g 程序上下文 处理请求时所用的临时变量,每次请求都会重设这个变量
request 请求上下文 请求对象,封装了客户端发出的HTTP请求中的内容
session 请求上下文 用户会话,用于存储请求之间需要"记住"的词的词典
Flask在分发请求之前激活(推送)程序和程序上下文,请求处理完成后再将其删除。
程序上下文被推送后,就可以使用current和g变量。类似的,请求上下文被推送后,
就可以使用request和session变量。如果没有激活上下文的话,就会导致错误。
来看一段代码栗子:
- >>> from hello import app
- >>> # 这个hello是你自己的文件名(hello.py)
- >>> from flask import current_app
- >>> current_app.name
- Traceback (most recent call last):
- File "<pyshell#47>", line 1, in <module>
- current_app.name
- File "C:\Users\rzzl\AppData\Local\Programs\Python\Python38\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
- return getattr(self._get_current_object(), name)
- File "C:\Users\rzzl\AppData\Local\Programs\Python\Python38\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
- return self.__local()
- File "C:\Users\rzzl\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\globals.py", line 52, in _find_app
- raise RuntimeError(_app_ctx_err_msg)
- RuntimeError: Working outside of application context.
- This typically means that you attempted to use functionality that needed
- to interface with the current application object in some way. To solve
- this, set up an application context with app.app_context(). See the
- documentation for more information.
- >>> #没激活上下文会报错
- >>> app_ctx = app.app_context() # 在程序实例上掉用app_context可以获得一个程序上下文
- >>> app_ctx.push() # 推送
- >>> current_app.name
- 'hello'
- >>> app_ctx.pop() # 结束上下文的使用
复制代码
|
|