【发布时间】:2021-11-11 05:22:33
【问题描述】:
我最近开始使用蓝图烧瓶。 我有一个 dicts => list[{'title':'ajsdhkd', 'author': 'askjdh qweqwqw'}, {'title':'ajsdhkd', 'author': 'askjdh qweqwqw'}] 的列表需要添加到sql。 我想用创建的包含这个字典的表来初始化我的数据库。这样我以后可以从蓝图烧瓶路线执行它。 但是我不明白怎么做。
在我创建的 db.py 中:
import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
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 query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
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('utf8'))
@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)
有一个 schema.sql 文件,其中: 如果存在书籍,则删除表;
CREATE TABLE books (
title varchar(50),
author varchar(100),
);
.....
【问题讨论】:
标签: python sqlite flask blueprint