关于flask入门教程-app代码

2022-03-11 17:12:33 浏览数 (1)

Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2。

Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容易上手。

它可以很好地结合MVC模式进行开发,开发人员分工合作,小型团队在短时间内就可以完成功能丰富的中小型网站或Web服务的实现。

另外,Flask还有很强的定制性,用户可以根据自己的需求来添加相应的功能,在保持核心功能简单的同时实现功能的丰富与扩展,其强大的插件库可以让用户实现个性化的网站定制,开发出功能强大的网站。

在本微小项目应用的flask程序里实现了系统的登陆、注销、主页面、用户信息的查询、增加、删除、修改等功能。

关于主框架

代码语言:javascript复制
# 将原生SQL语句返回结果集转换为字典       def datatodict():  
# 检查登陆情况      def login_check(): login.html
# 上下文钩子       def my_context_process():  
# 错误处理-404页面   @app.errorhandler(404) def internal_error(error): 404.html
# 错误处理-500页面   @app.errorhandler(500) def internal_error(error): 500.html
# 登陆页面 @app.route("/")    def login():   login.html
# 登录页面的提交验证    @app.route("/login")   def slogin():  home.html
# 注销页面 @app.route("/logout")  def logout():  login.html
# 管理系统主页面  @app.route('/home')    def home():    home.html
# 当前信息主页面  @app.route('/userinfo')    def userinfo():    userinfo.html
# 添加用户主页面  @app.route('/userinfo/useradd')    def useradd(): useradd.html
# 添加用户主页面响应    @app.route('/userinfo/useradd')    def useradd(): userinfo.html
# 删除用户主页面提交响应  @app.route('/userinfo/userdelete') def userdelete():  userinfo.html
# 修改用户主页面  @app.route('/userinfo/userupdate/<userid>')    def userupdate():  userupdate.html
# 修改用户主页面响应    @app.route('/userinfo/userupdate/<userid>')    def userupdate():  userinfo.html
import config
from exts import db
from functools import wraps
from flask import Flask,render_template,request,url_for,session,redirect,flash
from flask_paginate import Pagination,get_page_parameter
from flask_sqlalchemy import SQLAlchemy
from models import UserInfo,XxxInfo
from datetime import datetime

app = Flask(__name__)
# 从config.py文件中获取数据库配置信息
app.config.from_object(config)
db = SQLAlchemy(app)
if __name__ == '__main__':
    app.run()

系统常用到的几个标准函数

代码语言:javascript复制
# 将原生SQL语句返回结果转换为字典
def datatodict(resultProxy,fetch):
    #resultProxy = db.session.execute(sql, params, bind=db.get_engine(bind=bind))
    if fetch == 'one':
        result_tuple = resultProxy.fetchone()
        if result_tuple:
            result = dict(zip(resultProxy.keys(), list(result_tuple)))
        else:
            return None
    else:
        result_tuple_list = resultProxy.fetchall()
        if result_tuple_list:
            result = []
            keys = resultProxy.keys()
            for row in result_tuple_list:
                result_row = dict(zip(keys, row))
                result.append(result_row)
        else:
            return None
    return result

# 检查登陆情况
def login_check(func):
    @wraps(func)
    def wrapper(*args,**kwargs):
        if session.get('userid'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('login'))
    return wrapper

# 上下文钩子
@app.context_processor
def my_context_processor():
    userid = session.get('userid')
    if userid:
        userinfo = UserInfo.query.filter(UserInfo.userid == userid).first()
        if userinfo:
            return {'userinfo': userinfo}
    return {}

定制错误处理响应页面

代码语言:javascript复制
# -------------------------错误管理------------------------
# 错误处理-404页面
@app.errorhandler(404)
def internal_error(error):
    return render_template('404.html'),404
# 错误处理-500页面
@app.errorhandler(500)
def internal_error(error):
    db.session.rollback()
    return render_template('500.html'),500

登陆管理,包括登陆、注销页面和提交验证

代码语言:javascript复制
# -------------------------登陆管理------------------------
# 登陆页面
@app.route('/',methods=['GET','POST'])
def login():
    return render_template('login.html')

# 登录页面的提交验证
@app.route('/login',methods=['POST'])
def slogin():
    username = request.form['username']
    password = request.form['password']
    userinfo = UserInfo.query.filter(UserInfo.username == username,UserInfo.password == password).first()
    if userinfo:
        session['userid'] = userinfo.userid
        return redirect(url_for('home'))
    else:
        return  render_template('login.html',errorinfo='密码或账户输入错误')

# 注销登录
@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))

系统主页面

代码语言:javascript复制
# -------------------------主界面管理------------------------
# 管理系统主页面
@app.route('/home')
@login_check
def home():
    return render_template('home.html')

用户主页面,里面可进行数据的查询、新增、修改、删除

