首页 > 解决方案 > Flask SQLAlchemy db.create_all(app = app) can't set attribute

问题描述

Flask SQLAlchemy db.create_all(app = app) can't set attribute. The database.db file is not being created.Every time I try to create it shows that it cant set the attributes.I have used the same technique in another app but at that time it worked.Please just help me to get rid of this error. I am new to flask .

Here is my init.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager

# creating the object for database
db = SQLAlchemy()
DB_NAME = "database.db"


# for creating the app
def create_app():
    # initializing the app
    app = Flask(__name__)
    app.config['SECRET_KEY'] = "Any secret key"
    # initializing the data base
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    # for debugging sql
    # app.config['SQLALCHEMY_ECHO'] = True
    db.init_app(app)

    # now for registering the blueprints
    from .views import views
    from .auth import auth

    app.register_blueprint(views , url_prefix='/')
    app.register_blueprint(auth , url_prefix='/')

    # for creating database
    # from .models import User , Room , Participant , Message
    from .models import User,Note
    create_database(app)
    
    return app


def create_database(app):
    # if the database does not exist then we will create it
    if not path.exists('website/'+DB_NAME):
        db.create_all(app = app)
        print('Database created')

The create_database() def is not working

My models.py

from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func





# The User will inherit database model and UserMixin . The UserMixin is for authentication
# purpose
class User(db.Model , UserMixin):
    id = db.Column(db.Integer , primary_key = True)
    email = db.Column(db.String(150) , unique = True)
    password = db.Column(db.String(150))
    firstname = db.Column(db.String(150))
    lastname = db.Column(db.String(150))
    # a sudo column in Note
    notes = db.relationship('Note')

    # def __repr__(self):
    #     print(f"<Post {self.firstname}>")


class Note(db.Model):
    id = db.Column(db.Integer , primary_key = True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), default = func.now())
    user_id = db.Column(db.Integer , db.ForeignKey('user.id')) 

The main.py

from website import create_app

app = create_app()


if __name__ == '__main__':
    # This is a debugging server
    app.run(debug = True)

Here is the pic of the app structure: app structure

Here's the log: In the log it says that attribute cant be set. I have also tried to build the database manually but it doesn't work

(venv) naheed@naheed-s15-x530un:~/Desktop/flask-chat-app-v2$ python main.py 
/home/naheed/Desktop/flask-chat-app-v2/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py:833: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  warnings.warn(FSADeprecationWarning(
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    app = create_app()
  File "/home/naheed/Desktop/flask-chat-app-v2/website/__init__.py", line 32, in create_app
    create_database(app)
  File "/home/naheed/Desktop/flask-chat-app-v2/website/__init__.py", line 40, in create_database
    db.create_all(app = app)
  File "/home/naheed/Desktop/flask-chat-app-v2/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 1039, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "/home/naheed/Desktop/flask-chat-app-v2/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 1031, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
  File "/home/naheed/Desktop/flask-chat-app-v2/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 962, in get_engine
    return connector.get_engine()
  File "/home/naheed/Desktop/flask-chat-app-v2/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 555, in get_engine
    options = self.get_options(sa_url, echo)
  File "/home/naheed/Desktop/flask-chat-app-v2/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 570, in get_options
    self._sa.apply_driver_hacks(self._app, sa_url, options)
  File "/home/naheed/Desktop/flask-chat-app-v2/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 914, in apply_driver_hacks
    sa_url.database = os.path.join(app.root_path, sa_url.database)
AttributeError: can't set attribute

标签: pythondatabaseflaskflask-sqlalchemy

解决方案


add the following import:

from sqlalchemy import create_engine

then initialize it inside your your create_app() function:

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'Any secret key'
    # app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    engine = create_engine('sqlite:///{DB_NAME}')
    db.init_app(app)

sqlalchemy 1.4 documentation


推荐阅读