from flask import Flask, render_template, jsonify, redirect, request, url_for, session
@app.route('/delete')
@app.route('/edit/' , methods=['GET', 'POST']) # 有名分组 默认string
@app.route('/login', methods=['GET', 'POST']) # 默认支持get,需要手动添加post
@app.route('/index', endpoint='index') # 起别名,不写默认函数名称
- DEFAULT_CONVERTERS = {
- 'default': UnicodeConverter,
- 'string': UnicodeConverter,
- 'any': AnyConverter,
- 'path': PathConverter,
- 'int': IntegerConverter,
- 'float': FloatConverter,
- 'uuid': UUIDConverter,
- }
- 本质就是: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)
-
-
- |
- @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. get请求
- nid = request.args.get('nid')
- # 2. post请求
- username = request.form.get('username')
1.5.1 返回时的格式
- return render_template('login.html', error='用户名错误')
- return render_template('login.html', **{'error':'xxx','age':'xxx'})
- 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)
-
-
- @app.before_requestdef
- def func():
- print('xxx')
-
-
- def x1():
- print('xxx')
- x1.app.before_request(x1)
orm / session / cookie / admin / form / modelform/路由/视图/模板/中间件/分页/ auth / contenttype/缓存/信号/多数据库连接
- from flask import Flask
-
- # 起一个名字
- app = Flask(__name__)
-
-
- # 配置路由
- @app.route('/index')
- def index():
- return 'hello word'
-
-
- if __name__ == '__main__':
- # 启动
- app.run()
- 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()
- 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>
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Titletitle>
- <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>
- 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>
