【问题标题】:How do you load information into a database using flask?如何使用烧瓶将信息加载到数据库中?
【发布时间】:2016-05-12 01:18:09
【问题描述】:

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

"GET / HTTP/1.1" 200 -,

“POST/HTTP/1.1”405 -

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

这里是python sn-p:

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>

【问题讨论】:

  • 不要在此处手动增加id Vocab(id=len(instances) ...。删除条目时,此方法将失败!您的数据库可能会处理增量。尝试不使用该关键字:Vocab(word=request.form['new_word'])
  • @Wombatz 如果这是问题,它会引发异常而不是 405,对吗?我认为问题出在定义方法的位置(参见 Joran Beasleys 的回答)。不过,Nali 可能会在解决此问题后遇到 id 增量问题。不过很好。
  • @Aaron 是的,这只是一个旁注。当我评论时已经有一个正确的答案,所以我没有说清楚,我的评论不是解决方案。我的坏
  • @Wombatz 不不,我真的很感激,因为我一开始错过了它,我从你的评论中学到了一些东西。
  • @Aaron 非常感谢。以前不知道,但由于您的 cmets,我查找了自动增量。让生活更轻松。

标签: python html web flask http-status-code-405


【解决方案1】:

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

文档链接:

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()

【讨论】:

    【解决方案2】:

    你们很亲密

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

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 2020-02-29
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      相关资源
      最近更新 更多