先描述一下我的代码结构,如下图:
其中 model/init.py 文件的内容为
from flask_sqlalchemy import SQLAlchemy
from views.index import app
import sys
import os
WIN = sys.platform.startswith("win")
if WIN: # 如果是 Windows 系统,使用三个斜线
prefix = "sqlite://"
else: # 否则使用四个斜线
prefix = "sqlite:///"
# 数据库文件的绝对路径
app.config["SQLALCHEMY_DATABASE_URI"] = prefix + os.path.join(os.path.dirname(os.path.abspath(__name__)), "data.db")
# 初始化扩展,传入程序实例 app
db = SQLAlchemy(app)
if __name__ == '__main__':
print(prefix + os.path.join(os.path.dirname(os.path.abspath(__name__)), "data.db"))
我在 flask shell 执行的内容及结果是
$: flask shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21)
[Clang 6.0 (clang-600.0.57)] on darwin
App: views.index [development]
Instance: /这里我省略了自己电脑的文件路径/fflaskStu/instance
>>> from model import db
>>> db.create_all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1039, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1031, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 962, in get_engine
return connector.get_engine()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 555, in get_engine
options = self.get_options(sa_url, echo)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 570, in get_options
self._sa.apply_driver_hacks(self._app, sa_url, options)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/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
请问有知道怎么解决的么,非常感谢!!!