代码语言:javascript复制
# -------------------------用户界面管理------------------------
# 用户信息主页面
@app.route('/userinfo/',methods=['GET', 'POST'])
def userinfo():
    # 获取当前页
    page = request.args.get('page', 1,type=int)
    # 初始化参数值
    usernamestr='%'
    personalnamestr='%'
    # POST提交获取各提交参数,写入session,并将页码置为1
    if request.method == 'POST':
        session['username'] = request.form['username']
        session['personalname'] = request.form['personalname']
        page=1
    # 获取session值,如果存在或有值,则写入参数
    if session.get('username') :
        usernamestr = "%"   session['username']   "%"
    if session.get('personalname') :
        personalnamestr = "%"   session['personalname']   "%"
    # sql主题语句
    sqlpart="select userid,username,password,personalname,birthday,sex,phone,postcard,address from userinfo "
    # where主体语句
    wherepart = " where 1=1 and username like '{usernamestr}' and personalname like '{personalnamestr}'"
    # order by 主体语句
    orderbypart=" ORDER BY userid ASC "
    # 分页语句
    limitpart=" LIMIT {limit} offset {offset} "
    # 每页记录行数暂时内定5
    limit=5
    # 获取当前偏移量
    offset=(5 * int(page)-5)
    # 把sql主体语句和where主体语句的SQL合并起来,获取总页数
    sqlcount = "select count(*) from ( "   sqlpart   wherepart   " )"
    # sql语句,参数赋值
    sqlcount=sqlcount.format(usernamestr=usernamestr,personalnamestr=personalnamestr)
    total = db.session.execute(sqlcount).fetchone()[0]
    sql = sqlpart   wherepart   orderbypart   limitpart
    # sql语句,参数赋值
    sql = sql.format(limit=limit, offset=offset,usernamestr=usernamestr,personalnamestr=personalnamestr)
    # 获取执行结果
    data = db.session.execute(sql).all()
    # 获取分页代码
    pagination = Pagination(page=page, total=total, per_page=5)
    # 将数据和分页代码传给页面
    return render_template('userinfo.html', pagedata=data, pagination=pagination)

用户增加界面和提交验证

代码语言:javascript复制
# 添加用户提交
@app.route('/userinfo/useradd',methods=['GET', 'POST'])
def useradd():
    # Bootstrap提供的alert样式,依次为:‘success’、‘info’、‘warning’、‘danger’。
    if request.method == 'GET':
        return render_template('useradd.html')
    elif request.method == 'POST':
        username = request.form.get('username',type=str,default=None)
        password = request.form.get('password',type=str,default=None)
        personalname = request.form.get('personalname',type=str,default=None)
        birthday = request.form.get('birthday',type=str,default=None)
        sex = request.form.get('sex',type=str,default='男')
        phone = request.form.get('phone',type=str,default=None)
        postcard = request.form.get('postcard',type=str,default=None)
        address = request.form.get('address',type=str,default=None)
        birthday=datetime.strptime(birthday, '%Y-%m-%d').date()
        createdate = datetime.now()
        modifydate = datetime.now()
        createuserid=session.get('userid')
        sql = "select count(*) from userinfo where username='{}'".format(username)
        isexist = db.session.execute(sql).fetchone()[0]
        if isexist:
            flash('该用户已经存在!','danger')
            return redirect('/userinfo/useradd')
        else:
            sql = "insert into userinfo (username,password,personalname,birthday,sex,phone,postcard,address,createdate,modifydate,createuserid) " 
                  "values(:username,:password,:personalname,:birthday,:sex,:phone,:postcard,:address,:createdate,:modifydate,:createuserid)"
            params={"username":username,
                    "password":password,
                    "personalname":personalname,
                    "birthday":birthday,
                    "sex":sex,
                    "phone":phone,
                    "postcard":postcard,
                    "address":address,
                    "createdate":createdate,
                    "modifydate":modifydate,
                    "createuserid":createuserid}
            db.session.execute(sql,params)
            db.session.commit()
            return redirect('/userinfo/')

用户删除和返回

代码语言:javascript复制
# 删除用户提交响应
from flask import jsonify
@app.route('/userinfo/userdelete')
def userdelete():
    userid = request.values.get("userid")
    sql = "delete from userinfo where userid=:userid"
    params = {"userid": userid}
    from sqlalchemy.exc import SQLAlchemyError

    try:
        db.session.execute(sql, params)
        db.session.commit()
        return jsonify({"code": 200, "message": "删除成功"})
    except SQLAlchemyError as e:
        db.session.rollback()
        return jsonify({"code": 400, "message": "删除错误"})
    finally:
        db.session.close()

用户变更页面和提交验证

代码语言:javascript复制
# 变更用户信息
@app.route('/userinfo/userupdate/<int:userid>', methods=['GET', 'POST'])
def userupdate(userid):
    if request.method == 'GET':
        sql = "select userid,username,password,personalname,birthday,sex,phone,postcard,address from userinfo where userid=:userid"
        params = {"userid": userid}
        user = db.session.execute(sql, params)
        userdict=datatodict(user,'one')
        return render_template('userupdate.html',user = userdict)
    else:
        username = request.form.get('username', type=str, default=None)
        password = request.form.get('password', type=str, default=None)
        personalname = request.form.get('personalname', type=str, default=None)
        birthday = request.form.get('birthday', type=str, default=None)
        sex = request.form.get('sex', type=str, default='男')
        phone = request.form.get('phone', type=str, default=None)
        postcard = request.form.get('postcard', type=str, default=None)
        address = request.form.get('address', type=str, default=None)
        birthday = datetime.strptime(birthday, '%Y-%m-%d').date()
        modifydate = datetime.now()
        sql = "update userinfo " 
              "set " 
              " username=:username," 
              " password=:password," 
              " personalname=:personalname," 
              " birthday=:birthday," 
              " sex=:sex," 
              " phone=:phone," 
              " postcard=:postcard," 
              " address=:address," 
              " modifydate=:modifydate" 
              " where userid=:userid"
        params = {"username": username,
                  "password": password,
                  "personalname": personalname,
                  "birthday": birthday,
                  "sex": sex,
                  "phone": phone,
                  "postcard": postcard,
                  "address": address,
                  "modifydate": modifydate,
                  "userid": userid}
        print(params)
        db.session.execute(sql, params)
        db.session.commit()
        return redirect('/userinfo')

0 人点赞