Flask Session does not retain value between POST requests - python

So I'm using flask to create endpoints as receivers and data processors. I have two threads of http POST requests, the first one is sent to the first route, similarly for the second one. The thing is I want the 2nd processor to be triggered only when the 1st one is, so I created a session key, to validate for the execution of the 2nd processor.
But no matter what I did, session key is always wiped when I sent POST to the second processor. Here's my code, which has been simplified. Pardon my amateur ablity to express the problem, I'm extremely new to coding.
from flask import Flask, request, redirect, url_for, session
app = Flask(__name__)
app.secret_key = "abc"
#app.route('/first_processor', methods=['POST'])
def first_processor():
data = {
'message': 'json received',
'json': request.json
}
cond = data['json']
if cond['event'] == "message:received":
session["key"] = cond['key']
return redirect(url_for("second_processor"))
else:
return data
#app.route('/second_processor', methods=['POST'])
def second_processor():
if "key" in session:
print('OK')
else:
print("FAIL")
return data
if __name__ == "__main__":
app.run(debug=True)

Apparently I saw two minor problems. The first one is that
#app.route('/second_processor', methods=['POST']) `
only allows POST method, and
redirect(url_for("second_processor"))
is a GET request. And you cannot force a POST request. Even though, according to the documentation, there is a _method parameter in the url_for function.
Related question: Issue a POST request with url_for in Flask
The second problem is that you created the data variable inside the first_processor function, but you don't pass it to the second_processor.
if 'key' in session:
print('OK')
else:
print("FAIL")
--> return data
you could either:
pass the data inside the session,
make data global ( not sure if it is a good practice though)
store data in a file or db and read it inside second_processor.

Related

Increment the cookie value in Flask

I want to count the number of visits to the page. Below is the code for the same. When I run the code, it doesn't set the 'visit_count' cookie and '/visit' returns 'None' value. What's the problem?
from flask.helpers import make_response
app = Flask(__name__)
#app.route('/', methods=['GET','POST'])
def show_page():
return render_template('cookiecounter.html')
#app.route('/setcookie', methods=['GET','POST'])
def setcookie():
resp = make_response('Welcome to our site!')
resp.set_cookie('user_visit',str(1), max_age=5*60*60)
return resp
#app.route('/visit', methods=['GET','POST'])
def visit():
vc=request.cookies.get('user_visit')
if vc==1:
return 'You are visiting for the first time'
else:
vscount=int(vc)+1
resp1 = make_response('new visit')
resp1.set_cookie('visit_count',str(vscount), max_age=5*60*60)
inc_count=request.cookies.get('visit_count')
return str(inc_count)
if __name__=="__main__":
app.run(debug=True)
There's a couple things going on that cause the unexpected result.
resp1.set_cookie('visit_count',str(vscount), max_age=5*60*60)
When you do this you're not actually setting the cookie's value yet, just preparing the response so that the cookie will be set once the client receives your response.
inc_count=request.cookies.get('visit_count')
Since the previous statement did not actually set any cookie, this is effectively retrieving the same value as when you first called it, which is the old value.
return str(inc_count)
Remember how you set up your response so that it would set a cookie on the client? Since you're not returning that response, the updated cookie is never set and you're left with the old one (which in your case is no cookie at all). Plus you're also returning the old value because you retrieved it in the line before.
Another thing is you're checking equality between your variable holding the string "1" and the number 1, that is probably not what you meant to do.
I'm not sure why you're using two different cookies user_visit and visit_count.
from flask.helpers import make_response
from flask import Flask, request
app = Flask(__name__)
#app.route('/visit', methods=['GET','POST'])
def visit():
vc=request.cookies.get('user_visit', "1")
resp = make_response(f"This is visit number {int(vc)}")
vscount=int(vc)+1
resp.set_cookie('user_visit',str(vscount), max_age=5*60*60)
return resp
This is probably close to what you wanted to achieve.
https://docs.python.org/3/library/stdtypes.html#dict.get (dict get)
https://www.python.org/dev/peps/pep-0498/ (string interpolation)
Happy pythoning

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()
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.
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()

Flask - Pass back response of inner request

I looked at some of the similar suggested SO questions, but they weren't quite what I was looking for:
I have a Flask server with a POST route that calls another server. I want Flask to return the response from that request as-is.
import os
import requests
from flask import Flask, request, jsonify, make_response, Response
#app.route('/stuff', methods=['POST'])
def get_stuff():
resp = requests.post(...)
return resp
app.run(host='0.0.0.0', port=9999)
I've tried the following but each returns an error:
return jsonify(resp)
return ( resp.raw.read(), resp.status_code, resp.headers.items() )
return Response(json.dumps(resp), status=resp.status_code, mimetype='application/json')
I just want it to pass back what it got
Flask route functions should only return a string, you need a method to convert it and each of the attempts you made probably fell short in one way or another to do so.
Post the error messages, they may clue in how close you are to accomplishing the rerouting of the post response.

