• 测开之路一百三十五:实现登录身份验证功能


    新建表,插入用户信息

    create table UserInfo(
    UserName TEXT,
    Emali TEXT,
    Password
    );

    insert into UserInfo values ('Admin', 'Admin@email.com', '123456');
    insert into UserInfo values ('Jerry', 'Jerry@email.com', '654321');

    select * from UserInfo;

    login.html

    看一下效果

    登录逻辑

    错误登录

     

    正确登录

    视图

    # coding:utf-8
    import sqlite3
    from datetime import datetime
    from flask import Flask, request, render_template, redirect, url_for, g

    app = Flask(__name__)

    DATABASE = r'.dbfeedbach.db'

    '=======================封装sql助手函数============================='


    def make_dicts(cursor, row):
    """ 将游标获取的Tuple根据数据库列表转换为dict """
    return dict((cursor.description[idx][0], value) for idx, value in enumerate(row))


    def get_db():
    """ 获取(简历数据库链接)
    g: flask内置的变量:g = LocalProxy(partial(_lookup_app_object, "g"))
    """
    db = getattr(g, '_database', None)
    if not db:
    db = g._database = sqlite3.connect(DATABASE)
    db.row_factory = make_dicts
    return db


    def execute_sql(sql, params=()):
    """ 执行sql语句不返回数据结果 insert、update、delete """
    c = get_db().cursor()
    c.execute(sql, params)
    c.connection.commit()


    def query_sql(sql, params=(), one=False):
    """ 查询数据 one=False的时候返回多条"""
    c = get_db().cursor()
    result = c.execute(sql, params).fetchall()
    c.close()
    return (result[0] if result else None) if one else result


    @app.teardown_appcontext # 在当前app上下文销毁时执行
    def close_connection(exeption):
    """ 关闭数据库 """
    db = getattr(g, '_database', None)
    if db is not None:
    db.close()


    '========================================================================'


    @app.route("/")
    def index():
    return render_template('base.html')


    @app.route('/login/', methods=['GET', 'POST'])
    def login():
    """ 登录 """
    if request.method == 'POST':
    username = request.form.get('username')
    password = request.form.get('password')
    sql = 'select count(*) as [Count] from UserInfo where username = ? and password = ?'
    result = query_sql(sql, (username, password), True)
    if int(result.get('Count')) > 0:
    return redirect(url_for('list'))
    return '用户名或密码错误'
    return render_template('login.html')


    # 模板继承
    @app.route("/feedback/")
    def feedback():
    return render_template('post.html')


    @app.route("/post_feedback/", methods=["POST"])
    def post_feedback():
    """ 提交视图 """
    if request.method == 'POST': # 如果是post请求就获取表单值
    subject = request.form.get('subject', None)
    categoryid = request.form.get('category', 1)
    username = request.form.get('username')
    email = request.form.get('email')
    body = request.form.get('body')
    release_time = str(datetime.now())
    state = 0
    print(subject, categoryid, username, email, body, state, release_time)
    conn = sqlite3.connect(DATABASE)
    c = conn.cursor()
    # 防止sql注入,用?代替值
    sql = "insert into feedback (Subjeck, CategoryID, UserName, Email, Body, State, ReleaseTime) values (?,?,?,?,?,?,?)"
    c.execute(sql, (subject, categoryid, username, email, body, state, release_time))
    conn.commit()
    conn.close()
    # 为防止因卡顿引起重复提交,提交过后跳转到填写页面
    return redirect(url_for('feedback'))


    @app.route("/list/")
    def list():
    """ 展示所有问题 """
    sql = "select ROWID,* from feedback order by ROWID DESC"
    # feedbacks = query_sql(sql)
    # print(feedbacks)
    key = request.args.get('key', '')
    sql = 'select f.ROWID,f.*,c.CategoryName from feedback f INNER JOIN category c on c.ROWID = f.CategoryID where f.Subjeck like ? order by f.ROWID'
    feedbacks = query_sql(sql, (f'%{key}%',))
    return render_template('feedback-list.html', items=feedbacks)


    @app.route('/del/<id>/')
    def delete_feedback(id=0):
    """ 删除问题 ,前端传id"""
    conn = sqlite3.connect(DATABASE)
    c = conn.cursor()
    sql = "delete from feedback where ROWID = ?"
    c.execute(sql, (id,))
    conn.commit()
    conn.close()
    return redirect(url_for('list'))


    # 编辑功能
    @app.route("/edit/<id>/")
    def edit(id=None):
    """ 根据前端传过来的id返回编辑的html """
    # 获取绑定的下拉列表
    sql = "select ROWID,CategoryName from category"
    categories = query_sql(sql)
    # 获取当前id的信息,并绑定至form表单,以备修改
    sql = "select rowid,* from feedback where rowid = ?"
    curren_feedback = query_sql(sql, (id,), True)
    # return str(curren_feedback) # 查看查出来的数据顺序,方便html渲染排序
    return render_template('edit.html', categories=categories, item=curren_feedback)


    @app.route("/save_edit/", methods=['POST'])
    def save_edit():
    """ 保存编辑 """
    if request.method == 'POST':
    id = request.form.get('rowid', None)
    reply = request.form.get('reply')
    state = 1 if request.form.get('state', 0) == 'on' else 0
    sql = 'update feedback set Reply=?, State=? where rowid=?'
    conn = sqlite3.connect(DATABASE)
    c = conn.cursor()
    c.execute(sql, (reply, state, id))
    conn.commit()
    conn.close()
    return redirect(url_for('list'))


    if __name__ == '__main__':
    app.run(
    debug=True
    )

    html

    {% extends 'base.html' %}

    {% block main_content %}

    <!--登录界面-->
    <div class="row">
    <div class="col-md-6 col-md-offset-3">
    <div class="panel panel-default">
    <div class="panel-heading">
    <h4>登录</h4>
    </div>
    <div class="panel-body">
    <form action="#" class="form-horizontal" method="post">
    <div class="form-group">
    <label for="username">用户名:</label>
    <input type="text" class="form-control" name="username" id="username">
    </div>
    <div class="form-group">
    <label for="password">密码:</label>
    <input type="text" class="form-control" name="password" id="password">
    </div>
    <div class="form-group">
    <input type="submit" class="btn btn-primary" value="登录">
    </div>
    </form>
    </div>
    <div class="footer">
    &copy;版权所有
    </div>
    </div>
    </div>
    </div>








    {% endblock %}
  • 相关阅读:
    linux下sar指令查看系统活动报告
    视频卡顿网络侧问题处理----2019-5-17
    mysql中的group by
    多个条件组合的测试用例该如何决策
    对多条件进行组合,生成笛卡尔积的用例集合的python代码实现
    音视频测试相关文档集合
    类型转换
    基本类型:实型(浮点型)
    有符号数和无符号数
    基本类型:整型与字符型
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/11461904.html
Copyright © 2020-2023  润新知