Home:ALL Converter>Flask pass POST parameters to custom decorator

Flask pass POST parameters to custom decorator

Ask Time:2015-11-13T14:03:19         Author:Jason Strimpel

Json Formatter

I've seen the posts on passing GET parameters and hardcoded parameters here and here.

What I am trying to do is pass POST parameters to a custom decorator. The route is not actually rendering a page but rather processing some stuff and sending the results back through an AJAX call.

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.

The question then is how can my decorator access the POSTed variable?

Author:Jason Strimpel,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/33686834/flask-pass-post-parameters-to-custom-decorator
Jason Strimpel :

Simple solution. Imported Flask's request module into the util.py module which contains the decorator. Removed the outer function as well.\n\nSee code:\n\n# app/util.py\n\nfrom flask import request # <- added\n\nfrom functools import wraps\nfrom models import data\n\n# custom decorator to validate symbol\n\ndef symbol_valid(func):\n @wraps(func)\n def decorated_function(*args, **kwargs): # <- removed symbol arg\n symbol = request.form['symbol'] # <- paramter is in the request object\n if not data.validate_symbol(symbol):\n return jsonify({'status': 'fail'})\n return func(*args, **kwargs)\n return symbol_valid\n",
2015-11-15T12:53:06
yy