尝试使用Flask获取会话数据时,方法不允许出错

时间:2015-02-10 02:24:00

标签: python flask flask-wtforms

我正在尝试构建一个测试应用,当我尝试导航到我的submitted_form页面时出现405错误。我的代码如下:

from flask import Flask, render_template, session, redirect, url_for, flash
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'

manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)


class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])
    submit = SubmitField('Submit')


@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500


@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get('name')
        if old_name is not None and old_name != form.name.data:
            flash('Looks like you have changed your name!')
        session['name'] = form.name.data
        print session['name']
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))

@app.route('/submitted_form/', methods=['GET, POST'])
def submitted_form():
    name = session.get('name')
    print name
    return render_template('submitted_form.html', name=name)

if __name__ == '__main__':
    manager.run()

我试图让它打印名称变量,我认为我将其存储为会话变量。

我的submitted_form.html模板如下:

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Flasky{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
</div>

{% endblock %}

1 个答案:

答案 0 :(得分:1)

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

应该是

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

否则它认为您的方法是'GET,POST',当POST进来时它会拒绝它,因此405 Method Not Allowed