Flask使用SQLite数据库

SQLite是一个小型的轻量数据库,特别适合个人学习使用。因为SQLite不需要额外的数据库服务器,同时它也是内嵌在Python中的。缺点就是如果有大量的写请求过来,它是串行处理的,速度很慢。

连接数据库

新建flaskr/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()

g是flask给每个请求创建的独立的对象,用来存储全局数据。通过g实现了同一个请求多次调用get_db时,不会创建新连接而是会复用已建立的连接。

get_db会在flask应用创建后,处理数据库连接时被调用。

sqlite3.connect()用来建立数据库连接,它指定了配置文件的Key DATABASE

sqlite3.Row让数据库以字典的形式返回行,这样就能通过列名进行取值。

close_db关闭数据库连接,它先检查g.db有没有设置,如果设置了就关闭db。

创建表

新建flaskr/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)
);

flaskr/db.py文件中添加以下代码:

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.')

open_resource()打开刚才创建的数据库脚本文件。

@click.command()定义了命令行命令init-db

注册到应用

close_dbinit_db_command函数Flask不会自动触发,需要手动注册到应用上。

编辑flaskr/db.py文件:

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)

app.teardown_appcontext指定响应结束后清理时的函数。

app.cli.add_command定义了可以被flask命令使用的命令。

再把init_app手动添加到创建应用函数中,编辑flaskr/__init__.py文件:

def create_app():
    app = ...
    # existing code omitted

    from . import db
    db.init_app(app)

    return app

执行命令

至此,准备工作已就绪,打开命令行执行:

$ flask init-db
Initialized the database.

在项目目录下,就会生成一个flaskr.sqlite,这就是SQLite数据库。

参考资料:

https://flask.palletsprojects.com/en/2.0.x/tutorial/database/

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以帮您完成这个任务。以下是一个简单的Flask应用程序,其中包含用户登录和注册界面,并使用SQLite3数据库进行身份验证。 首先,您需要安装FlaskSQLite3。请使用以下命令: ``` pip install flask pip install sqlite3 ``` 接下来,创建一个名为“app.py”的文件,并添加以下代码: ```python from flask import Flask, render_template, request, redirect, url_for, flash import sqlite3 app = Flask(__name__) app.secret_key = 'some_secret' # 定义数据库名称 db_name = 'user.db' # 创建用户数据表 def create_users_table(): conn = sqlite3.connect(db_name) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT NULL)''') conn.commit() conn.close() # 注册新用户 def register_user(username, password): conn = sqlite3.connect(db_name) c = conn.cursor() c.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password)) conn.commit() conn.close() # 检查用户是否存在 def check_user(username): conn = sqlite3.connect(db_name) c = conn.cursor() c.execute("SELECT * FROM users WHERE username=?", (username,)) result = c.fetchone() conn.close() return result # 首页 @app.route('/') def index(): return render_template('index.html') # 注册 @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] confirm_password = request.form['confirm_password'] if check_user(username): flash('该用户名已经存在,请尝试另一个用户名') elif password != confirm_password: flash('两次输入的密码不一致,请重新输入') else: register_user(username, password) flash('注册成功,请登录') return redirect(url_for('login')) return render_template('register.html') # 登录 @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] user = check_user(username) if user and user[2] == password: flash('登录成功') return redirect(url_for('index')) else: flash('用户名或密码不正确,请重新输入') return render_template('login.html') if __name__ == '__main__': create_users_table() app.run(debug=True) ``` 这个应用程序包含三个页面:主页、注册和登录。在主页上,用户可以选择注册或登录。在注册页面上,用户可以输入用户名和密码进行注册。在登录页面上,用户可以输入用户名和密码进行登录。 此应用程序使用SQLite3数据库来存储用户信息。在“create_users_table”函数中,我们定义了一个名为“users”的表,其中包含三个列:id、username和password。在“register_user”函数中,我们将新用户的用户名和密码插入到“users”表中。在“check_user”函数中,我们检查给定的用户名是否存在于“users”表中,并返回该用户的详细信息(如果存在)。 在“register”路由中,我们首先检查给定的用户名是否已经存在于“users”表中。如果存在,则向用户显示错误消息。否则,我们检查两次输入的密码是否相同。如果不是,则向用户显示错误消息。如果一切正常,则将新用户的用户名和密码插入到“users”表中,并向用户显示成功消息。 在“login”路由中,我们首先检查给定的用户名是否存在于“users”表中,并检查密码是否正确。如果一切正常,则向用户显示成功消息,并重定向到主页。否则,向用户显示错误消息。 最后,请在应用程序文件夹中创建一个名为“templates”的文件夹,并在其中创建三个名为“index.html”、“register.html”和“login.html”的HTML文件。这些文件包含应用程序的用户界面。以下是一个基本的“index.html”文件: ```html <!doctype html> <html> <head> <title>用户登录和注册</title> </head> <body> <h1>用户登录和注册</h1> {% with messages = get_flashed_messages() %} {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} <p><a href="{{ url_for('register') }}">注册</a></p> <p><a href="{{ url_for('login') }}">登录</a></p> </body> </html> ``` 请注意,我们使用Flask模板功能来将动态内容(例如错误消息)插入到HTML文件中。 现在,您可以启动应用程序并在Web浏览器中查看它。要启动应用程序,请在命令行中运行以下命令: ``` python app.py ``` 访问 [http://localhost:5000/](http://localhost:5000/) 即可查看应用程序的主页。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值