0

How can I print something like this:

{
    username = admin
    email = admin@localhost
    id=42
}

With only using a method = ['POST'] and without using render_template?

PS: I already made it run with ['GET']

Here's my code:

from flask import Flask, jsonify, request

app = Flask(__name__)

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

def index():
    if request.method == 'POST':
        return jsonify(username="admin",
                       email="admin@localhost",
                       id="42")
    else:
        if request.method == 'POST':
        return jsonify(username="admin",
                       email="admin@localhost",
                       id="42")

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

And what I get is a 405 Method error.

Louie Cubero
  • 329
  • 1
  • 3
  • 11

2 Answers2

0

Hey make sure your trailing stashes in your html are correct.

you may refer to : Flask - POST Error 405 Method Not Allowed and flask documentation : http://flask.pocoo.org/docs/0.10/quickstart/

this

<form action="/" method="post">

and this is same same but different

<form action="" method="post">

Accessing it without a trailing slash will cause Flask to redirect to the canonical URL with the trailing slash.

Given your error 405, I am suspecting that this is your problem. GET is fine, because you will just be redirected.

Community
  • 1
  • 1
biobirdman
  • 4,060
  • 1
  • 17
  • 15
0

Try returning the form (as biobirdman said) on a GET request. Not sure why you need the request.method == 'POST' conditional statement. The parameter methods=['POST'] in the route should suffice.

Try this:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    return jsonify(username="admin", email="admin@localhost", id="42")

@app.route('/', methods=['GET'])
def form():
    return "<form action='/' method='POST'>" \
            "<input type='submit'>" \
            "</form>"

if __name__ == "__main__":
    app.run()
Chigurh
  • 131
  • 1
  • 3