Key Error in Flask Sessions - python

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)

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)

session variables in flask keep changing

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)

Flask error setting session attribute: BadPayload

I'm having trouble setting a flask session attribute. I cannot set session['var_name'] to anythign without getting a BadPayload: Could not load the payload because an exception occurred on unserializing the data error. The below code throws an error. but if I comment out session['a'] = 1 and it runs fine. Seem's like its an itsdangerous error. Should I be setting me secret_key to something better than gobblygook? Is that related?
from flask import Flask, render_template, session
app = Flask(__name__)
app.secret_key = 'sdfnbsifhosdfsdsfsddfsdfiewl'
#app.route('/', methods=['GET','POST'])
def index():
session['a'] = 1
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7777, debug=True)

Flask Pluggable Views Error: "Not Implemented Error"

I am learning how to use Pluggable Views in Flask, since it seems that everyone uses them always for their advantages. I have the following file which returns an "Not Implemented Error". I am assuming that is because I am not implementing the dispatch_request. However, according to Flask's documentation, when using MethodView: "...if you implement a method called get() it means you will response to ’GET’ requests and the dispatch_request() implementation will automatically forward your request to that." Meaning, I do not require dispatch_request.
from flask import Flask, render_template, request, redirect, url_for, flash
from flask.views import View, MethodView
import os
SECRET_KEY = 'some_secret_key'
DEBUG = TRUE
app = Flask(__name__)
app.config.from_object(__name__)
class Main(View):
def dispatch_request(self):
return "Hello World!"
class Template(View):
def get(self):
return render_template('index.html')
def post(self):
result = eval(request.form['expression'])
flash(result)
return self.get()
app.add_url_rule('/', view_func=Main.as_view('main'))
app.add_url_rule('/template', view_func=Template.as_view('template'), methods=['GET', 'POST'])
if __name__ == "__main__":
app.run()
Oops.. silly Python beginner's mistake by me.
I was subclassing flask.views.View instead of flask.views.MethodView. flask.views.View requires dispatch_request, and does not automatically forward HTTP requests to dispatch_request as MethdoView does, hence the error.

Flask, Blueprint, current_app

I am trying to add a function in the Jinja environment from a blueprint (a function that I will use into a template).
Main.py
app = Flask(__name__)
app.register_blueprint(heysyni)
MyBluePrint.py
heysyni = Blueprint('heysyni', __name__)
#heysyni.route('/heysyni'):
return render_template('heysyni.html', heysini=res_heysini)
Now in MyBluePrint.py, I would like to add something like :
def role_function():
return 'admin'
app.jinja_env.globals.update(role_function=role_function)
I will then be able to use this function in my template. I cannot figure out how I can access the application since
app = current_app._get_current_object()
returns the error:
working outside of request context
How can I implement such a pattern ?
The message error was actually pretty clear :
working outside of request context
In my blueprint, I was trying to get my application outside the 'request' function :
heysyni = Blueprint('heysyni', __name__)
app = current_app._get_current_object()
print(app)
#heysyni.route('/heysyni/')
def aheysyni():
return 'hello'
I simply had to move the current_app statement into the function. Finally it works that way :
Main.py
from flask import Flask
from Ablueprint import heysyni
app = Flask(__name__)
app.register_blueprint(heysyni)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)
Ablueprint.py
from flask import Blueprint, current_app
heysyni = Blueprint('heysyni', __name__)
#heysyni.route('/heysyni/')
def aheysyni():
# Got my app here
app = current_app._get_current_object()
return 'hello'

Categories

Resources