session variables in flask keep changing - python

I have a very basic flask application that I have deployed to Heroku. I am trying to define a variable that I can change when a specific function is executed. For example, if I have a variable logged_in=True, I want to be able to change it to logged_in=False when the route #app.route('/logout') is executed. Here is the code:
import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True
Session(app)
# Redirect to /login route
#app.route('/')
def index():
return redirect(url_for("login"))
# Open main login page
#app.route("/login", methods=["POST","GET"])
def login():
return render_template("login.html")
# Verify login credentials
#app.route("/login_check",methods=["POST"])
def login_check():
return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")
#app.route("/main_page", methods=["POST"])
def main_page():
return render_template("main_page.html",name="Main page")
#app.route("/log_out", methods=["POST"])
def log_out():
app.config['logged_in']=False
return redirect(url_for("login"))
if __name__ == '__main__':
app.run(debug=True)
When I launch the app locally, the value of logged_in is set to False when logout is executed and does not change if login is triggered again. However, when I deploy the app to Heroku, the value of logged_in goes back True when login is triggered again (it's weird, the value changes sometimes, but not always).
How can I set the value of logged_in so that it does not change until I update it with a function? I tried to use session.config['logged_in']instead of app.config['logged_in'], but I had the same issue. Ideally, I want the value to be unique for each session.
Thank you

If you want to store one value to each session. No sql like redis is recommendation.
import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
import redis
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = redis.from_url('127.0.0.1:6379')
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True
Session(app)
# Redirect to /login route
#app.route('/')
def index():
return redirect(url_for("login"))
# Open main login page
#app.route("/login", methods=["POST","GET"])
def login():
return render_template("login.html")
# Verify login credentials
#app.route("/login_check",methods=["POST"])
def login_check():
return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")
#app.route("/main_page", methods=["POST"])
def main_page():
return render_template("main_page.html",name="Main page")
#app.route("/log_out", methods=["POST"])
def log_out():
session['key'] = 'False'
return redirect(url_for("login"))
if __name__ == '__main__':
app.run(debug=True)

Related

flask session - TypeError: 'type' object does not support item assignment

I'm trying to verify a user using flask session. The problem is that whenever I try to assign a value to my session, I get the error:
TypeError: 'type' object does not support item assignment
I have seen This stack overflow question and I have been using guides such as this one, however I have been unable to solve this problem.
Code:
from flask import Flask, redirect, url_for, request, render_template
from flask_session import Session
if request.method == 'POST':
username = request.form['un']
password = request.form['pw']
Session['name'] = request.form['un'] #this is where my error is occuring
else:
username = request.args.get('un')
password = request.args.get('pw')
Session["name"] = request.args.get('un')
I thought that my error could have been related to request.form['un'], so I changed the code to:
from flask import Flask, redirect, url_for, request, render_template
from flask_session import Session
if request.method == 'POST':
username = request.form['un']
password = request.form['pw']
Session['test'] = 'test' #still have an error here
else:
username = request.args.get('un')
password = request.args.get('pw')
Session["test"] = "test"
App is setup like this:
app = Flask(__name__, template_folder='template')
app.config["SESSION_PERMANENT"] = True
app.config["SESSION_TYPE"] = "filesystem"
app.secret_key = 'why would I tell you my secret key?'
app.config.from_object(__name__)
Session(app)
If this is something silly then I apologize for wasting your time :). I would appreciate any help.
Thanks
You are trying to assign the value to Session object.
If you check the example on the project's repo, you'll see it assigns the value to flask session, not flask_session's Session object:
from flask import Flask, session
from flask_session import Session
SESSION_TYPE = 'redis'
app = Flask(__name__)
app.config.from_object(__name__)
Session(app)
#app.route('/set/')
def set():
# check here
# it is flask's session, not flask_session's Session object
session['key'] = 'value'
return 'ok'
#app.route('/get/')
def get():
return session.get('key', 'not set')
if __name__ == "__main__":
app.run(debug=True)

Flask in showing 404 Error in Existing Routes

