Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow POST method with Flask?

Tags:

python

flask

I'm doing a web Flask app with "sign up" and "log in" functions. I'd like to use a POST method for the "sign up" function, like this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "Index"

@app.route("/signup/<username>,<password>" , methods = ['POST'])
def signup(username, password):

    return "Hello %s ! Your pw is %s" % (username,password)


if __name__== "__main__":
    app.run(debug=True)

But when I ran it, I received this error : "Method not allowed. The method is not allowed for the requested URL."

How can I do? Thanks in advance.

like image 608
Frank Avatar asked May 21 '16 12:05

Frank


People also ask

How do you send a POST request in Flask?

post() method is used to generate a POST request. This method has can contain parameters of URL, params, headers and basic authentication. URL is the location for sending the request. Params are the list of parameters for the request.

How do you display Python output on a Flask html page?

Create a simple HTML page to display text. create a route ”/” and return home. html from the function. Then run your api.py file and click on the link that it provides after running.

How do you transfer data to a Flask?

Flask sends form data to template Flask to send form data to the template we have seen that http method can be specified in the URL rule. Form data received by the trigger function can be collected in the form of a dictionary object and forwarded to the template to render it on the corresponding web page.


1 Answers

You could use something like this perhaps.

from flask import Flask, request, render_template, url_for, redirect

...

@app.route("/signup/<username>,<password>", methods = ['GET', 'POST'])
def signup(username, password):
    if request.method == 'POST':
        # Enter your function POST behavior here
        return redirect(url_for('mainmenu'))    # I'm just making this up
    else:
        return "Hello %s ! Your pw is %s" % (username,password)
        # Or you could try using render_template, which is really handy
        # return render_template('signupcomplete.html')

You'd have to flesh it out with the various things you need it to do, but that basic structure should be what you need. I've used it myself in some projects.

like image 115
coralvanda Avatar answered Nov 15 '22 03:11

coralvanda