Flask错误初始化数据库

时间:2017-09-02 14:46:24

标签: python flask sqlite

我跟随Flask tutorial试图制作自己的东西。我尝试初始化数据库时,在step 5中收到错误。

当我在终端中输入flask initdb时,这是我得到的错误: seei5.py 第24行,在init_db中 db.cursor()。executescript(f.read()) sqlite3.OperationalError:near" drop":语法错误

我正在使用python 3.6

这是我的文件结构:

/seei5
    /seei5
        __init__.py
        /static
        /templates
        seei5.py
        schema.sql
    setup.py
    MANIFEST.in

MANIFEST.in

graft seei5/templates
graft seei5/static
include seei5/schema.sql

schema.sql文件

drop table if exists books;
create table books (
    book_id integer,
    title text,
    PRIMARY KEY (book_id))


drop table if exists chapters;
create table chapters (
    chapter_id integer,
    chapter text,
    book_id integer,
    PRIMARY KEY (chapter_id),
    FOREIGN KEY (book_id) REFERENCES books (book_id))


drop table if exists concepts;
create table concepts (
    concepts_id integer,
    concept text,
    definition text,
    chapter_id integer,
    PRIMARY KEY (concepts_id),
    FOREIGN KEY (chapter_id) REFERENCES chapters (chapter_id))

seei5.py

import os
import sqlite3
from flask import *

app = Flask(__name__)
app.config.from_object(__name__)

app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'seei5.db'),
    SECRET_KEY='development key',
    USERNAME='admin',
    PASSWORD='default'
))
app.config.from_envvar('SEEI5_SETTINGS', silent=True)

def connect_db():
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row 
    return rv

def init_db():
    db = get_db()
    with app.open_resource('schema.sql', mode='r') as f:
        db.cursor().executescript(f.read())
    db.commit()

@app.cli.command('initdb')
def initdb_command():
    init_db()
    print("Initialized the database.")

def get_db():
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

@app.teardown_appcontext
def close_db(error):
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

1 个答案:

答案 0 :(得分:1)

您可以修复schema.sql

吗?

<强> schema.sql文件

drop table if exists books;
create table books (
    book_id integer,
    title text,
    PRIMARY KEY (book_id));


drop table if exists chapters;
create table chapters (
    chapter_id integer,
    chapter text,
    book_id integer,
    PRIMARY KEY (chapter_id),
    FOREIGN KEY (book_id) REFERENCES books (book_id));


drop table if exists concepts;
create table concepts (
    concepts_id integer,
    concept text,
    definition text,
    chapter_id integer,
    PRIMARY KEY (concepts_id),
    FOREIGN KEY (chapter_id) REFERENCES chapters (chapter_id));

您遗失了;