I am facing a very weird Issue, In my Flask App when index route (https://sitename.com/) is called everything is fine, but as i navigate to a route like https://sitename.com/about it shows 404 Error, even when About route is created in main.py . This App works all perfect in localhost:5000 but when I deployed it too a VPS It is showing that Error of showing 404 on every route
My main.py
from os import environ
from flask import Flask, redirect, render_template, request, url_for
import requests
import json
import datetime
def getUserData(route):
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr
with open("users.txt", "a") as f:
f.write(f"Page Visited: {route}\n")
f.write(f"User Agent: {request.headers.get('User-Agent')}\n")
f.write(f"Remote Addr: {ip}\n")
f.write(f"DateTime: {datetime.datetime.now()}\n")
f.write(f"\n\n\n")
app = Flask(__name__)
app.debug = True
# Website
#app.route('/')
def index():
getUserData("Index Page")
return render_template('index.html')
#app.route('/gallery')
def gallery():
getUserData("Gallery")
return render_template('pages/gallery.html')
#app.route('/faqs')
def faqs():
getUserData("FAQs")
return render_template('pages/faqs.html')
#app.route('/about')
def about():
getUserData("About")
return render_template('pages/about.html')
#app.route('/contact')
def contact():
getUserData("Contact")
return render_template('pages/contact.html')
# 404 Handling
#app.errorhandler(404)
def not_found(e):
getUserData("404 Page")
return render_template("pages/404.html")
if __name__ == '__main__':
app.run()

Why do I lose the session information on redirect in Flask app?

I was following one of cs50's lectures and writing the same code in vscode as in the lecture. For some reason it works in the course's ide but when it is in vscode on my PC the session forgets the input after redirection. Where is the problem and Is it possible to fix it?
from flask import Flask, render_template, request, redirect, session
from flask_session import Session
app = Flask(__name__)
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SECRET_KEY'] = 'randomkey'
Session(app)
#app.route('/')
def tasks():
if 'todos' not in session:
session['todos'] = []
return render_template('tasks.html', todos=session['todos'])
#app.route('/add', methods=["GET", "POST"])
def add():
if request.method == "GET":
return render_template('add.html')
else:
todo = request.form.get('task')
session['todos'].append(todo)
return redirect('/')

How can I make a non-permanent session in Flask

I'm learning flask and am trying to associate some randomly generated data with each session.
I use the approach from this answer to set session.permanent to False, but closing the browser, then reopening it at going back to the page still displays the same code.
MWE:
from flask import Flask, session
import numpy as np
app = Flask(__name__)
app.secret_key = "supersecretkey"
#app.before_request
def make_session_permanent():
session.permanent = False
#app.route('/')
def index():
if 'id' not in session:
random_id = "".join(np.random.choice(list("abcdefg123"), 16))
session["id"] = random_id
return session['id']
if __name__ == '__main__':
app.run(debug=True)
Update: Based on this answer someone recommended to use socketio to notice disconnects. This also makes no difference, i.e. closing the browser, reopening it, and going to 127.0.0.1:5000 gives the same number as before closing. An updated MWE using this is below:
from flask import Flask, session
from flask_socketio import SocketIO
import numpy as np
app = Flask(__name__)
app.secret_key = "supersecretkey"
#app.before_request
def make_session_permanent():
session.permanent = False
#app.route('/')
def index():
if 'id' not in session:
random_id = "".join(np.random.choice(list("abcdefg123"), 16))
session["id"] = random_id
return session['id']
socketio = SocketIO(app)
#socketio.on('disconnect')
def disconnect_user():
session.pop('id', None)
if __name__ == '__main__':
app.run(debug=True)
# Instantiate a new web application called `app`,
# with `__name__` representing the current file
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False

Key Error in Flask Sessions

So I have been using sessions to pass data from one decorator to another. But now every time I make a new session variable, I get a KeyError from page to page. Meaning, I had a session error from my third to fourth page; but I had the same issue adding a new session variable from my second to third page even though I have four other session variables that give me no error.
My code is similar to the one #laila posted below:
from flask import Flask, render_template
from flask import request, session, url_for,abort,redirect
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
#app.route('/'):
def first():
session['this_one']='hello'
render('template.html')
#app.route('/second')
def second():
it=session['this_one']
render('other_page.html')
if __name__ == '__main__':
app.run(debug=True)
it seems like the code has some syntax error.Please try the code below, it should be ok:
from flask import Flask, render_template
from flask import request, session, url_for, abort, redirect
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
#app.route('/')
def first():
session['this_one'] = 'hello'
return render_template('template.html')
#app.route('/second')
def second():
it = session.get('this_one', 'not found')
return render_template('other_page.html')
if __name__ == '__main__':
app.run(debug=True)

Categories

Resources