How to test redirection In Flask with Python unittest?

I am currently trying to write some unit tests for my Flask application. In many of my view functions (such as my login), I redirect to a new page. So for example:
#user.route('/login', methods=['GET', 'POST'])
def login():
....
return redirect(url_for('splash.dashboard'))
I'm trying to verify that this redirect happens in my unit tests. Right now, I have:
def test_register(self):
rv = self.create_user('John','Smith','John.Smith#myschool.edu', 'helloworld')
self.assertEquals(rv.status, "200 OK")
# self.assert_redirects(rv, url_for('splash.dashboard'))
This function does make sure that the returned response is 200, but the last line is obviously not valid syntax. How can I assert this? My create_user function is simply:
def create_user(self, firstname, lastname, email, password):
return self.app.post('/user/register', data=dict(
firstname=firstname,
lastname=lastname,
email=email,
password=password
), follow_redirects=True)
Flask has built-in testing hooks and a test client, which works great for functional stuff like this.
from flask import url_for, request
import yourapp
test_client = yourapp.app.test_client()
with test_client:
response = test_client.get(url_for('whatever.url'), follow_redirects=True)
# check that the path changed
assert request.path == url_for('redirected.url')
For older versions of Flask/Werkzeug the request may be available on the response:
from flask import url_for
import yourapp
test_client = yourapp.app.test_client()
response = test_client.get(url_for('whatever.url'), follow_redirects=True)
# check that the path changed
assert response.request.path == url_for('redirected.url')
The docs have more information on how to do this, although FYI if you see "flaskr", that's the name of the test class and not anything in Flask, which confused me the first time I saw it.
Try Flask-Testing
there is api for assertRedirects you can use this
assertRedirects(response, location)
Checks if response is an HTTP redirect to the given location.
Parameters:
response – Flask response
location – relative URL (i.e. without http://localhost)
TEST script:
def test_register(self):
rv = self.create_user('John','Smith','John.Smith#myschool.edu', 'helloworld')
assertRedirects(rv, url of splash.dashboard)
One way is to not follow the redirects (either remove follow_redirects from your request, or explicitly set it to False).
Then, you can simply replace self.assertEquals(rv.status, "200 OK") with:
self.assertEqual(rv.status_code, 302)
self.assertEqual(rv.location, url_for('splash.dashboard', _external=True))
If you want to continue using follow_redirects for some reason, another (slightly brittle) way is to check for some expected dashboard string, like an HTML element ID in the response of rv.data. e.g. self.assertIn('dashboard-id', rv.data)
You can verify the final path after redirects by using Flask test client as a context manager (using the with keyword). It allows keeping the final request context around in order to import the request object containing request path.
from flask import request, url_for
def test_register(self):
with self.app.test_client() as client:
user_data = dict(
firstname='John',
lastname='Smith',
email='John.Smith#myschool.edu',
password='helloworld'
)
res = client.post('/user/register', data=user_data, follow_redirects=True)
assert res.status == '200 OK'
assert request.path == url_for('splash.dashboard')

How do you access the query string in Flask routes?

How do you access query parameters or the query string in Flask routes? It's not obvious from the Flask documentation.
The example route /data below illustrates the context that I would like to access that data. If someone requests something like example.com/data?abc=123, I would like access to the string ?abc=123 or to be able to retrieve the value of parameters like abc.
#app.route("/data")
def data():
# query_string = ???
return render_template("data.html")
from flask import request
#app.route('/data')
def data():
# here we want to get the value of user (i.e. ?user=some-value)
user = request.args.get('user')
The full URL is available as request.url, and the query string is available as request.query_string.decode().
Here's an example:
from flask import request
#app.route('/adhoc_test/')
def adhoc_test():
return request.query_string
To access an individual known param passed in the query string, you can use request.args.get('param'). This is the "right" way to do it, as far as I know.
ETA: Before you go further, you should ask yourself why you want the query string. I've never had to pull in the raw string - Flask has mechanisms for accessing it in an abstracted way. You should use those unless you have a compelling reason not to.
I came here looking for the query string, not how to get values from the query string.
request.query_string returns the URL parameters as raw byte string (Ref 1).
Example of using request.query_string:
from flask import Flask, request
app = Flask(__name__)
#app.route('/data', methods=['GET'])
def get_query_string():
return request.query_string
if __name__ == '__main__':
app.run(debug=True)
Output:
References:
Official API documentation on query_string
We can do this by using request.query_string.
Example:
Lets consider view.py
from my_script import get_url_params
#app.route('/web_url/', methods=('get', 'post'))
def get_url_params_index():
return Response(get_url_params())
You also make it more modular by using Flask Blueprints - https://flask.palletsprojects.com/en/1.1.x/blueprints/
Lets consider first name is being passed as a part of query string
/web_url/?first_name=john
## here is my_script.py
## import required flask packages
from flask import request
def get_url_params():
## you might further need to format the URL params through escape.
firstName = request.args.get('first_name')
return firstName
As you see this is just a small example - you can fetch multiple values + formate those and use it or pass it onto the template file.
Werkzeug/Flask as already parsed everything for you. No need to do the same work again with urlparse:
from flask import request
#app.route('/')
#app.route('/data')
def data():
query_string = request.query_string ## There is it
return render_template("data.html")
The full documentation for the request and response objects is in Werkzeug: http://werkzeug.pocoo.org/docs/wrappers/
Try like this for query string:
from flask import Flask, request
app = Flask(__name__)
#app.route('/parameters', methods=['GET'])
def query_strings():
args1 = request.args['args1']
args2 = request.args['args2']
args3 = request.args['args3']
return '''<h1>The Query String are...{}:{}:{}</h1>''' .format(args1,args2,args3)
if __name__ == '__main__':
app.run(debug=True)
Output:
Every form of the query string retrievable from flask request object as described in O'Reilly Flask Web Devleopment:
From O'Reilly Flask Web Development, and as stated by Manan Gouhari earlier, first you need to import request:
from flask import request
request is an object exposed by Flask as a context variable named (you guessed it) request. As its name suggests, it contains all the information that the client included in the HTTP request. This object has many attributes and methods that you can retrieve and call, respectively.
You have quite a few request attributes which contain the query string from which to choose. Here I will list every attribute that contains in any way the query string, as well as a description from the O'Reilly book of that attribute.
First there is args which is "a dictionary with all the arguments passed in the query string of the URL." So if you want the query string parsed into a dictionary, you'd do something like this:
from flask import request
#app.route('/'):
queryStringDict = request.args
(As others have pointed out, you can also use .get('<arg_name>') to get a specific value from the dictionary)
Then, there is the form attribute, which does not contain the query string, but which is included in part of another attribute that does include the query string which I will list momentarily. First, though, form is "A dictionary with all the form fields submitted with the request." I say that to say this: there is another dictionary attribute available in the flask request object called values. values is "A dictionary that combines the values in form and args." Retrieving that would look something like this:
from flask import request
#app.route('/'):
formFieldsAndQueryStringDict = request.values
(Again, use .get('<arg_name>') to get a specific item out of the dictionary)
Another option is query_string which is "The query string portion of the URL, as a raw binary value." Example of that:
from flask import request
#app.route('/'):
queryStringRaw = request.query_string
Then as an added bonus there is full_path which is "The path and query string portions of the URL." Por ejemplo:
from flask import request
#app.route('/'):
pathWithQueryString = request.full_path
And finally, url, "The complete URL requested by the client" (which includes the query string):
from flask import request
#app.route('/'):
pathWithQueryString = request.url
Happy hacking :)
I prefer
user = request.args['user'] if 'user' in request.args else 'guest'
over
user = request.args.get('user')
this way, you can check the url actually contains the query string first
The implementation below worked for me.
from flask import request
def getVerificationStatus():
try:
requestId=int(request.args.get('requestId'))
print(requestId)
status= verificationStepRepository.getVerificationStatus(requestId)
return tb.responsify(200, "success", status)
except Exception as e:
return errorHandler.dispatchInternalServerError(str(e))
Often we just want to map the whole query string into an appropriate python data structure and take it from there. The appropriate structure is a multi-dictionary because keywords can repeat, for example we need to handle A=123&A=456&B=789. A multi-dictionary is a list of 2-tuples where each 2-tuple contains the key as its first item and the list of values as its second, so the above goes to [('A',['123','456']),('B',['789'])]. All of this is achieved by
qstr = request.args.lists() # A generator for the multi-dict
qstr = list(qstr) # To get the actual multi-dict
If all you want is a dictionary where the first occurrence of a duplicate keyword is used you can just go
qstr = request.args.to_dict()
This can be done using request.args.get().
For example if your query string has a field date, it can be accessed using
date = request.args.get('date')
Don't forget to add "request" to list of imports from flask,
i.e.
from flask import request
If the request if GET and we passed some query parameters then,
fro`enter code here`m flask import request
#app.route('/')
#app.route('/data')
def data():
if request.method == 'GET':
# Get the parameters by key
arg1 = request.args.get('arg1')
arg2 = request.args.get('arg2')
# Generate the query string
query_string="?arg1={0}&arg2={1}".format(arg1, arg2)
return render_template("data.html", query_string=query_string)
This Code worked for me:
from flask import Flask, request
app = Flask(__name__)
#app.route('/')
def search():
query = request.args
for key,value in query.items():
print(key,value)
return "Hello World"
if __name__ == '__main__':
app.run(debug=True)

Categories