2017-09-02 50 views
-1

我正在關注Flask tutorial以嘗試創建自己的東西。當我嘗試初始化數據庫時,出現step 5錯誤。Flask error initalizing database

當I型flask initdb到終端,這是我的錯誤: seei5.py 線24,在init_db db.cursor()executescript(f.read()) sqlite3.OperationalError:近「滴「:語法錯誤

我使用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

你能解決您的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)); 

您還缺少;