Flask文档学习(一)搭建登录界面

这篇博客介绍了如何在Ubuntu18上使用Python3和虚拟环境搭建Flask项目,并结合SQLite创建登录界面。首先,创建虚拟环境并安装Flask,然后设置项目目录和开发模式。接着,使用SQLite数据库并创建用户数据表。最后,编写auth.py处理登录逻辑,创建HTML模板和CSS样式,完成登录界面的搭建。
摘要由CSDN通过智能技术生成

环境准备

  1. Ubuntu18(一般Flask都是部署在linux的服务器)
  2. python3
  3. 为项目搭建只带有flask的虚拟环境

步骤

  1. 建立一个放项目的文件夹例如:myproject
  2. 创建python虚拟环境,python3 -m venv venv如果遇到提示要安装virtualenv就按提示安装即可。
  3. 注意在当前项目路径下激活虚拟环境. venv/bin/activate
  4. 在虚拟环境中pip安装Flask,这里可以换清华源安装快些pip install Flask-i https://pypi.tuna.tsinghua.edu.cn/simple
  5. 创建一个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)
    
    from . import auth
    app.register_blueprint(auth.bp)


    from . import blog
    app.register_blueprint(blog.bp)
    app.add_url_rule('/', endpoint='index')


    return app
  1. myproject文件夹目录下设置flask要启动的APP和设置为开发模式(即每次修改后不需重启服务直接刷新浏览器即可看到效果)
export FLASK_APP=flaskr
export FLASK_ENV=development
flask run
  1. 使用SQLite嵌入式数据库,优点无需连接数据库,缺点性能相对其他数据库较差(但作为小demo够用)。在flaskr目录下新建 db.py 写入以下内容
import sqlite3

import click
from flask import current_app, g
from flask.cli import with_appcontext

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

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 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
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值