Apologies this is a very broad question.

The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protected - I am wondering what this does and how it does it? It appears to be checking that a valid user is logged in prior to executing the do_upload_ajax function. That looks like a really effective way to do user authentication. I don't understand the mechanics of this @ function though - can someone steer me in the right direction to explain how this would be implemented in the real world? Python 3 answers please. thanks.

@bottle.route('/ajaxupload', method='POST')
@protected(check_valid_user) 
def do_upload_ajax():
    data = bottle.request.files.get('data')
    if data.file:
        size = 0

推荐答案

Take a good look at this enormous answer/novel. It's one of the best explanations I've come across.

The shortest explanation that I can give is that decorators wrap your function in another function that returns a function.

This code, for example:

@decorate
def foo(a):
  print a

would be equivalent to this code if you remove the decorator syntax:

def bar(a):
  print a

foo = decorate(bar)

Decorators sometimes take parameters, which are passed to the dynamically generated functions to alter their output.

Another term you should read up on is closure, as that is the concept that allows decorators to work.

Python-3.x相关问答推荐

错误2没有这样的文件或目录website_content.txt""

基于另一个数据帧计算总和

Django中自动设置/更新字段

无法提出给定 for 循环的原因 (Python 3.11)

attrs 将 list[str] 转换为 list[float]

当我判断另一个 checkButton 时,如何判断两个 python tkinter checkButtons?

Python ** 用于负数

为什么最简单的流光示例会出错?

Dask worker post-processing

通过 requests 库调用 API 获取访问令牌

为什么 Python 枚举中的可变值是同一个对象?

逗号分隔列表的 argparse 操作或类型

使用自定义比较删除重复项

在数据类中创建类变量的正确方法

ValueError:预期的 2D 数组,得到 1D 数组:

如何在 Python 中计算两个包含字符串的列表的 Jaccard 相似度?

Python:在 map 对象上调用列表两次

如何强制 Sphinx 使用 Python 3.x 解释器

如何修复:cx_Oracle.DatabaseError:DPI-1047:找不到 64 位 Oracle 客户端库 - Python

Python MySQLdb - 类中的连接