如何使用def __init __(self):在类中调用我的sqlite3数据库?

时间:2018-05-30 19:53:11

标签: python class sqlite init

我使用Flask并且我有一个python函数文件:db.py,但是,每次我调用其他python文件中的函数时,我必须调用get_db()来获取数据库而我必须导入该函数的文件。

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)

所以在另一个文件中,我必须导入文件(from myapp.db import get_db)并调用db = get_db()来获取数据库。

routes.py:

from myapp.db import get_db

@app.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']

        db = get_db()
        error = None

       <more code here>

        if db.execute(
        'SELECT id FROM user WHERE username = ?', (username,)
    ).fetchone() is not None:
        error = 'Username {} is already registered.'.format(username)

       <more code here>

        db.execute(
            'INSERT INTO user (username, password, email, signup_date) VALUES (?, ?, ?, ?)',
            (username, generate_password_hash(password), email, now_time)
        )
        db.commit()

       <more code here>

但我想知道是否有可能只是通过调用db.execute(),如果我导入它就会自然get_db()

我试图在db2.py中构建这样的类:

class DatabaseFunctions:
    import sqlite3
    import click
    def __init__(self, db):
        self.db = db 
        db = qlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )

    def get_db(self):
    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(self, e=None):
        db = g.pop('db', None)
        if db is not None:
            db.close()

    def init_db(self):
        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(self, app):
        app.teardown_appcontext(close_db)
        app.cli.add_command(init_db_command)

我还想将db2.py扩展为allfunctions.py文件,我告诉类是最佳做法。但是,我在自我和 init 方面很挣扎,即使只是阅读了一些内容,当你只有一个函数页面时,我也看不到课堂上的重点。

任何帮助将不胜感激。

0 个答案:

没有答案