suod allos
suod allos

Reputation: 13

'scoped_session' object has no attribute 'create_all' 'scoped_session' object has no attribute 'session'

So Im trying to create a website using flask and SQLAlchemy for database storage but I keep getting the two aforementioned errors

Here is my app.py code

import os

from flask import Flask, session,render_template, request
from flask_session import Session
from sqlalchemy import create_engine,Column, Integer, String
from sqlalchemy.orm import scoped_session, sessionmaker
from flask_sqlalchemy import SQLAlchemy
from models import *
app = Flask(__name__)

#app.config["DATABASE_URL"] = "sqlite:////plz_work.db"
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)


# Check for environment variable
#if not os.getenv("DATABASE_URL"):
#    raise RuntimeError("DATABASE_URL is not set")

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
class User:
    def __init__(self,username,password):
        self.username = username
        self.password = password


@app.route("/")
def index():
    return render_template('index.html')

@app.route("/registration.html")
def registration():
    return render_template('registration.html')

@app.route("/send", methods = ['GET','POST'])
def send():
    username = request.form['username']
    password = request.form['password']
    users = User(username,password)
    db.session.add(users)
    db.session.commit()
    return render_template('index.html')

if __name__ == "__main__":
    app.run(debug = True)
    db.create_all()

and here is my models.py file

import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class USERS(db.Model):
    __tablename__ = "Users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String)
    password = db.Column(db.String)
def __repr__(self):
        value = "USER:({}, {})".format(self.username, self.password)
        return value

I have been looking online for a soloution for so long but I can not find anything that works for me, and I have spent 2 days just on this problem, any help will be appreciated.

Thank You !!

Upvotes: 1

Views: 1407

Answers (1)

Berkin Anık
Berkin Anık

Reputation: 133

I guess you're overriding your database object within your models.py file. I suggest you to use sqlalchemy itself or flask-sqlalchemy not using them together. In my opinion things get complicated if you use them together.

You can achive that like this:

in your app.py

...your_other_imports...
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from .models import *

app = Flask(__name__)

...your_other_configs...

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
#NOW db carries your database session
#Do not define your database models in app.py remove User class from here.
#You should define your database model and also your query method (not necessary)
#if you're used to query with flask-sqlalchemy. Would make queries look similar to you
dbModel = declarative_base()
dbModel.query = db.query_property()

# define the function which will create your tables
def init_db():
    from .models import *
    dbModel.metadata.create_all(bind=engine)

...your_routes...

if __name__ == "__main__":
    app.run(debug = True)

    # now call the function to create your tables
    init_db()

in your models.py

from .app import dbModel
from sqlalchemy import Column, Integer, String

class User(dbModel):
    __tablename__ = "users"
    id = Columnn(Integer, primary_key=True)
    username = Column(String)
    password = Column(String)
    def __repr__(self):
        value = "USER:({}, {})".format(self.username, self.password)
        return value

Using query_property you can now query your data from your database and use your session to put data in your database like this:

User.query.filter_by(username=...).first()

newUser = User(
        username=...,
        password=...
    )
db.add(newUser)
db.commit()

Upvotes: 1

Related Questions