基于Flask快速搭建一个管理系统

  1. 用到的技术

1.1 导模块

from flask import Flask, render_template, jsonify, redirect, request, url_for, session

1.2 模块介绍

1.3 flask路由系统

1.3.1 普通使用

@app.route('/delete')

1.3.2 带有名分组

@app.route('/edit/', methods=['GET', 'POST'])  # 有名分组 默认string

1.3.3 带请求限制

@app.route('/login', methods=['GET', 'POST'])  # 默认支持get,需要手动添加post

1.3.4 带别名,默认别名是函数名

@app.route('/index', endpoint='index')  # 起别名,不写默认函数名称

1.3.5 路由其他参数(默认string)

DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}

1.3.6 路由的本质

本质就是:app.add_url_rule()

路由加载的源码流程
-将ur1和函数打包成为rule对象
-将ru1e对象添加到map对象中。
- app.url_map = map对象

endpoint:如果不写默认是函数名,endpoint不能重名

一般使用第一种
@app.route('/index')
def index():
    return render_template(' index.html ')

第二种
def home():
    return render_template(' index.html ')
app.add_url_rule('/home', 'home', home)

|

1.3.7 app.add_url_rule参数

@app.route和app.add_url_rule参数:
rule:URL规则
view_func:视图函数名称
defaults = None, 默认值, 当URL中无参数,函数需要参数时,使用defaults = {'k': 'v'}
为函数提供参数
endpoint = None, 名称,用于反向生成URL,即: url_for('名称')
methods = None, 允许的请求方式,如:["GET", "POST"]
#对URL最后的 / 符号是否严格要求,默认严格,False,就是不严格
strict_slashes = None
    '''
        @app.route('/index', strict_slashes=False)
        #访问http://www.xx.com/index/ 或http://www.xx.com/index均可
        @app.route('/index', strict_slashes=True)
        #仅访问http://www.xx.com/index
    '''
#重定向到指定地址
redirect_to = None,
    '''
        @app.route('/index/', redirect_to='/home/')
    '''

1.4 获取提交的数据

1. get请求
nid = request.args.get('nid')
2. post请求
username = request.form.get('username')

1.5 返回数据

1.5.1 返回时的格式

return render_template('login.html', error='用户名错误')
return render_template('login.html', **{'error':'xxx','age':'xxx'})

1.5.2 坑1,出现找不到模板,解决办法

  • 项目下面是否有templates文件夹,你的html文件是否放进了里面;
  • templates文件夹是否和你运行的py文件在同一级目录;
  • render_template(‘***.html’)这里面的名字是否正确,别打错了;
  • app = Flask(name, template_folder=’templates’) 在最开始的这句话中,template_folder后面一定要跟上templates;

1.6 session&装饰器

1.6.1 导入&使用

import functools
from flask import session

flask使用session需要,传入一个secret_key,flask会生成一个key返回给前端,类似于cookie存储
app.secret_key = 'lfsakhfnednlasdjmcls'

