简体   繁体   中英

Handling POST request Flask

I am trying to pass data from my website's login page as a POST request to Flask. However, Flask fails to obtain any data. Here's a code snippet of my test.py file that runs the Flask app. I realised that the code isn't entering the method itself.Can anyone help me understand where am I going wrong?

@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

Here's the snippet of my login form:

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>

I simulated your problem on my machine it worked !
I made the following changes.

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

for html file

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

However you should use WTF forms you will have a clean and reusable code with that.

an example 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.')

then your html becomes

{% 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 %}

The line containing the opening tag for your form seems like the suspect here:

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

While I'm not sure if the floating form attribute is causing any issues, I'm certain that it isn't doing anything useful so you should get rid of that.

Also, by specifying action="." , you are saying that the submission of the form should be directed to the same route that you got the form from. In your Flask code, you wrote

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

so in your form tag, you should specify action="/" for the submission to go to the my_form_post method in Flask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM