Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask routing problems

I'm practicing writing a rest api in flask, and I'd like to save a username as a session variable, and have it accessible in each route. I'd like to just interact with this program through the command line via curl.

from flask import Flask, Response, session, request, url_for, redirect
import json

app = Flask(__name__)
app.secret_key = 'blabla'

@app.route('/')
def index():
  print 'Inside index route'
  if 'username' in session:
    username = session['username']
    print 'Logged in as {}'.format(username)
    return Response(response='Logged In\n', status=200, mimetype='text')
  else:
    print 'Not logged in'
    return Response(response='Not Logged In\n', status=200, mimetype='text')

@app.route('/login', methods=['GET', 'POST'])
def login():
  print 'Inside login route'
  if request.method == 'POST':
    session['username'] = json.loads(request.data)['username']
    print session['username']
    return redirect(url_for('index'))

@app.route('/logout')
def logout():
  session.pop('username', None)
  return redirect(url_for('index'))

if __name__ == '__main__':
  app.run(debug=True)

When I curl the site with:

curl -X POST -H 'Content-Type: application/json' http://127.0.0.1:5000/login -d '{"username": "mdito"}'

I get the output:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="/">/</a>.  If not click the link.

On the server side I am seeing:

Inside login route
mdito

If I'm redirecting to the index url, why does 'Inside index route' not appear on the server side? And why does 'Logged In' not get returned to the user?

like image 219
mcdito13 Avatar asked Nov 24 '17 00:11

mcdito13


1 Answers

Because flask does 302 redirect from /url to /url/. To avoid redirects add / at the end:

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

Docs (see Unique URLs / Redirection Behavior part). That's it.

like image 149
Artsiom Praneuski Avatar answered Sep 28 '22 10:09

Artsiom Praneuski