路由系统

  • @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'])

常用路由系统有以上五种,所有的路由系统都是基于一下对应关系来处理:

DEFAULT_CONVERTERS = {
'default': UnicodeConverter,
'string': UnicodeConverter,
'any': AnyConverter,
'path': PathConverter,
'int': IntegerConverter,
'float': FloatConverter,
'uuid': UUIDConverter,
}
 def auth(func):
def inner(*args, **kwargs):
print('before')
result = func(*args, **kwargs)
print('after')
return result return inner @app.route('/index.html',methods=['GET','POST'],endpoint='index')
@auth
def index():
return 'Index' 或 def index():
return "Index" self.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"])
or
app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"])
app.view_functions['index'] = index 或
def auth(func):
def inner(*args, **kwargs):
print('before')
result = func(*args, **kwargs)
print('after')
return result return inner class IndexView(views.View):
methods = ['GET']
decorators = [auth, ] def dispatch_request(self):
print('Index')
return 'Index!' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint 或 class IndexView(views.MethodView):
methods = ['GET']
decorators = [auth, ] def get(self):
return 'Index.GET' def post(self):
return 'Index.POST' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint @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"] 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, 子域名访问
from flask import Flask, views, url_for app = Flask(import_name=__name__)
app.config['SERVER_NAME'] = 'wupeiqi.com:5000' @app.route("/", subdomain="admin")
def static_index():
"""Flask supports static subdomains
This is available at static.your-domain.tld"""
return "static.your-domain.tld" @app.route("/dynamic", subdomain="<username>")
def username_index(username):
"""Dynamic subdomains are also supported
Try going to user1.your-domain.tld/dynamic"""
return username + ".your-domain.tld" if __name__ == '__main__':
app.run() a.注册路由原理

注册路由原理

 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 # 添加到flask中
app.url_map.converters['regex'] = RegexConverter @app.route('/index/<regex("\d+"):nid>')
def index(nid):
print(url_for('index', nid=''))
return 'Index' if __name__ == '__main__':
app.run() b. 自定制正则路由匹配

自定义正则路由匹配

模板系统

模板的使用

Flask使用的是Jinja2模板,所以其语法和Django无差别

自定义模板方法

Flask中自定义模板方法的方式和Bottle相似,创建一个函数并通过参数的形式传入render_template,如:

html

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>自定义函数</h1>
{{ww()|safe}} </body>
</html> html

run.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template
app = Flask(__name__) def wupeiqi():
return '<h1>Wupeiqi</h1>' @app.route('/login', methods=['GET', 'POST'])
def login():
return render_template('login.html', ww=wupeiqi) app.run()

  

flask 如何传参数到 js中,避免& # 39等转义

经常会有字符 空格 ' "" 等被转义成其他字符,这其实是特殊字符进行转义,防止js注入

在js中可以利用tojson解决。

比如数组  num = ["ni"],经过flask的 {{num}}传入js后,就变成了'ni'

解决方法

利用js的tojson

var myGeocode = {{ num|tojson }};

Flask路由系统与模板系统的更多相关文章

  1. Flask:Flask的模板系统和静态文件

    1.Flask模板系统 Django框架有自己独立的模板系统,而Flask是没有的,Flask默认采用jinjia2模板系统,jinjia2是仿写Django模板系统的一个第三方模块,但性能上要比Dj ...

  2. 第一篇 Flask基础篇之(配置文件,路由系统,模板,请求响应,session&cookie)

    Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后 ...

  3. Flask框架(二)—— 反向解析、配置信息、路由系统、模板、请求响应、闪现、session

    Flask框架(二)—— 反向解析.配置信息.路由系统.模板.请求响应.闪现.session 目录 反向解析.配置信息.路由系统.模板.请求响应.闪现.session 一.反向解析 1.什么是反向解析 ...

  4. django基础2: 路由配置系统,URLconf的正则字符串参数,命名空间模式,View(视图),Request对象,Response对象,JsonResponse对象,Template模板系统

    Django基础二 request request这个参数1. 封装了所有跟请求相关的数据,是一个对象 2. 目前我们学过1. request.method GET,POST ...2. reques ...

  5. Flask - 路由系统

    目录 Flask - 路由系统 @app.route()装饰器中的常用参数 methods : 当前 url 地址,允许访问的请求方式 endpoint:反向url地址,默认为视图函数名(url_fo ...

  6. Flask路由系统

    Flask路由系统 我们之前了解了路由系统是由带参数的装饰器完成的. 路由本质:装饰器和闭包实现的. 设置路由的两种方式 第一种: @app.route('/index') def index(): ...

  7. Flask ——路由系统

    Flask中的路由系统其实我们并不陌生了,从一开始到现在都一直在应用 @app.route("/",methods=["GET","POST" ...

  8. flask配置文件、路由设置、模板语法、请求与响应、session使用、闪现功能(flash)

    今日内容概要 flask 配置文件 flask 路由系统 flask模板语法 请求与相应 session 闪现(flash翻译过来的) 内容详细 1.flask 配置文件 # django ---&g ...

  9. Django框架-模板系统

    来看一段代码 def current_datetime(request): now = datetime.datetime.now() html = "<html><bod ...

随机推荐

  1. php代码检查

    最近写php,几个同事都是没写过c的,经常写的变量没有定义,而php没有编译,错误无法发现. 我们现在用的是NetBeans,好在其提供了语法检测,如下图,让编辑器强制显示我错误

  2. SpringMVC 之类型转换Converter 源代码分析

    SpringMVC 之类型转换Converter 源代码分析 最近研究SpringMVC的类型转换器,在以往我们需要 SpringMVC 为我们自动进行类型转换的时候都是用的PropertyEdito ...

  3. 解决Maven项目 Missing artifact jdk.tools:jdk.tools:1.7的错误

    因学习项目需要,在pom.xml添加hbase-client依赖的时候提示解决Maven工程中报 Missing artifact jdk.tools:jdk.tools:1.7的提示信息,之前遇到这 ...

  4. python 图像处理基础操作

    Python 读取图片文件为矩阵和保存矩阵为图片 读取图片为矩阵 import matplotlib im = matplotlib.image.imread('0_0.jpg') 保存矩阵为图片 i ...

  5. 第二百六十九节,Tornado框架-Session登录判断

    Tornado框架-Session登录判断 Session需要结合cookie来实现 Session的理解 1.用户登录系统时,服务器端获取系统当前时间,进行nd5加密,得到加密后的密串 2.将密串作 ...

  6. Dubbo (开源分布式服务框架)

    Provider 暴露服务方称之为“服务提供者”. Consumer 调用远程服务方称之为“服务消费者”. Registry 服务注册与发现的中心目录服务称之为“服务注册中心”. Monitor 统计 ...

  7. jquery cdn加速注意事项

    1, <script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script> 这里 ...

  8. 常用的jQuery前端技巧收集

    调试时巧用console.log(),这比用alert()方便多了. jquery易错点:元素拼接的时候,元素还未添加到DOM,就用该预添加元素操作. ajax动态获取的数据,还没有装载html元素, ...

  9. 关于Animator状态在运行时的正负方向播放

    如果直接在脚本里改播放速度,会报出如下警告: 之前没有很好的解决方法,但根据评论里的新方法,我试了下,可以控制播放正负方向了:

  10. zookeeper配置详解

    原文地址: http://itindex.net/detail/40187-zookeeper-%E7%AE%A1%E7%90%86%E5%91%98-%E7%AE%A1%E7%90%86 参数名 说 ...