Liquidmetal
Liquidmetal

Reputation: 295

Adding query parameter for every flask GET request

Trying to figure out the right mechanism to use here.

I want to modify the flask request coming in every time.

I think the request is immutable, so I am trying to figure out if this mechanism exists.

Basically, I want to append a string onto the end of the request coming in.

I can hook into the request and the right time in a before_request handler like this:

@app.before_app_request
def before_request_custom():
    # Get the request
    req = flask.request

    method = str(req.method)

    if method == "GET":
        # Do stuff here
        pass

But I am not sure what to actually do to add this in, and don't see a way to accomplish it...I guess i could redirect, but that seems silly in this case. Any ideas?

Upvotes: 2

Views: 2086

Answers (3)

CamiEQ
CamiEQ

Reputation: 771

The request object is immutable (https://werkzeug.palletsprojects.com/en/1.0.x/wrappers/#base-wrappers), but request.args or request.form can be set from ImmutableOrderedMultiDict to just OrderedMultiDict using Subclassing on Flask (https://flask.palletsprojects.com/en/1.1.x/patterns/subclassing/). Here's an example of how you could add that filter[is_deleted]=False URL param:

from flask import Flask, request, Request
from werkzeug.datastructures import OrderedMultiDict

class MyRequest(Request):
    parameter_storage_class = OrderedMultiDict

class MyApp(Flask):
    def __init__(self, import_name):
        super(MyApp, self).__init__(import_name)
        self.before_request(self.my_before_method)

    def my_before_method(self):
        if "endpoint" in request.base_url:
            request.args["filter[is_deleted]"] = "False"

app = MyApp(__name__)
app.request_class = MyRequest

@app.route('/endpoint/')
def endpoint():
    filter = request.args.get('filter[is_deleted]')
    return filter

This way you can modify request.args before you actually send the request.

Upvotes: 3

GAEfan
GAEfan

Reputation: 11370

How about this?

from flask import g

@app.before_request
def before_request():

    # Get the request
    req = flask.request

    method = str(req.method)

    if method == "GET":
        g.my_addon = "secret sauce"
    return None

Then, g.my_addon is available in every view function:

from flask import g

@app.route('/my_view')
def my_view():
    if g.my_addon == "secret sauce":
         print('it worked!')

Upvotes: 0

Related Questions