I've spent too much time on this problem, and I think i'm just doing something wrong, and there's a better way to do this.
I am creating a website with a react frontend and flask backend, with sqlite database. My issue is that when I am using session.get() it returns None in one function but not another.
In this function, the session.get() returns the correct user id and therefore the function is able to add the data to the database correctly. Even when I sign in as a different user, and the user id changes.
@app.route('/addlist', methods=['GET','POST'])
def addlist():
if request.method == 'POST':
user_id = session.get("user_id")
list_name = request.form['ListName']
color = request.form['color']
new_list = ListOfLists(user_id = user_id,name = list_name,color=color)
db.session.add(new_list)
db.session.commit()
return redirect('http://localhost:3000/userPage')
but when I try to get the lists in the frontend, session.get('user_id') returns None, and so I can not get the user's lists.
@app.route('/getlists', methods=['GET', 'POST'])
def getlists():
user_id = session.get('user_id')
print("USER ID: {}".format(user_id))
lists = ListOfLists.query.filter_by(user_id=1).all()
return jsonify(lists)
print output: USER ID: None
the function itself definitely works because when I changed .filter_by(user_id=user_id)
to .filter_by(user_id=1)
where the user id in the database is 1, it actually sent the correct lists I have in the database to the frontend.
here is the app configuration, register and login endpoints, and the javascript function that gets the lists if that's of any interest:
from flask import Flask, request, redirect, session, jsonify
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
#flask app initialization
app = Flask(__name__)
app.config["SECRET_KEY"] = "changeme"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
app.config["SESSION_TYPE"] = "sqlalchemy"
app.config['SESSION_SQLALCHEMY'] = db
Session(app)
CORS(app)
@app.route('/register', methods = ['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['email']
password = request.form['password']
new_user = User(username=username, password=password) #user table constructor
db.session.add(new_user)
db.session.commit()
return redirect('http://localhost:3000/mainpage')
@app.route('/login', methods=['GET', 'POST'])
def Login():
if request.method == 'POST':
username = request.form['email']
password = request.form['password']
user = User.query.filter_by(username = username).first()
if user and user.password == password:
#save user to session
session['user_id'] = user.id
return redirect('http://localhost:3000/userPage')
import React, { useState, useEffect } from 'react';
export default function GetLists() {
const [lists, setLists] = useState('');
useEffect(() => {
fetch('http://localhost:5000/getlists')
.then(response => response.json())
.then(data => console.log(data))
},[]);
//return currently doesn't matter as I am only console.log-ing the data
return (...);
}
EDIT 1:
I noticed the print output is USER ID: 1
(the correct user id) when I manually go to http://localhost:5000/getlists
, but the output is None
when I use fetch() in javascript