简体   繁体   中英

Flask running request.method 'POST' by default instead of 'GET'

I am developing this Flask application where I press 'Login' button and I am redirected to "Dashboard".

Here's a simplified code for my default route which opens login page:

@app.route('/',  methods=['POST', 'GET'])
def home():
    if not session.get('logged_in'): 
        if request.method == 'GET':
            return render_template('login.html')
        elif request.method == 'POST':
            if # Username and Password are correct from the login form
                session['logged_in'] = True
                return dashboard()
            else:
                return render_template('login.html', message = "Wrong username or password")
    else:
        return render_template('dashboard.html')

The login.html has a form with form action="/" method="POST" which triggers the condition elif request.method == 'POST' in default route('/') above

Here's simplified code for route('/dashboard')

@app.route('/dashboard', methods=['POST', 'GET'])
def dashboard():
    if session.get('logged_in'):
        if request.method == 'GET':
            return "it was GET"
        elif request.method == 'POST':
            return "it was POST"
    else:
        return render_template('login.html')

Here comes the problem. The dashboard route runs POST method after login although (according to my concept) it should run GET method (as GET is default).

The output it gives is "it was POST". Please help. Thanks :)

You cannot just call return dashboard() . You must initiate redirect - tell the browser to load /dashboard :

return flask.redirect(flask.url_for('dashboard'))

You need to change the structure of your application. Instead of two routes that login the user, display the login page, display the dashboard, and provide user validation, consider four routes: 1) the home route, which displays HTML with an href to 2) the login route, which accepts the user input, redirects to 3) a validation route, which commits the user to the session, and 4), the dashboard route which the user is redirected from the validation route. Lastly, instead of user validation in the body of each route, create a decorator:

In home.html :

<html>
  <body>
     <h1>Welcome to the application</h1>
     {%if not_validated%}
       <a href='/login'>Login</a>
     {%endif%}
  </body>
</html>

In login.html :

<html>
   <body> 
     <form action='/user_login' method='POST'>
        <input type='email' name='userEmail' placeholder='enter email'>
        <input type='password' name='userPassword' placeholder='password'>
       <button type='submit'>Login</button>
     </form>
   </body>
 </html>

In dashboard.html :

<html>
  <body>
     <h1>Welcome, @{{username}}</h1>
  </body>
 </html>

Next, you need to create your routes. First, create a wrapper to validate the user:

import functools
import flask

app = flask.Flask(__name__)


def isloggedin(to_Login = False):
  def outer(f):
    @functools.wraps(f)
    def wrapper(*args):
      if (flask.session.get('loggedin', False) and not to_Login) or to_Login:
        return f(*args)
      return flask.redirect('/')
     return wrapper
  return outer


@app.route('/', methods=['GET'])
def home():
   flask.session['loggedin'] = False
   return flask.render_template('home.html', not_validated=flask.session.get('loggedin'))

@app.route('/login', methods=['GET'])
@isloggedin(to_Login = True)
def login():
   return flask.render_template('login.html')

@app.route('/user_login', methods=['POST'])
def login_user():
  email = flask.request.form['userEmail']
  password = flask.request.form['userPassword']
  flask.session['email'] = email
  flask.session['password'] = password
  flask.session['loggedin'] = True
  flask.redirect('/dashboard')

@app.route('/dashboard')
@isloggedin()
def dashboard():
  return flask.render_template('dashboard', username=flask.session['email'])

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