Flask 的路由系统 FBV 与 CBV
Flask的路由系统
本质:
带参数的装饰器
传递函数后 执行 add_url_rule 方法
将 函数 和 url 封装到一个 Rule对象
将Rule对象 添加到 app.url_map(Map对象)
注意:装饰器要放在路由的上方 -- 注意装饰器的执行顺序
1 路由格式以及参数
@app.route('/user/<username>')
@app.route('/post/<int:post_id>')
@app.route('/post/<float:post_id>')
@app.route('/post/<path:path>')
@app.route('/login', methods=['GET', 'POST'])
本质: app.add_url_rule(rule 路由, endpoint 别名, f 视图函数, **options 参数)
常用路由系统有以上五种,所有的路由系统都是基于一下对应关系来处理:
DEFAULT_CONVERTERS = {
'default': UnicodeConverter,
'string': UnicodeConverter,
'any': AnyConverter,
'path': PathConverter,
'int': IntegerConverter,
'float': FloatConverter,
'uuid': UUIDConverter,
}
app.route和app.add_url_rule参数详细:
rule, URL规则
view_func, 视图函数名称 #CBV 使用 view_func=IndexView.as_view(name='...')
defaults=None, 默认值,当URL中无参数,函数需要参数时,使用defaults={'k':'v'}为函数提供参数
endpoint=None, 名称,用于反向生成URL,即: url_for('名称')
methods=None, 允许的请求方式,如:["GET","POST"]
strict_slashes=None, 对URL最后的 / 符号是否严格要求
如:
@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>')
或
def func(adapter, nid):
return "/home/888"
@app.route('/index/<int:nid>', redirect_to=func)
subdomain=None, 子域名访问
公网上线时
租域名 aaa.com/net
租用服务器 + 公网IP 213.213.21
访问 域名 -->> (域名解析)ip
测试时 修改hosts
hosts文件
127.0.0.1:8000 www.aaa.com
127.0.0.1:8000 www.admin.aaa.com
127.0.0.1:8000 www.username.aaa.com
使用子域名
from flask import Flask, views, url_for
app = Flask(import_name=__name__)
app.config['SERVER_NAME'] = 'www.aaa.com:5000' # 配置主域名
@app.route("/", subdomain="admin") # 子域名 admin.aaa.com
def static_index():
return "static.your-domain.tld"
@app.route("/dynamic", subdomain="<username>") # 传参--字符串 username.aaa.com/dynamic
def username_index(username):
return username + ".your-domain.tld"
if __name__ == '__main__':
app.run()
>## 2 url_for 与 endpoint
url反向生成
无参数
app.route('/login',method=['GET','POST'],endpoint='login')
视图
return redirect(url_for('login'))
模板
<form action='{{url_for("login")}}'></form>
有参数
app.route('/index/<int:nid>',method=['GET','POST'],endpoint='index')
视图
return redirect(url_for('index',nid=111))
模板
<form action='{{url_for("index",nid=111)}}'></form>
>## 3 让路由支持正则
from flask import Flask, views, url_for
from werkzeug.routing import BaseConverter # 导入基础转换类
app = Flask(import_name=__name__)
# 正则表达式类
class RegexConverter(BaseConverter):
"""
自定义URL匹配正则表达式
"""
def __init__(self, map, regex):
super(RegexConverter, self).__init__(map)
self.regex = regex
def to_python(self, value):
"""
路由匹配时,匹配成功后传递给视图函数中参数的值
:param value:
:return:
"""
return int(value)
def to_url(self, value):
"""
使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
:param value:
:return:
"""
val = super(RegexConverter, self).to_url(value)
return val
app.url_map.converters['regex'] = RegexConverter # 添加到flask中
@app.route('/index/<regex("\d+"):nid>') # 使用
def index(nid):
print(url_for('index', nid='888'))
return 'Index'
if __name__ == '__main__':
app.run()
>##4 Flask 的FBV与CBV
不常使用
from flask import Flask,views,redirect,url_for # 导入views 基础类
app = Flask(__name__)
# 定义装饰器
def auth_decorator(func):
def inner(*args,**kwargs):
print('装饰器')
return func(*args,**kwargs)
return inner
CBV 添加 装饰器 和 指定 请求方法
class IndexView(views.MethodView):
methods = ['POST','GET'] # 指定允许的 请求方法
decorators = [auth_decorator] # 所有方法都加上 装饰器
def get(self):
return redirect(url_for('home'))
def post(self):
return 'POST'
class HomeView(views.MethodView):
def get(self):
return 'Home'
app.add_url_rule('/index',view_func=IndexView.as_view(name='index'))
app.add_url_rule('/home',view_func=HomeView.as_view(name='home'))
# CBV 只能通过这种方式
# view_func = IndexView.as_view(name='index') # 指定 反向解析的name
if __name__ == '__main__':
app.run()
Flask 的路由系统 FBV 与 CBV的更多相关文章
- Flask最强攻略 - 跟DragonFire学Flask - 第七篇 Flask 中路由系统
Flask中的路由系统其实我们并不陌生了,从一开始到现在都一直在应用 @app.route("/",methods=["GET","POST" ...
- Flask中路由系统以及蓝图的使用
一.Flask的路由系统 1.@app.route()装饰器中的参数 methods:当前URL地址,允许访问的请求方式 @app.route("/info", methods=[ ...
- day89_11_11Flask启动,配置,路由,fbv和cbv
一.flask的形成. flask是一个基于python并且以来jinja2模板和werkzeug wsgi服务器的一个微型框架. 安装了flask模块就代表安装了wekzeug,所以先安装flask ...
- 源码解析flask的路由系统
源码解析flask的路由系统 当我们新建一个flask项目时,pycharm通常已经为项目定义了一个基本路由 @app.route('/') def hello_world(): return 'He ...
- 第七篇 Flask 中路由系统以及参数
Flask中的路由系统其实我们并不陌生了,从一开始到现在都一直在应用 @app.route("/",methods=["GET","POST" ...
- 第七篇 Flask 中路由系统
1. @app.route() 装饰器中的参数 如果不明白装饰器 点击这里 methods : 当前 url 地址,允许访问的请求方式 @app.route("/info", me ...
- 7,Flask 中路由系统
Flask中的路由系统 @app.route("/",methods=["GET","POST"]) 为什么要这么用?其中的工作原理我们知道 ...
- flask框架路由系统
flask框架的url系统: flask框架的路由系统: flask框架的路由系统使用实例化的route方法来指定: 如: @app.route('/') route函数装饰器可以把一个函数绑定到对应 ...
- Flask之路由系统
路由系统 路由的两种写法 1.第一种方法: def index(): return render_template('index.html') app.add_url_rule('/index', ' ...
随机推荐
- mysql-5.6.22的安装步骤
一.环境与下载地址: 1.系统下载地址: http://mirrors.sohu.com/centos/6.6/isos/x86_64/CentOS-6.6-x86_64-bin-DVD1.iso 2 ...
- nginx常用
1.rewrite return 301 http://example.com$request_uri; rewrite ^ http://example.com permanent; 2.try_f ...
- 基本运算符与流程控制(Day5)
一 运算符 1.算数运算 2.比较运算 3.赋值运算 4.逻辑运算 and注解: 在Python 中,and 和 or 执行布尔逻辑演算,如你所期待的一样,但是它们并不返回布尔值:而是,返回它们实际 ...
- Python(变量、数据类型)
常量:python中没有常量,只能通过名字特征来提示例如:全部大写,如 : OLDBOY_AGE=57 一.变量 变量声明变量#!/usr/bin/env python age=18gender1=' ...
- 为Windows窗口标题栏添加新按钮
为Windows窗口标题栏添加新按钮 对于我们熟悉的标准windows窗口来讲,标题栏上一般包含有3个按钮,即最大化按钮,最小化按钮和关闭按钮.你想不想在Windows的窗口标题栏上添加一个新的自 ...
- BCB直接访问硬件端口和物理内存 - WinIO的应用
BCB直接访问硬件端口和物理内存 - WinIO的应用 (读硬盘参数和主板BIOS信息, 支持 Win9x/NT/2k/XP/2003) 关于直接访问端口, 有很多网站很多文章都讨论过, 但总找不到非 ...
- 关于maven包冲突的一些思路
在最近的项目中出现了很多包冲突,有时一下子就能猜到错误,但是有写往往需要很久都不能定位问题,尤其是项目人员参差不齐,有时为了方便私自引入一些工具类,而未考虑到项目本身. maven的出现方便了我们的包 ...
- Flume1.7.0概述
Flume概述 常见的开源数据收集系统有: 非结构数据(日志)收集 Flume 结构化数据收集(传统数据库与 Hadoop 同步) Sqoop:全量导入 Canal(alibaba):增量导入 Dat ...
- PHP 网站隔离配置
PHP网站间隔离 网站内目录与目录之间是可以访问的,在某些特定情况下这样是不安全的,如果目录间网址权限被黑客利用很可能造成数据流失,在这里我们可以通过PHPopen_basedir来实现网站间目录隔离 ...
- Oracle中对现有表增加列
altertable Tablename add(column1 varchar2(20),column2 number(7,2)...) --Oracle中修改列名不可以,但是可以删除列,增加列 a ...