Handling POST method for two app routes to same function [duplicate] - python

This question already has answers here:
How do I get the different parts of a Flask request's url?
(4 answers)
Are global variables thread-safe in Flask? How do I share data between requests?
(4 answers)
Closed 4 years ago.
How can i get something like this to work?
#app.route('/client_progress')
#app.route('/client_update', methods=['POST', 'GET'])
def func_1():
if (//app.route == client_progress)
if request.method == 'POST':
return 'hello world'
elif (//app.route == client_update)
if request.method == 'POST':
return 'Good World'
I would like to have two app routes to same function and be able to respond back to appropriate route.
is this possible? if yes, please share the example.

Related

How can I use a variable of flask in jinja while writing href [duplicate]

This question already has answers here:
Get a variable from the URL in a Flask route
(2 answers)
Closed 1 year ago.
#html code
click here
flask code
#app.route('/dashboard/<name>', methods=['GET', 'POST'])
def text():
user = "abc"
return render_template('dashboard.html', name=user)
on clicking 'click here' i want to route to dashboard/abc
Here you go:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/dashboard/')
#app.route('/dashboard/<name>', methods=['GET', 'POST'])
def text():
user = "abc"
return render_template('dashboard.html', name=user)
#app.route('/dashboard/abs')
def something():
return 'redirected'
just add #app.route('/dashboard/')
Note: I've also included an additional #app.route('/dashboard/abs') decorator just to display you're redirected.

how to solve "TypeError: new_reply() missing 1 required positional argument: 'post_id'" [duplicate]

This question already has answers here:
Get a variable from the URL in a Flask route
(2 answers)
Closed 2 years ago.
I am trying to map the specific post id to the reply I am making but when I ran my application it gave me the error
TypeError: new_reply() missing 1 required positional argument: 'post_id'
when I passed post_id as a static integer 1 and went to the specific post and replied it worked as intended but obviously this is not the solution I'm looking for, any help is appreciated
#app.route("/post/reply", methods=['GET', 'POST'])
#login_required
def new_reply(post_id):
form = ReplyForm()
if form.validate_on_submit():
reply = Reply(title=form.title.data, content=form.content.data, author=current_user, post_id=post_id)
db.session.add(reply)
db.session.commit()
flash('reply posted', 'success')
return redirect(url_for('home'))
return render_template('Reply.html', title='New Reply', form=form, legend='New Reply')
You will need to add that parameter to your route.
Your current route is:
#app.route("/post/reply", methods=['GET', 'POST'])
which provides no post_id to your method.
Try
#app.route("/post/<int:post_id>/reply", methods=['GET', 'POST'])
which will also convert it into an integer for use by your method.

How to call a function with the content received from a flask api's get request as a parameter in flask [duplicate]

This question already has answers here:
Are global variables thread-safe in Flask? How do I share data between requests?
(4 answers)
Closed 3 years ago.
I have built an api which accepts any filepath passed to it in the url and displays it in the webpage. Example: http://12.389.798.220:5000/C:/MYES/ALL.pdf
The webpage will display
C:/MYES/ALL.pdf
Now I want to take this output and pass it to the function 'convert' in my code which needs a filepath to process a file and return an output.
Code till now:
app = Flask(__name__)
api = Api(app)
class ectdtext(Resource):
def get(self, result):
return {'data': ectd.convert(result)}
categories=convert('/FILES/5cf9-5b67-45ef8-9DD69c-ae571431c665.pdf')
#app.route('/')
def returnResult():
return categories
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def get_dir(path):
return path
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)
So, the line
categories=convert('/FILES/5cf9-5b67-45ef8-9DD69c-ae571431c665.pdf)
was previously hardcoded. Now I want to pass the path entered in the webpage to be passed as a parameter to this convert function for each new request. How can I solve this?
Just call the needed function within the respective route:
...
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def get_dir(path):
categories = convert(path)
return categories

BadRequestKeyError [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 4 years ago.
Multiple questions have been asked with a similar error on SO. I have tried all of the solutions but still keep getting a beautiful error:
werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'username'
Below is my html form:
<form action='/login' method = "GET">
<label>Name: </label>
<input name="username" type="text">
<input type="submit" name='submit' value='submit'>
</form>
Here is the function that deals with the form data:
#app.route('/login', methods = ['GET'])
def login():
if request.method == "GET":
un = request.form['username']
return un
I have learned Bottle and transitioning towards Flask.
So far, I have tried the following:
1) GET to POST
2) request.form.get('username', None)
3) Add POST reason to the function route without any rhyme or reason.
Can somebody help me out?
You need to change the method (GET to POST) in the html file and add the method in the decorator #app.route too. Do not forget that in this case a return (GET) is required to render the html file.
#app.route("/login", methods = ['GET', 'POST'])
def login():
if request.method == "POST":
# import pdb; pdb.set_trace()
un = request.form.get('username', None)
return un
return render_template('form.html')
Tip: Learn about pdb to debug your programs more easily.
https://realpython.com/python-debugging-pdb/
https://docs.python.org/3/library/pdb.html
no need to change your form action method. but when you use GET method for sending form data your data is transmitted as URL variables and you need to read data this way:
if flask.request.method == 'GET':
username = flask.request.args.get('username')
and if you change the method to POST, read content as below:
if flask.request.method == 'POST':
username = flask.request.values.get('username')

How do I make a POST request to flask?

I'm new to Flask and I'm trying to find a way to invoke the elif statement in the code below, without having to manually type in the url when I run my app. In other words, I'd like to be able to provide a url in one of my templates that will make a POST request for question(title). Can anyone give me insight?
#application.route('/question/<title>', methods=['GET', 'POST'])
def question(title):
if request.method == 'GET':
question = r.get(title+':question')
return render_template('AnswerQuestion.html',
question = question)
elif request.method == 'POST':
submittedAnswer = request.form['submittedAnswer'];
answer=r.get(title+':answer')
if submittedAnswer == answer:
return render_template('Correct.html');
else:
return render_template('Incorrect.html',
answer = answer,
submittedAnswer = submittedAnswer);
Looks like in thePOST request, you are getting the contents of a form. You can try to create a form whose action="/question/some_title" and method="post". So on submit this will be handled on theelif part of your flask code.
Or you can try sending am ajax request through JavaScript or jQuery, with relevant data, method and URL.

Categories

Resources