Flask 如何在我不将请求作为参数的情况下通过装饰器传递请求变量?
How does Flask pass request variable through a decorator without me putting request as an argument?
我一直在学习 python 装饰器,我想知道 flask 如何将 request
变量传递到我用路径装饰的函数中。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
print(request)
return 'Hello, World!'
这个请求怎么存在?为什么我在编写函数时不必输入 def hello_world(request)
?
当我尝试让自己的包装器像这样模仿这种行为时
def wrapper(function):
def wrapped_item(*args, **kwargs):
request = "yes"
function(*args, **kwargs, request=request)
return wrapped_item
@wrapper
def hello_world():
print(request)
hello_world()
它会导致错误 TypeError: hello_world() got an unexpected keyword argument 'request'
。但是,当我输入 def hello_world(request)
时,它会按预期工作。那么,我如何让它与 def hello_world()
一起工作?
Flask 使用 Thread Local,这就是“魔法”发生的方式。有关更多信息,请参阅 https://flask.palletsprojects.com/en/1.1.x/advanced_foreword/ and https://werkzeug.palletsprojects.com/en/1.0.x/local/
这是你导入的变量
from flask import request
您的代码示例不包含它,但我相信您的文件中有它。
我一直在学习 python 装饰器,我想知道 flask 如何将 request
变量传递到我用路径装饰的函数中。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
print(request)
return 'Hello, World!'
这个请求怎么存在?为什么我在编写函数时不必输入 def hello_world(request)
?
当我尝试让自己的包装器像这样模仿这种行为时
def wrapper(function):
def wrapped_item(*args, **kwargs):
request = "yes"
function(*args, **kwargs, request=request)
return wrapped_item
@wrapper
def hello_world():
print(request)
hello_world()
它会导致错误 TypeError: hello_world() got an unexpected keyword argument 'request'
。但是,当我输入 def hello_world(request)
时,它会按预期工作。那么,我如何让它与 def hello_world()
一起工作?
Flask 使用 Thread Local,这就是“魔法”发生的方式。有关更多信息,请参阅 https://flask.palletsprojects.com/en/1.1.x/advanced_foreword/ and https://werkzeug.palletsprojects.com/en/1.0.x/local/
这是你导入的变量
from flask import request
您的代码示例不包含它,但我相信您的文件中有它。