flask_sqlalchemy无法创建sqlite数据库问题
在学习flask框架时,遇到了flask_sqlalchemy小插件,在使用时一直无法创建本地的数据库文件。其实并非没有创建数据库,而是创建在了内存中,这是sqlite特有的一个特性。
app.py
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
# 导入用于配置的类
from config import Config
app = Flask(__name__)
bootstrap = Bootstrap(app)
# 读取配置文件
app.config.from_object(Config)
db = SQLAlchemy(app)
@app.route('/')
def index():
title = 'Flask Web App'
paragraphs = [
'section 1',
'section 2',
'section 3'
]
return render_template('index.html', title="Home", data=paragraphs)
if __name__ == '__main__':
app.run(debug=True, host="127.0.0.1", port=3000)
config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
# Database configuration
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'app.db')
# SQLALCHEMY_DATABASE_URI = 'sqlite:gitRe/flaskLearn/test.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
问题就出在配置文件中,我一开始应该是把配置文件中字母写错了,所以在读取的时候没有读到,导致创建了默认的内存数据库
从flask_sqlalchemy/init.py文件中的init_app方法可以看出,若没有读取到SQLALCHEMY_DATABASE_URI与SQLALCHEMY_BINDS参数,那么SQLALCHEMY_DATABASE_URI的值就会被设置为sqlite:///:memory:,即建立内存数据库。
def init_app(self, app):
"""This callback can be used to initialize an application for the
use with this database setup. Never use a database in the context
of an application not initialized that way or connections will
leak.
"""
if (
'SQLALCHEMY_DATABASE_URI' not in app.config and
'SQLALCHEMY_BINDS' not in app.config
):
warnings.warn(
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
'Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".'
)
app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:')
app.config.setdefault('SQLALCHEMY_BINDS', None)
models.py
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
password = db.Column(db.String(20), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
# def __init__(self, username, password, email):
# self.username = username
# self.password = password
# self.email = email
def __repr__(self):
return '<User %r>' % self.username
解决方案
在python console 中重新启动一下,就能释放掉内存数据库,然后就可以重新创建了