-1

Trying to teach myself flask by making a web app. I'm having trouble posting inputs from the user to my dataBase and when I load the page and then try to submit info through my form I get this 405 error:

"GET / HTTP/1.1" 200 -,

"POST / HTTP/1.1" 405 -

Any insight would be greatly appreciated, Thanks.

Here is the python snippet:

session = DBSession()

app = Flask(__name__)

@app.route('/')
def index(methods=['GET','POST']):
    print request.method
    if request.method == 'POST':
        instances = session.query(Vocab)
        newItem = Vocab(id=len(instances), word=request.form['new_word'])
        session.add(newItem)
        session.commit()
    instances = session.query(Vocab)
    return render_template('vocab_template.html', instances = instances)

The html template:

<!DOCTYPE html>
<html>
 <head> 
  <title>Vocab</title>
 </head>

 <body>
  <div>
   <h1>Words!</h1>
   <ul id='Words'>
    {% for i in instances %}
     <li>
     {{i.word}}     
     </li>
    {% endfor %}
   </ul>
   <form action="/" method="post">
    <input type="text" name='new_word'>
    <input type="submit" value="Add" name='submit'>
   </form>
  </div>
 </body>

</html>
Nali
  • 1
  • 1
  • 1
    Do not increment the `id` manually here `Vocab(id=len(instances) ...`. When entries are deleted this method will fail! Your database will probably handle the increment. Try it without that keyword: `Vocab(word=request.form['new_word'])`. – Wombatz Feb 03 '16 at 01:37
  • @Wombatz If this were the issue it would raise an exception rather then a 405, right? I think the problem is where the methods have been defined (see Joran Beasleys answer). Though, Nali will probably then experience issues with the id increment after resolving this. Good catch though. – Dandy Feb 03 '16 at 01:53
  • 1
    @Aaron Yes, that was only a side note. There was already a correct answer when I commented so I didn't make it clear, that my comment was not a solution. My bad – Wombatz Feb 03 '16 at 02:02
  • 1
    @Wombatz No no, genuinely appreciated on my part because I missed it at first, and I learnt something from your comment. – Dandy Feb 03 '16 at 02:04
  • @Aaron Thanks a lot. Didn't know about it before but I looked up autoincrementing because of your comments. Makes life much easier. – Nali Feb 03 '16 at 17:02

2 Answers2

1

you were very close

@app.route('/',methods=['GET','POST'])
def index():
    print request.method
...
Joran Beasley
  • 93,863
  • 11
  • 131
  • 160
0

The method should define in route, not in view function.

doc link:

http://flask.pocoo.org/docs/0.10/quickstart/#http-methods

doc example:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        do_the_login()
    else:
        show_the_login_form()
Tony
  • 889
  • 2
  • 12
  • 24