处理POST请求Flask

时间:2016-03-13 20:37:49

标签: python post web flask

我正在尝试将数据从我网站的登录页面作为POST请求传递给Flask。但是,Flask无法获取任何数据。这是我运行Flask应用程序的test.py文件的代码片段。我意识到代码本身并没有进入方法。任何人都可以帮我理解我哪里出错了?

@app.route('/', methods=['POST'])
def my_form_post():
    text = request.form['text']
    processed_text = text.upper()
    print "Processed text is..."
    print processed_text
    return processed_text

这是我的登录表单的片段:

div class="modal fade" id="direct-login-form" tabindex="-1" role="dialog" aria-labelledby="direct-login-form-label" aria-hidden="true">
      <div class="vertical-alignment-helper">
          <div class="modal-dialog vertical-align-center">
              <div class="modal-content">
                  <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>

                      </button>
                       <h4 class="modal-title" id="direct-login-form-label">Login</h4>

                  </div>
                  <div class="modal-body">
                    <div class="wrap-login-form wrap-reviews">
                      <form id="direct-login" form action="." method="POST" class="form-horizontal">
                        <div class="form-group">
                          <label class="col-sm-3" for="direct_username">Username</label>
                          <div class="col-sm-9">
                            <input type="text" name="text" class="form-control" id="direct_username" placeholder="Username">
                          </div>
                        </div>
                        <div class="form-group">
                          <label class="col-sm-3" for="direct_password">Password</label>
                          <div class="col-sm-9">
                            <input type="password" class="form-control" id="direct_password" placeholder="Password">
                          </div>
                        </div>
                        <div class="wrap-slidecheck clearfix">
                          <div class="col-sm-3"></div>
                          <div class="col-sm-9">
                            <div class="slidecheck">
                              <input type="checkbox" id="direct_remember_me" name="check" />
                              <label for="direct_remember_me"></label>
                            </div>
                            <span>Remember me</span>
                          </div>
                        </div>
                        <div class="form-group">
                          <label class="col-sm-3"></label>
                          <div class="col-sm-9">
                            <button type="submit" name="my-form" class="btn btn-default" value="Send">Submit</button>
                          </div>
                        </div>
                        <div class="form-group">
                          <label class="col-sm-3"></label>
                          <div class="col-sm-9">
                            <p class="help-block"><a href="../../vxeg/indexc2b6.html?action=lostpassword">Lost your password?</a><span> or </span><a href="../../membership-account/index.html">Register an Account</a></p>
                          </div>
                        </div>
                        <input type="hidden" id="direct_security" name="direct_security" value="f0abedaf74" /><input type="hidden" name="_wp_http_referer" value="/directory-category/coffee-lounge/" />                      </form>
                    </div>
                  </div>
              </div>
          </div>
      </div>
  </div>

2 个答案:

答案 0 :(得分:3)

我在我的机器上模拟了你的问题! 我做了以下更改。

for view

@app.route("/")
def hello():
    return render_template('register.html')


@app.route("/register", methods=['POST'])
def register():
    text = request.form['text']
    passwd = request.form['passwd']
    processed_text = text.upper()
    print "Processed text is...", processed_text, passwd
    #do your further processing like saving to Database...
    return render_template('register.html') #send to the profile/dashboard page

用于html文件

<form id="direct-login" form action="{{ url_for('register') }}" method="POST" class="form-horizontal">


 <input type="password" class="form-control" id="direct_password" name='passwd' placeholder="Password">

但是你应该使用WTF forms,你将拥有一个干净且可重复使用的代码。

示例forms.py

class RegistrationForm(Form):
    email = StringField('Email', validators=[Required(), Email(), Length(1, 64)])
    username = StringField('Username', validators=[Required(), Length(1, 64), Regexp('^[A-Za-z][A-za-z0-9._]*$', 0,'Username must have only letters, dots, digitsm or underscores')])
    password = PasswordField('Password', validators=[Required(), EqualTo('password2', message='Password must match.')])
    password2 = PasswordField('Confirm Password', validators=[Required()])
    submit = SubmitField('Register')


    '''
    Custome validator for email validate_*
    '''
    def validate_email(self, field):
    if(User.query.filter_by(email= field.data)).first():
        raise ValidationError('Email already registered.')

    '''
    Custome validator for email validate_*
    '''
    def validate_username(self, field):
    if(User.query.filter_by(username = field.data)).first():
        raise ValidationError('Username already registered.')

然后你的html变成了

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

{% block title %} - Register{% endblock %}
{% block page_content %}
    <div class="page-header">
    <h1>Register</h1>
    </div>
    <div class="col-md-5">
        {{ wtf.quick_form(form) }}
    </div>
{% endblock %}

答案 1 :(得分:0)

包含表单开头标记的行似乎是嫌疑人:

<form id="direct-login" form action="." method="POST" class="form-horizontal">

虽然我不确定浮动form属性是否会导致任何问题,但我确信它没有做任何有用的事情,所以你应该摆脱它。

此外,通过指定action=".",您说表单的提交应该指向您从表单获取的相同路由。在你的Flask代码中,你写了

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

因此,在form标记中,您应指定提交的action="/"以转到Flask中的my_form_post方法。

相关问题