python - 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
解决方案
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)
推荐阅读
- laravel - 存储路径上的 Laravel 验证
- c - 移位和按位和运算符在查找像素颜色中的意义/功能是什么?
- json - 存储 TMDB API 数据
- android - ActivityManager::getProcessMemoryInfo 和 dumpsys meminfo 的区别
- dataset - 如何从黑白蒙版生成 COCO 数据集
- python - 如何使用 anaconda 3.6 在 jupyter notebook 中获取 librosa.display 和 matplotlib
- reactjs - react-route-dom 不会发出警报或 console.log
- angular - 当我单击子组件中的表单按钮时,如何关闭位于父组件中的 mat-expansion-panel。角
- c - 即使子进程已死,waitpid 也会挂起
- next.js - 为什么我在运行 NextJS 应用程序时得到“无法获取 /”