如何使用 Flask 将信息加载到数据库中?

How do you load information into a database using flask?

尝试通过制作网络应用程序自学烧瓶。我在将用户的输入发布到我的数据库时遇到问题,当我加载页面然后尝试通过我的表单提交信息时,我收到此 405 错误:

"GET / HTTP/1.1" 200 -,

"POST / HTTP/1.1" 405 -

任何见解将不胜感激,谢谢。

这是 python 片段:

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)

html 模板:

<!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>

你们很亲密

@app.route('/',methods=['GET','POST'])
def index():
    print request.method
...

该方法应该在路由中定义,而不是在视图函数中。

文档link:

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

文档示例:

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