1. 定制软件用到的技术
1.1 导模块
from flask import Flask, render_template, jsonify, redirect, request, url_for, session
1.2 模块介绍
1.3 路由系统
1.3.1 普通使用
@app.route('/delete')
1.3.2 定制软件带有名分组
@app.route('/edit/<string:nid>', 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/<int:nid>', redirect_to='/home/<nid>')
- '''
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 &装饰器
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. 快速搭建管理系统
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/<string:nid>', 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
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>登录</title>
- </head>
- <body>
- <form method="post">
- <p>用户名:<input type="text" name="username"></p>
- <p>密码:<input type="password" name="password"></p>
- {{ error }}
- <input type="submit" value="提交">
- </form>
- </body>
- </html>
2.2.3 index.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
- </head>
- <body>
- <div>
- <div class="bs-example" data-example-id="hoverable-table">
-
- <div class="panel panel-info">
- <div class="panel-heading">
- <h3 class="panel-title">xx管理系统</h3>
- </div>
- <div class="panel-body">
- <table class="table table-hover">
- <thead>
- <tr>
- <th>序号</th>
- <th>名称</th>
- <th>年龄</th>
- <th>操作</th>
- </tr>
- </thead>
- <tbody>
- {% for key,item in data_dict.items() %}
- <tr>
- <th scope="row">{{ key }}</th>
- <td>{{ item.name }}</td>
- <td>{{ item["age"] }}</td>
- <td><a href="/edit/{{ key }}">编辑</a>|
- <a href="/delete?nid={{ key }}">
- 删除
- </a>
- </td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- </div>
- </div>
-
-
- </div>
- </div>
- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
- <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
- </body>
- </html>
2.2.4 edit.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>编辑</title>
- </head>
- <body>
- <form method="post">
- <p>用户名:<input type="text" name="username" value="{{ user_dic.name }}"></p>
- <p>密码:<input type="text" name="age" value="{{ user_dic.age }}"></p>
- <input type="submit" value="提交">
- </form>
- </body>
- </html>