示例项目结构
__init__.py
# __init__.py
from flask import Flask
from lovers.extensions import db
import os
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.root_path, 'date22.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
register_commands(app)
return app
def register_commands(app):
@app.cli.command()
def initdb():
db.create_all()
print('成功了')
extensions.py
# extensions.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
model.py
#models.py
from lovers.extensions import db
from datetime import datetime
class Exam(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, default=datetime.utcnow)
.flaskenv
# .flaskenv
FLASK_APP = lovers
FLASK_ENV = development
初始化数据库
终端输入
发现只有数据库没有表
解决方法
原因,没有导入模型
所以在__init__.py文件需要导入模型
# __init__.py
...
from lovers.models import Exam
...