简体   繁体   English

Flask 将 POST 参数传递给自定义装饰器

[英]Flask pass POST parameters to custom decorator

I've seen the posts on passing GET parameters and hardcoded parameters here and here .我在这里这里看到了关于传递GET参数和硬编码参数的帖子。

What I am trying to do is pass POST parameters to a custom decorator.我想要做的是将POST参数传递给自定义装饰器。 The route is not actually rendering a page but rather processing some stuff and sending the results back through an AJAX call.route实际上并不是渲染页面,而是处理一些内容并通过 AJAX 调用将结果发送回。

The decorator looks like this:装饰器看起来像这样:

# app/util.py

from functools import wraps
from models import data

# custom decorator to validate symbol
def symbol_valid():
    def decorator(func):
        @wraps(func)
        def decorated_function(symbol, *args, **kwargs):
            if not data.validate_symbol(symbol):
                return jsonify({'status': 'fail'})
            return func(*args, **kwargs)
        return decorated_function
    return decorator

The view looks something like this:视图看起来像这样:

# app/views/matrix_blueprint.py

from flask import Blueprint, request, jsonify

from ..models import data
from ..util import symbol_valid

matrix_blueprint = Blueprint('matrix_blueprint', __name__)

# routing for the ajax call to return symbol details
@matrix_blueprint.route('/route_line', methods=['POST'])
@symbol_valid
def route_line():
    symbol = request.form['symbol'].upper()
    result = data.get_information(symbol)
    return jsonify(**result)

I understand that I can actually call @symbol_valid() when I pass a parameter through GET like this /quote_line/<symbol> but I need to POST .我知道当我通过GET这样的/quote_line/<symbol>传递参数时,我实际上可以调用@symbol_valid()但我需要POST

The question then is how can my decorator access the POST ed variable?那么问题是我的装饰器如何访问POST ed 变量?

Simple solution.简单的解决方案。 Imported Flask's request module into the util.py module which contains the decorator.将 Flask 的request模块导入到包含装饰器的util.py模块中。 Removed the outer function as well.也删除了外部功能。

See code:见代码:

# app/util.py

from flask import request # <- added

from functools import wraps
from models import data

# custom decorator to validate symbol

def symbol_valid(func):
    @wraps(func)
    def decorated_function(*args, **kwargs): # <- removed symbol arg
        symbol = request.form['symbol'] # <- paramter is in the request object
        if not data.validate_symbol(symbol):
            return jsonify({'status': 'fail'})
        return func(*args, **kwargs)
    return symbol_valid

The decorator accept a func parameter. decorator接受一个func参数。 You must use your decorator like @symbol_valid() or make the function symbol_valid accept a func parameter.您必须使用像@symbol_valid()这样的装饰器或使函数symbol_valid接受一个func参数。

If you are doing it right, you can access the request object anywhere during the request cycle.如果你做得对,你可以在请求周期内的任何地方访问request对象。 It just works.它只是有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM