I'm trying to flash a message then redirect to the home page. But the flash message never appears after being redirected to home page. However app.logger.debug(get_flashed_messages()) does catch the flash message before redirection.
app.secret_key = 'somesecret'
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/add',methods=["GET","POST"])
def add():
if request.method == "POST":
url = request.form['url']
flash("Stored bookmark " + url) # Never displays
store_bookmarks(url)
app.logger.debug(get_flashed_messages()) # Catches flash message
return redirect(url_for('index')) # Always redirects
return render_template('add.html')
https://github.com/mitsuhiko/flask/issues/1168 This is the only thing i could find while searching but my APPLICATION_ROOT is unmodified
Related
I'm currently having some trouble with my flask webapp, where I have written it as below, but when I try to run the flask app, I run into a Bad Request Error. (The browser (or proxy) sent a request that this server could not understand)
Essentially, I am trying to allow users to log in to an external website through the flask webapp
What is the cause of this error? Apologies if I am making a stupid mistake, I'm very new to flask.
from flask import Flask,render_template, request, redirect
import requests
from bs4 import BeautifulSoup as bs
app = Flask(__name__)
#app.route('/', methods = ["POST", "GET"])
def login():
username = request.form['username']
pin = request.form['password']
s = requests.Session()
r = s.get("https://www.example.com/User/Login")
soup = bs(r.text, 'html.parser')
loginToken = soup.findAll(attrs={"name" : "__RequestVerificationToken"})[0]['value']
#Create Login Payload
login_payload = {
"__RequestVerificationToken" : loginToken,
"UserName" : username,
"Password" : pin,
"returnUrl" : "https://example.com/user-action/?action=login&returnUrl=https://www.example.com/User/Information",
}
#Post Login Payload
r = s.post("https://www.example.com/Account/Login", data = login_payload)
if r.status_code == 200:
return render_template('home.html')
else:
return render_template('login.html')
return render_template('login.html')
#app.route('/home') #If login works, redirect to this page
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
app.run(debug = True)
In addition, if there are other resources that I could refer to with regards to allowing a user to log in to a external URL from the flask webapp as compared to the conventional tutorials that only show a user logging in to the flask webapp itself, do share it with me, thank you!
Your endpoint' s has two Http verbs ["POST", "GET"]. You should specify your methods as below.
#app.route('/', methods = ["POST", "GET"])
def login():
if request.method == "GET":
#something do stuff
return render_template("your_html_page")
if request.method == "POST":
#something do stuff
return your_response, 200
Edited Block
#app.route('/', methods = ["POST", "GET"])
def login():
if request.method == "GET":
return render_template('login.html')
if request.method == "POST":
#same logic here
if status_code == 200:
return redirect(url_for('home'))
return render_template('login.html')
I am actually creating an app with Flask and I am encountering issues regarding my routing.
My situation is simple: The user enters a token to authenticate himself. Once he clicks on authenticate, an angular HTTP request uses POST to send his token to a Python server. There, if he is granted access, the home page is displayed using render_template; otherwise the login keeps still.
However, when the user authenticates himself, I see on my command line that the POST was successful, the authentication was a success but the page just stuck on login and does not redirect to home page as if the second render_template does not work. Please Help!
#app.route('/')
def index():
if not session.get('logged_in'):
return render_template('auth.html') # this is ok.
else:
return render_template('index.html') # this does not work
#app.route('/login', methods=['POST','GET'])
def login():
tok = request.form['token']
if (check_token(tok) == "pass"): # check_token is a function I've implemented
# to check if token is ok=pass, ko=fail
session['logged_in'] = True
else:
flash("wrong token")
return index()
Your login handler shouldn't call index directly. It should return a redirect to the index.
return redirect('/')
or better:
return redirect(url_for('index'))
I was thinking of the following.
#app.route('/')
def index():
if not session.get('logged_in'):
return return redirect(url_for('login'))
else:
return render_template('index.html')
#app.route('/login', methods=['POST','GET'])
def login():
if request.method = "POST":
tok = request.form['token']
if (check_token(tok) == "pass"):
session['logged_in'] = True
return redirect(url_for('index'))
else:
flash("wrong token")
return render_template("login.html")
I have used Angular JS in my app to send requests to my flask server and i realised that my client side angular JS had difficulties in rendering page as it was just expecting a response.
I first tried to do.. document.write('response.data') and it did display my home page but my scripts attached on my html page stopped working.
Second try, I tried to reload the page after receiving the response in my client and it works well. I don't know if it's the best way to do but it does work.
I'm building a login with flask and flask-login, and the authentication works perfectly. When a user is authenticated, he should be automatically redirected to the home page (which is unavailable for a not-logged user). The issue is that flask.redirect function just returns me the html code of the home page instead of redirecting to that page. I see the html code in the response object inside the browser console. How can I solve?
Here it is the relevant code:
#app.route('/home')
#flask_login.login_required
def home():
return render_template('home.html')
#app.route('/login', methods=['GET', 'POST'])
def login():
if(request.method == 'GET'):
return render_template('login.html')
email = request.form['email']
passwd = request.form['passwd']
data = getUsersData()
for key in data:
if(email == data[key]['email'] and passwd == data[key]['pass']):
user = User()
user.id = email
flask_login.login_user(user, remember=True)
next = request.args.get('next')
if(next):
return redirect(next)
else:
return redirect(url_for('home'))
abort(401) # if inside the for, it can't find valid username and password
I would like that when the authentication succeeded, the browser redirects me to localhost:10000/home
EDIT:
The terminal log with both GET and POST request to /home
EDIT 2:
The response object
If I look at your screen copy, you have something like this:
"POST /login HTTP/1.1" 302 -
"POST /home HTTP/1.1" 200 -
note: you can have exit code 302 or 307, which is approximately the same: a redirection.
So, the redirection from /login to /home works. No error here.
You said:
The issue is that flask.redirect function just returns me the HTML code of the home page instead of redirecting to that page.
But this is exactly what you implement here:
#app.route('/home')
#flask_login.login_required
def home():
return render_template('home.html')
So, I think there is an ambiguity: what do you call "home page"? Is it the page of the /home route, or an "index.html" page which can be the page of the "/" route?
I have a Flask app that runs on https behind nginx. The app also uses flask-login to log users in.
I have set my app.secret_key and have 3 views:
#app.route('/')
def index():
return render_template('index.html')
#app.route('/login', methods=['GET', 'POST'])
def login():
form = Login()
if form.validate_on_submit():
# log the user in...
......
return redirect(request.args.get('next') or '/')
return render_template('login.html', form=form)
#login_required
#app.route('/logged_in')
def logged_in():
return render_template('logged_in.html')
The vast, vast majority of my users do not log in (and don't have a user account) and some are complaining that we are setting cookies on them. I can confirm this behavior in my browser (Firefox) when I delete the cookie, visit "https://www.example.com" and see that the cookie gets reset.
How do I change the behavior so that the cookie only gets reset if the user logs in?
I have an endpoint that does some logic and a flash()and then redirects to another endpoint, which adds another flash and displays both flashed messages. When I test the endpoint in my browser, I get both messages. However, when I do my unittest, the first flash doesn't show up.
#bp.route('/signup/', methods=['POST'])
def signup():
form = SignupForm(prefix='signup')
next_url = url_for('.home')
if form.validate_on_submit():
# do stuff like add to waiting list
person = persons.new()
form.populate_obj(person)
person = persons.save(person)
flash(Markup(u'Thanks for signing up!'), 'success')
return redirect(next_url)
#bp.route('/')
def home():
flash('This is home', 'info')
return render_template('home.html')
class PageTests(MTestCase):
def test_signup(self):
r = self.post('/signup/',
data={
'signup-email': 'test1#test.com',
})
person = persons.find(email='test1#test.com').first()
self.assertIsNotNone(person)
self.assertIn('Thanks for signing up', r.data)
I'm guessing that during the redirect the flash queue is lost, but I'm not entirely sure how or why.
Add follow_redirects=True argument because login page redirects.
r = self.post(
'/signup/',
data={
'signup-email': 'test1#test.com',
},
follow_redirects=True # <----
)
See Logging in and out - Testing Flask Application.