flask如何使用sqlite3进行数据库操作,首先我们创建一个数据表的建表语句在schema.sql文件中
DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS post;
CREATE TABLE user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
);
CREATE TABLE post (
id INTEGER PRIMARY KEY AUTOINCREMENT,
author_id INTEGER NOT NULL,
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
title TEXT NOT NULL,
body TEXT NOT NULL,
FOREIGN KEY (author_id) REFERENCES user (id)
);
然后我们创建一个db.py文件用来生成数据库文件
import sqlite3
import click
from flask import current_app,g,Flask
from flask.cli import with_appcontext
app=Flask(__name__)
def get_db():
if 'db' not in g:
g.db=sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory=sqlite3.Row
return g.db
def close_db(e=None):
db=g.pop('db',None)
if db is not None:
db.close()
def init_db():
db=get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf-8'))
@click.command('init-db')
@with_appcontext
def init_db_command():
init_db()
click.echo('Initialized the database.')
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
然后在__inti__.py文件中加入一行代码
def create_app():
app = ...
from . import db
db.init_app(app)
return app
接下来我们在终端输入命令flask inti-db生成sqlite3文件在instance目录下 完整的__init__.py文件
import os
from flask import Flask
def create_app(test_config=None):
app=Flask(__name__,instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path,'flaskr.sqlite'),
)
if test_config is None:
app.config.from_pyfile('config.py',silent=True)
else:
app.config.from_mapping(test_config)
try:
os.makedirs(app.instance_path)
except OSError:
pass
from . import db
db.init_app(app)
from . import auth
app.register_blueprint(auth.bp)
@app.route('/hello')
def hello():
return 'Hello,World!'
return app
|