python - Flask 如何通过装饰器传递 request 变量,而无需我将 request 作为参数?

标签 python flask python-decorators

我一直在学习 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() 获得意外的关键字参数“request”。但是,当我输入 def hello_world(request) 时,它会按预期工作。那么,如何让它在仅使用 def hello_world() 的情况下工作?

最佳答案

Flask 使用 Thread Local,这就是“魔法”发生的方式。请参阅https://flask.palletsprojects.com/en/1.1.x/advanced_foreword/https://werkzeug.palletsprojects.com/en/1.0.x/local/了解更多

关于python - Flask 如何通过装饰器传递 request 变量,而无需我将 request 作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63717828/

相关文章:

python - 在 Python 中导入嵌套模块

python - 为什么我的想法在 python2 中不起作用?

python - 使用装饰器链在程序退出时注册类方法

python - Flask,获取本地时间

python - 如何为 sphinx 文档保留装饰类的文档字符串?

python - astropy.io.votable - 是否有一种简单的方法来获取 VOTable 参数?

Python 无法识别 'imread' 函数

Python:使用 dis 分析列表理解

仅当我在 apache2 或 nginx 中部署 Flask 应用程序时,Python 中的 sqlite3 "OperationalError: unable to open database file"

python - 如何使用 conda 环境从终端启动 flask 应用程序