初学Python定义数据库出现的问题

Python操作数据库出现的问题

  • 首先创建文件夹
    • 创建__init__.py文件
    • 创建db.py文件
    • 创建schema.sql
    • 打开终端进入项目并运行
    • 问题所在

注:前提使用 Flask 框架

首先创建文件夹

文件夹名为 flaskr

创建__init__.py文件

文件内容:

import os

from flask import Flask


def create_app(test_config=None):
    # create and configure the app
    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:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    from . import db
    db.init_app(app)

    return app

创建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 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():
    """Clear the existing data and create new tables."""
    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

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)
);

打开终端进入项目并运行

$ cd xxx (你的项目地址)
$ export FLASK_APP=flaskr
$ export FLASK_ENV=development (配置环境)
$ flask init-db

当你运行上面最后一句时终端显示

Usage: flask [OPTIONS] COMMAND [ARGS]…
Error: No such command “init-db”.

这时非常纳闷,我找了半天问题所在原来

问题所在

如看到上面的报错请检查你的文件目录
返回 flaskr 当前项目的文件上级文件
执行 flask init-db 这个命令

好啦,现在不会在报错了

$ flask run

你可能感兴趣的:(python)