Riko Kurahashi
Riko Kurahashi

Reputation: 61

Setting a parameter in Post body to header when accessing Get endpoint in Flask?

I am working on a simple service with my show_greeting endpoint handling Get request while set_greeting is my Post. The purpose of this app is that when "header_message: {header parameter}" is sent to set_greeting, {header parameter} will be returned in the header for responses to show_greeting and to reset {header parameter}, "clear" would reset header_message and header.

I have tried using global variables but encountered an error with shadowing from outside the scope and am not sure which approach to take for this. For now, I would like to learn how to return {header parameter} from my /show_greeting endpoint.

Edit: The /show_greeting endpoint returns holiday_message from the request. The header that I would like to send in addition to holiday_message is "header_message".

My code is as follows:

from flask import Flask, request, make_response, Response

app = Flask(__name__)

@app.route('/show_greeting', methods=['GET'])
def show_greeting():
    received = request.args    
    (I do not know how to set header here from header_message in set_greeting)
    return received['holiday_message']


@app.route('/set_greeting', methods=['POST'])
def set_greeting():
    posted = request.args
    if 'header_message' in posted:
        (I attempted save_message = posted['header_message'] here but this approach failed)
        return "Header Message Set"
    else:
        return "Please Send A Header Message"

if __name__ == '__main__':
    app.run()

Upvotes: 1

Views: 789

Answers (2)

Detlef
Detlef

Reputation: 8552

My recommendation is to use the session object. It stores the data in a cookie, which is sent with every request. If a cookie is not desired, there are other options for saving sessions. For this, however, an extension will be necessary.

Saving with global variables should also work, but is not recommended.
A file or a database can also be used if the data is to be saved across multiple requests from many users.

The data of the post body can be accessed via request.form, while the url parameters of a get request can be queried via request.args.

from flask import Flask
from flask import request, session

app = Flask(__name__)

app.secret_key = b'your secret here'

@app.route('/show_greeting', methods=['GET'])
def show_greeting():
    received = request.args
    # get the saved message or an empty string if no message is saved
    header_message = session.get('header_message', '')
    return f"{received['holiday_message']} - {header_message}"

@app.route('/set_greeting', methods=['POST'])
def set_greeting():
    posted = request.form
    if 'header_message' in posted:
        # store the message 
        session['header_message'] = posted['header_message']
        return "Header Message Set"
    else:
        # clear the message 
        session.pop('header_message', None)
        return "Please Send A Header Message"

Much success in your further steps.

Upvotes: 1

J. Rios
J. Rios

Reputation: 54

If I understood your problem, you can work with "g" the flask global object.

Check this code, I expect it will fix your issue.

from flask import g # Added

from flask import Flask, request, make_response, Response

app = Flask(__name__)

@app.route('/show_greeting', methods=['GET'])
def show_greeting():
    received = request.args    
    return g.saved_message # Modified


@app.route('/set_greeting', methods=['POST'])
def set_greeting():
    posted = request.args
    if 'message' in posted:

        g.saved_message = posted['request'] # Added

        return "Message Set"
    else:
        return "Please Send A Greeting Message"

if __name__ == '__main__':
    app.run()

Upvotes: 0

Related Questions