AttributeError: 'scoped_session' object has no attribute 'session'
Question:
I am trying to insert new data to my database but my web application returns this error.
My codes are as follows:
models.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...
class Patient(db.Model):
__tablename__ = "patients"
id = db.Column(db.Integer, primary_key=True)
lname = db.Column(db.String, nullable=False)
fname = db.Column(db.String, nullable=False)
mname = db.Column(db.String, nullable=True)
address = db.Column(db.String, nullable=False)
birthdate = db.Column(db.Date, nullable=False)
date_modified = db.Column(db.DateTime, nullable=False)
modified_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
date_created = db.Column(db.DateTime, nullable=False)
created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
def __init__(self, fname, mname, lname):
self.fname = fname
self.mname = mname
self.lname = lname
application.py
import os
from flask import *
from flask_session import Session
from sqlalchemy import *
from sqlalchemy.orm import scoped_session, sessionmaker
from models import *
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
# Check for environment variable
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
app.secret_key = '######'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
...
@app.route("/submitpatient", methods=["POST"])
def submitpatient():
fname = request.form.get("fname")
mname = request.form.get("mname")
lname = request.form.get("lname")
patient = Patient(fname=fname, mname=mname, lname=lname)
db.session.add(patient)
db.session.commit()
return redirect(url_for('index'))
I’m new to python and I have been trying to find the error in my code for hours but I can’t seem to find anything that would help me.
Answers:
I guess the problem that u missed to create a constructor “Session” after using it,
The code will be:
# create a configured "Session" class
Session = scoped_session(sessionmaker(bind=engine))
@app.route("/submitpatient", methods=["POST"])
def submitpatient():
fname = request.form.get("fname")
mname = request.form.get("mname")
lname = request.form.get("lname")
patient = Patient(fname=fname, mname=mname, lname=lname)
#create a Session
session = Session()
session.add(patient)
session.commit()
return redirect(url_for('index'))
for more information, see this
What if you just add
and commit
as follows,
db.add(patient)
db.commit()
Use Session object with SQLAlchemy’s declarative way
I know this answer is not exactly related to the questioner’s scenario but a similar issue can arise if you are using flask-security
‘s user model with sqlalchemy
in a declarative way.
In this case, your user_datastore
should be as below:
user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role)
not SQLAlchemyUserDatastore
For more explanation:
database.py
import importlib
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine("sqlite:///crm.sqlite3")
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def create_db(all_microservices_names = []):
_ = importlib.import_module("database.models.all_models")
Base.metadata.create_all(bind=engine)
all_models.py
import sqlalchemy as sa
from database.database import Base
from flask_security import RoleMixin, UserMixin
class User(Base, UserMixin):
id = sa.Column(sa.Integer(), primary_key=True)
public_id = sa.Column(sa.String(length=255), unique=True, nullable=False)
username = sa.Column(sa.String(20), unique=True, nullable=False)
#...
datastore.py
from flask_security import SQLAlchemySessionUserDatastore
from database.database import db_session
from database.models.user_models import User, Role
user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role)
app.py will contain the initialization of these elements including login_manager and attach it to the Flask app.
I am trying to insert new data to my database but my web application returns this error.
My codes are as follows:
models.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...
class Patient(db.Model):
__tablename__ = "patients"
id = db.Column(db.Integer, primary_key=True)
lname = db.Column(db.String, nullable=False)
fname = db.Column(db.String, nullable=False)
mname = db.Column(db.String, nullable=True)
address = db.Column(db.String, nullable=False)
birthdate = db.Column(db.Date, nullable=False)
date_modified = db.Column(db.DateTime, nullable=False)
modified_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
date_created = db.Column(db.DateTime, nullable=False)
created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
def __init__(self, fname, mname, lname):
self.fname = fname
self.mname = mname
self.lname = lname
application.py
import os
from flask import *
from flask_session import Session
from sqlalchemy import *
from sqlalchemy.orm import scoped_session, sessionmaker
from models import *
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
# Check for environment variable
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
app.secret_key = '######'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
...
@app.route("/submitpatient", methods=["POST"])
def submitpatient():
fname = request.form.get("fname")
mname = request.form.get("mname")
lname = request.form.get("lname")
patient = Patient(fname=fname, mname=mname, lname=lname)
db.session.add(patient)
db.session.commit()
return redirect(url_for('index'))
I’m new to python and I have been trying to find the error in my code for hours but I can’t seem to find anything that would help me.
I guess the problem that u missed to create a constructor “Session” after using it,
The code will be:
# create a configured "Session" class
Session = scoped_session(sessionmaker(bind=engine))
@app.route("/submitpatient", methods=["POST"])
def submitpatient():
fname = request.form.get("fname")
mname = request.form.get("mname")
lname = request.form.get("lname")
patient = Patient(fname=fname, mname=mname, lname=lname)
#create a Session
session = Session()
session.add(patient)
session.commit()
return redirect(url_for('index'))
for more information, see this
What if you just add
and commit
as follows,
db.add(patient)
db.commit()
Use Session object with SQLAlchemy’s declarative way
I know this answer is not exactly related to the questioner’s scenario but a similar issue can arise if you are using flask-security
‘s user model with sqlalchemy
in a declarative way.
In this case, your user_datastore
should be as below:
user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role)
not SQLAlchemyUserDatastore
For more explanation:
database.py
import importlib
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine("sqlite:///crm.sqlite3")
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def create_db(all_microservices_names = []):
_ = importlib.import_module("database.models.all_models")
Base.metadata.create_all(bind=engine)
all_models.py
import sqlalchemy as sa
from database.database import Base
from flask_security import RoleMixin, UserMixin
class User(Base, UserMixin):
id = sa.Column(sa.Integer(), primary_key=True)
public_id = sa.Column(sa.String(length=255), unique=True, nullable=False)
username = sa.Column(sa.String(20), unique=True, nullable=False)
#...
datastore.py
from flask_security import SQLAlchemySessionUserDatastore
from database.database import db_session
from database.models.user_models import User, Role
user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role)
app.py will contain the initialization of these elements including login_manager and attach it to the Flask app.