KRISHNAKANT MISHRA
KRISHNAKANT MISHRA

Reputation: 43

Trouble with Flask and POST/GET

So I have the following app.py file through which I am trying to process a post request which will essentially read firstname, lastname, username and password and then store it in mongodb but that is for later. As of now, I am having trouble receiving the post/get request.

Even the small snippet that I am trying to run gives me a bad request error when I try to use postman to submit data to localhost:5000/register.

Any help will be appreciated.

from flask import *
#from pymongo import MongoClient
#import json
app = Flask(__name__)

# main interface
@app.route("/")
def main():
    return render_template('index.html')

# Register Interface
@app.route('/register/', methods = ['GET'])
def register():
    #collection = db['userdb']
    firstname = request.form['firstname']
    lastname = request.form['lastname']
    username = request.form['username']
    password = request.form['password']
    #postData = { 'firstname': firstname, 'lastname': lastname,'username':username,'password':password}
    #json = json.dumps(postData)
    #try:
        #status = db.userdb.insert_one(postData).insert_id
    #except:
        #status = 'This user is already registerd'
    return 'This data works'

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

Upvotes: 1

Views: 545

Answers (2)

T. Arboreus
T. Arboreus

Reputation: 1059

you do need to add the "POST' method to the route decorator, but you need one more step. Use an if statement to make the view ignore the request.form assignments:

from flask import *
#from pymongo import MongoClient
#import json
app = Flask(__name__)

# main interface
@app.route("/")
def main():
    return 'go to <a href="/register/">register</a>'

# Register Interface
@app.route('/register/', methods = ['GET','POST'])
def register():
    #collection = db['userdb']
    if request.method == 'POST':
        firstname = request.form['firstname']
        lastname = request.form['lastname']
        username = request.form['username']
        password = request.form['password']
        #postData = { 'firstname': firstname, 'lastname': lastname,'username':username,'password':password}


    return 'This data works'

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

This is a common pattern in views that use both GET and POST. Also notice that I've added debug=True as an argument to app.run. This will make debugging your code a lot easier.

Upvotes: 4

Cameron Mochrie
Cameron Mochrie

Reputation: 139

@app.route('/register/', methods = ['GET'])

The above decorator means the handler will only be mapped to GET requests.

@app.route('/register/', methods = ['GET', 'POST'])

Try that and you should be good to go.

Upvotes: 3

Related Questions