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', ' ...
随机推荐
- Elasticsearch中文搜索环境搭建
Elasticsearch是一个建立在全文搜索引擎 Apache Lucene™ 基础上的搜索引擎,功能强大,最近刚好要研究搜索这一块,简要记录备日后查阅 安装Java JDK,由于Lucene是用J ...
- Rare But Powerful Vim Commands.
@1: We all know about :wq, but we usually ignore :x. :x和:wq都是保存当前文件并退出. 这两个命令实际上并不完全等价,当文件被修改时两个命令时相 ...
- appium server日志分析
文章出处http://blog.csdn.net/yan1234abcd/article/details/60765295 每次运行测试,可以从Appium Server控制台看到有特别多的日志输出, ...
- appium入门基础
1. 建立session时常用命令: DesiredCapabilities cap = new DesiredCapabilities(); cap.SetCapability("brow ...
- smarty基础原理
smarty基础原理 一.html模板页面 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" &q ...
- 12 Spring框架 SpringDAO的事务管理
上一节我们说过Spring对DAO的两个支持分为两个知识点,一个是jdbc模板,另一个是事务管理. 事务是数据库中的概念,但是在一般情况下我们需要将事务提到业务层次,这样能够使得业务具有事务的特性,来 ...
- hibernate 一对多、多对多的配置
一对多 <class name="Question" table="questions" dynamic-insert="true" ...
- PL/SQL编程—视图
create or replace view test_view as select TestA.id, TestB.idno, TestB.name, TestB.sex from TestB le ...
- 笔记-CSS空背景图片会导致页面被加载两次
如果页面样式的背景图片路径设置为'' 或 '#', 会导致页面被重复加载两次 (Chrome.56.0.2924.87 测试) 因为:空图片路径属性值,默认加载当前页面的URL作为图片路径 Safar ...
- 对 Java Integer.valueOf() 的一些了解
从一道选择题开始 分析 选项A 选项A中比较的是i01和i02,Integer i01=59这里涉及到自动装箱过程,59是整型常量,经包装使其产生一个引用并存在栈中指向这个整型常量所占的内存,这时 ...