def auth(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        if session.get('username'):
            # print(session.get('username'))
            ret = func(*args, **kwargs)
            return ret
        return redirect(url_for('login'))

    return inner

@app.route('/index', endpoint='index')  # 起别名,不写默认函数名称
@auth
def index():
    """首页"""
    return render_template('index.html', data_dict=DATA_LIST)

1.6.2 装饰器的使用方法

@app.before_requestdef
def func():
    print('xxx')

def x1():
    print('xxx')
x1.app.before_request(x1)

1.7 request介绍

  • django的请求处理是逐一封装和传递;
  • flask的请求是利用上下文管理来实现的。

1.8 django/flask介绍

  • django是个大而全的框架,flask是一个轻量级的框架。 django内部为我们提供了非常多的组件:
orm / session / cookie / admin / form / modelform/路由/视图/模板/中间件/分页/ auth / contenttype/缓存/信号/多数据库连接
  • flask框架本身没有太多的功能:路由/视图/模板(jinja2)/session/中间件,第三方组件非常齐全。

  • 快速搭建管理系统

2.1 基本使用

from flask import Flask

起一个名字
app = Flask(__name__)

配置路由
@app.route('/index')
def index():
    return 'hello word'

if __name__ == '__main__':
    # 启动
    app.run()

2.2 完整版

2.2.1 py

import functools
from flask import Flask, render_template, jsonify, redirect, request, url_for, session

app = Flask(__name__)  # 默认 template_folder='templates'
模拟数据
DATA_LIST = {
    '1': {'name': 'a', 'age': 32},
    '2': {'name': 'a', 'age': 64},

}
flask使用session需要,传入一个secret_key,flask会生成一个key返回给前端,类似于cookie存储
app.secret_key = 'lfsakhfnednlasdjmcls'

def auth(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        if session.get('username'):
            # print(session.get('username'))
            ret = func(*args, **kwargs)
            return ret
        return redirect(url_for('login'))

    return inner

@app.route('/login', methods=['GET', 'POST'])  # 默认支持get,需要手动添加post
def login():
    """登录"""
    # render_template,  # 类似与django中国的render
    # jsonify, # 类似与django中国的JsonResponse
    # url_for 别名
    if request.method == 'GET':
        return render_template('login.html')
    username = request.form.get('username')
    password = request.form.get('password')
    if username == '1' and password == '1':
        session['username'] = username
        return redirect('/index')
    return render_template('login.html', error='用户名错误')

@app.route('/index', endpoint='index')  # 起别名,不写默认函数名称
@auth
def index():
    """首页"""
    return render_template('index.html', data_dict=DATA_LIST)

@app.route('/edit/', methods=['GET', 'POST'])  # 有名分组 默认string
@auth
def edit(nid):
    """编辑"""
    if request.method == 'GET':
        user_dic = DATA_LIST.get(nid)
        # print(user_dic) # {'name': 'a', 'age': 32}
        return render_template('edit.html', user_dic=user_dic)
    name = request.form.get('username')
    age = request.form.get('age')
    DATA_LIST[nid]['name'] = name
    DATA_LIST[nid]['age'] = age
    return redirect('/index')

@app.route('/delete')
@auth
def delete():
    """删除"""
    nid = request.args.get('nid')
    print(nid)  # 2
    del DATA_LIST[nid]
    return redirect(url_for('index'))

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

2.2.2 login.html


    登录

    用户名:
    密码:
    {{ error }}

2.2.3 index.html


    Title

                xx管理系统

                        序号
                        名称
                        年龄
                        操作

                    {% for key,item in data_dict.items() %}

                        {{ key }}
                        {{ item.name }}
                        {{ item["age"] }}
                        编辑|

                                删除

                    {% endfor %}

2.2.4 edit.html


    编辑

    用户名:
    密码:

  1. 截图

基于Flask快速搭建一个管理系统

Original: https://blog.csdn.net/qq_52385631/article/details/123466949
Author: 骑台风走
Title: 基于Flask快速搭建一个管理系统

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/744113/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 关于matplotlib安装失败

    在pychram的terminal安装matplotlib模块不能被import 昨天试了无数次,也找了很多方法尝试。最终终于成功了! 前提是项目用的是anaconda创建的虚拟环…

    Python 2023年9月6日
    071
  • Ubuntu20.04安装vscode配置python环境

    记录一下在Ubuntu20.04下安装vscode并配置python环境的过程 1、安装vscode 在官网上下载vscode deb安装包,官网地址 Visual Studio …

    Python 2023年8月1日
    092
  • Python使用flask搭建HTTP服务并测试

    Python使用flask搭建HTTP服务并测试 响应GET、POST请求代码 运行代码 * 取消WARNING警告 使用Postman测试 * 测试响应get请求 测试响应pos…

    Python 2023年8月13日
    058
  • 掌握 Python 中下划线的 5 个潜规则

    本文将介绍Python中 单下划线和 双下划线(“dunder”)的各种含义和命名约定,名称修饰(name mangling)的工作原理,以及它如何影响你自…

    Python 2023年6月11日
    080
  • java贪吃蛇项目总结_《结对-贪吃蛇-结对项目总结》

    《结对-贪吃蛇-结对项目总结》 1.编写目的 鉴于日常工作压力太大,闲暇的时间大多比较零碎,为了缓解紧张的情绪,获得更高工作效率,人们在日常的娱乐生活中,经常会玩一些单机版的益智类…

    Python 2023年9月22日
    054
  • CARTOPY

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

    Python 2023年9月1日
    055
  • Spring获取Bean的9种方式

    随着SpringBoot的普及,Spring的使用也越来越广,在某些场景下,我们无法通过注解或配置的形式直接获取到某个Bean。比如,在某一些工具类、设计模式实现中需要使用到Spr…

    Python 2023年11月6日
    027
  • matplotlib常见绘图函数

    plt.scatter()函数用于生成一个scatter 散点图。 matplotlib.pyplot.scatter(x, y, s=20, c=’b’, marker=’o’,…

    Python 2023年9月3日
    063
  • 深度学习入门:基于Python的理论与实现

    1.Python入门 python中使用class关键字来定义类: class 类名: def __init__(self, 参数,…): … def 方法1(self, …

    Python 2023年8月24日
    073
  • 懒加载

    使用原生JavaScript实现懒加载 window.innerHeight 是浏览器可视区的高度 document.body.scrollTop || document.docu…

    Python 2023年10月20日
    038
  • 太空射击第09课:精灵动画

    太空射击第09课:精灵动画 在本课中,我们将通过添加一些精灵动画来使我们的流星更有趣。本次课用到的图像可以点击这里下载 视频 观看视频 流星动画 pygame 中的transfor…

    Python 2023年9月25日
    043
  • 自制卡牌游戏Python

    这次我会开一个系列,持续更新(也不排除放弃的可能)。 先进行基本的框架搭建 import pygame,sys canvas=pygame.display.set_mode((13…

    Python 2023年9月20日
    071
  • 用 ChatGPT 运行 Python

    啊哦~你想找的内容离你而去了哦 内容不存在,可能为如下原因导致: ① 内容还在审核中 ② 内容以前存在,但是由于不符合新 的规定而被删除 ③ 内容地址错误 ④ 作者删除了内容。 可…

    Python 2023年11月4日
    043
  • Python 字符串str详解(超详细)

    文章目录 Python内置函数/方法详解—字符串str * 1、创建字符串 – 1.1 使用 ‘ ‘ 或 ” ” 创建字…

    Python 2023年8月1日
    070
  • 如何从零开始搭建基于Django的后端项目

    web项目开发之开发环境的搭建 开始开发一个Django项目前,如何搭建虚拟环境呢?假设初始配置为:linux ubuntu20.04 pycharm专业版假设项目名称为: Pco…

    Python 2023年8月5日
    047
  • 瞧瞧别人家的API接口,那叫一个优雅

    在实际工作中,我们需要经常跟第三方平台打交道,可能会对接第三方平台API接口,或者提供API接口给第三方平台调用。 那么问题来了,如果设计一个优雅的API接口,能够满足:安全性、可…

    Python 2023年10月12日
    040
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球