Access request parameters from flask application deployed in openshift - python

I have a python web app that carry's out calculations on data you send to it via POST / GET parameters.
The app works perfectly on my machine, but when deployed to openshift, it fails to access the parameters with an error no 32 : Broken pipe
I then used this quickstart repo to just focus on server code and not app code.
Got to differentiate between a POST and GET request and ended there
here's the relevant python code :
#app.route('/', methods=['GET','POST'])
def index():
result = ""
if request.method == "GET":
name = request.form['name'] if "name" in request.form else ""
result = "We received a GET request and the value for <name> is :%s" % name
elif request.method == "POST":
result = "We received a POST request"
else :
result = "We don't know what type of request we have received"
return result
So i just wanna know how i can access the parameters.

Don't use Flask's development server in production. Use a proper WSGI server that can handle concurrent requests, like Gunicorn. For now try turning on the server's threaded mode and see if it works.
app.run(host="x.x.x.x", port=1234, threaded=True)

You can get form data from the POST request via:
name = request.form.get("name")
Refactor:
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
name = request.form.get("name")
result = "We received a POST request and the value for <name> is - {0}".format(name)
else:
result = "This is a GET request"
return result
Refer to the official Flask documentation to learn more about the Request object.

Related

How do i send data to a flask app and then have the flask app display it [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 10 months ago.
I want to send some POST data to a flask webpage then have it display that data but when I try to send the data {"hi": "hi"} it gives me these errors:
code 400, message Bad request syntax ('hi=hi')
"None / HTTP/0.9" HTTPStatus.BAD_REQUEST -
my code is this:
from flask import Flask, request
app = Flask("__name__")
#app.route("/", methods=['GET', 'POST'])
def hi():
return "hi"
if request.method == "POST":
data = request.values
return f"<p>{data}</p>"
the flask app:
and the post data sending program:
import requests
requests.post('http://127.0.0.1:5000', data={ "req": "hi" })
am I just not understanding POST requests right or am I doing something really wrong?
please see this answer regarding how to access the request's data.
the requests.post you are using as http client is sending the data as form-encoded, so we could use Flasks' request.form to access the data. Also your function needs some restructuring, else it will always return "hi", we can make it:
from flask import Flask, request
app = Flask("__name__")
#app.route("/", methods=['GET', 'POST'])
def hi():
if request.method == "GET":
return "hi"
if request.method == "POST":
# data = request.values
# data will be = req if your POST request has req field, else will be = field: req was not provided
data = request.form.get("req", "field: req was not provided")
return f"<p>{data}</p>"
if you dont know the fields the POST request will contain, you can use this loop to get the fields and their values:
#app.route("/", methods=['GET', 'POST'])
def hi():
if request.method == "GET":
return "hi"
if request.method == "POST":
# data = request.values
for field in request.form:
print(field, request.form.get(field))
return "hi"

How to convert POST request to GET request in flask?

I created a web application in flask that has a form and whatever text the user enters appears on the bottom along with all the previously entered messages.
I was trying to load test it using JMeter, but I'm not able to send POST request using multiple threads in JMeter so I wanted to convert the post request to GET request so that I am able to perform load tests on my application.
Currently my route looks something like this
#app.route('/blog', methods=['GET', 'POST'])
#app.route('/', methods=['GET', 'POST'])
def blog():
print
form = PostForm()
if form.validate_on_submit():
post = Post(body=form.post.data)
db.session.add(post)
db.session.commit()
return redirect(url_for('blog'))
posts = Post.query.all()
return render_template('index.html', title='Blogger', form=form,
posts=posts)
What can I do to send the parameters through the URL.
I am very new to web development and I followed the mega tutorial in flask. Is there a workaround this?
add #app.route("/<string:param>",methods['GET']) and give it default values def blog(param = "") and use it for your get method
#app.route("/<string:param>",methods['GET'])
#app.route("/blog/<string:param>",methods['GET'])
#app.route('/blog', methods=['GET', 'POST'])
#app.route('/', methods=['GET', 'POST'])
def blog(param = ""):
print
if request.method == "POST":
##your post code here
elif request.method == "GET":
## new code using 'param' here

render_template in Python-Flask is not working

I am actually creating an app with Flask and I am encountering issues regarding my routing.
My situation is simple: The user enters a token to authenticate himself. Once he clicks on authenticate, an angular HTTP request uses POST to send his token to a Python server. There, if he is granted access, the home page is displayed using render_template; otherwise the login keeps still.
However, when the user authenticates himself, I see on my command line that the POST was successful, the authentication was a success but the page just stuck on login and does not redirect to home page as if the second render_template does not work. Please Help!
#app.route('/')
def index():
if not session.get('logged_in'):
return render_template('auth.html') # this is ok.
else:
return render_template('index.html') # this does not work
#app.route('/login', methods=['POST','GET'])
def login():
tok = request.form['token']
if (check_token(tok) == "pass"): # check_token is a function I've implemented
# to check if token is ok=pass, ko=fail
session['logged_in'] = True
else:
flash("wrong token")
return index()
Your login handler shouldn't call index directly. It should return a redirect to the index.
return redirect('/')
or better:
return redirect(url_for('index'))
I was thinking of the following.
#app.route('/')
def index():
if not session.get('logged_in'):
return return redirect(url_for('login'))
else:
return render_template('index.html')
#app.route('/login', methods=['POST','GET'])
def login():
if request.method = "POST":
tok = request.form['token']
if (check_token(tok) == "pass"):
session['logged_in'] = True
return redirect(url_for('index'))
else:
flash("wrong token")
return render_template("login.html")
I have used Angular JS in my app to send requests to my flask server and i realised that my client side angular JS had difficulties in rendering page as it was just expecting a response.
I first tried to do.. document.write('response.data') and it did display my home page but my scripts attached on my html page stopped working.
Second try, I tried to reload the page after receiving the response in my client and it works well. I don't know if it's the best way to do but it does work.

strange with use request.args?

submit an Ip to post1.py
#main.route('/post1',methods=['GET','POST'])
#login_required
def post1():
Ip=request.form['Ip']
print Ip
return redirect(url_for('.post',Ip=Ip))
then redirect to post.py
#main.route('/post', methods=['GET', 'POST'])
#login_required
def post():
#Ip=request.args['Ip']
form = RepairForm(request.form)
print request.form
if request.method == "POST":
repair = Repair(Ip=form.ip.data,Series=form.series.data,Hostname=form.hostname.data,
ManagerIp=form.managerip.data,Comp=form.comp.data,
Model=form.model.data,Location=form.location.data,Box=form.box.data,
Important=form.important.data,Faultype=form.faultype.data,
Subject=form.subject.data,Body=form.body.data,Classify=form.classify.data,
Status=form.status.data,auth_id=current_user._get_current_object().id,
Owner=current_user._get_current_object().username,)
db.session.add(repair)
db.session.commit()
flash('报修成功')
return redirect(url_for('.index'))
form.ip.data=1
print form.ip.data
form.hostname.data=1
print form.hostname.data
print request.form
form.managerip.data=1
form.comp.data=1
form.model.data=1
form.location.data=1
form.box.data=1
form.important.data=1
form.faultype.data=1
form.classify.data=1
form.status.data=1
return render_template('post.html',form=form)
all test ok,but when I uncomment Ip=request.args['Ip'],then test returns 'The browser (or proxy) sent a request that this server could not understand',
This post points out the Form sending error:
Flask raises an HTTP error when it fails to find a key in the args and form dictionaries. What Flask assumes by default is that if you are asking for a particular key and it's not there then something got left out of the request and the entire request is invalid.
You can't use request.args['Ip']because Flask use a custom dictionary implementation from werkzeug called MultiDict. It has his own get method.
use request.args.get('Ip') solved this error,but do not know the reason because request.args['Ip'] still can get the data.

Flask test response to post request incorrectly returns 400

I'm working on unit tests for my Flask app. I have a URL that can be accessed only by an authorized (logged in) user. As a setup I create a test app, a temp database and a test user. I then authorize the test user.
I tested GET request on for this URL and it correctly returns 200 response. However, if I send any test POST or DELETE requests, instead of 200 they return 400 and 401 respectively.
I spell checked all the arguments and I'm pretty sure I'm sending correct test arguments together with the requests, but I still can't figure out what's the problem.
Is there anything different in testing POST and DELETE requests than in GET requests that I don't understand?
Here are my example GET and POST request tests and a corresponding implementation:
Tests:
def test_successful_get(self):
self.login('valid_user', 'valid_password')
response = self.app.get('/home', data=dict(parameter='parameter'))
assert_that(response.status_code, equal_to(200))
def test_successful_post(self):
self.login('valid_user', 'valid_password')
response = self.app.post('/home', data=dict(parameter='parameter'))
assert_that(response.status_code, equal_to(200))
Implementation:
#app.route('/home', methods=['GET', 'POST', 'DELETE'])
#login_required
def home():
if request.method == 'POST':
insert_param_in_db(request.form['parameter'])
return redirect(url_for('index'))
elif request.method == 'DELETE':
remove_param_from_db(request.form['parameter'])
return redirect(url_for('index'))
return redirect(url_for('index'))

Categories

Resources