Flask路由系统与模板系统

路由系统

  • @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,
}
  1 def auth(func):
  2             def inner(*args, **kwargs):
  3                 print('before')
  4                 result = func(*args, **kwargs)
  5                 print('after')
  6                 return result
  7 
  8         return inner
  9 
 10         @app.route('/index.html',methods=['GET','POST'],endpoint='index')
 11         @auth
 12         def index():
 13             return 'Index'
 14 
 15  16         
 17         def index():
 18             return "Index"
 19 
 20         self.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"])
 21         or
 22         app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"])
 23         app.view_functions['index'] = index
 24 
 25 
 26  27         def auth(func):
 28             def inner(*args, **kwargs):
 29                 print('before')
 30                 result = func(*args, **kwargs)
 31                 print('after')
 32                 return result
 33 
 34         return inner
 35 
 36         class IndexView(views.View):
 37             methods = ['GET']
 38             decorators = [auth, ]
 39 
 40             def dispatch_request(self):
 41                 print('Index')
 42                 return 'Index!'
 43 
 44         app.add_url_rule('/index', view_func=IndexView.as_view(name='index'))  # name=endpoint
 45 
 46 
 47 
 48  49 
 50 
 51         class IndexView(views.MethodView):
 52             methods = ['GET']
 53             decorators = [auth, ]
 54 
 55             def get(self):
 56                 return 'Index.GET'
 57 
 58             def post(self):
 59                 return 'Index.POST'
 60 
 61 
 62         app.add_url_rule('/index', view_func=IndexView.as_view(name='index'))  # name=endpoint
 63 
 64 
 65 
 66 
 67         @app.route和app.add_url_rule参数:
 68             rule,                       URL规则
 69             view_func,                  视图函数名称
 70             defaults=None,              默认值,当URL中无参数,函数需要参数时,使用defaults={'k':'v'}为函数提供参数
 71             endpoint=None,              名称,用于反向生成URL,即: url_for('名称')
 72             methods=None,               允许的请求方式,如:["GET","POST"]
 73             
 74 
 75             strict_slashes=None,        对URL最后的 / 符号是否严格要求,
 76                                         如:
 77                                             @app.route('/index',strict_slashes=False),
 78                                                 访问 http://www.xx.com/index/ 或 http://www.xx.com/index均可
 79                                             @app.route('/index',strict_slashes=True)
 80                                                 仅访问 http://www.xx.com/index 
 81             redirect_to=None,           重定向到指定地址
 82                                         如:
 83                                             @app.route('/index/<int:nid>', redirect_to='/home/<nid>')
 84  85                                             def func(adapter, nid):
 86                                                 return "/home/888"
 87                                             @app.route('/index/<int:nid>', redirect_to=func)
 88             subdomain=None,             子域名访问
 89                                                 from flask import Flask, views, url_for
 90 
 91                                                 app = Flask(import_name=__name__)
 92                                                 app.config['SERVER_NAME'] = 'wupeiqi.com:5000'
 93 
 94 
 95                                                 @app.route("/", subdomain="admin")
 96                                                 def static_index():
 97                                                     """Flask supports static subdomains
 98                                                     This is available at static.your-domain.tld"""
 99                                                     return "static.your-domain.tld"
100 
101 
102                                                 @app.route("/dynamic", subdomain="<username>")
103                                                 def username_index(username):
104                                                     """Dynamic subdomains are also supported
105                                                     Try going to user1.your-domain.tld/dynamic"""
106                                                     return username + ".your-domain.tld"
107 
108 
109                                                 if __name__ == '__main__':
110                                                     app.run()
111         
112 
113 a.注册路由原理
注册路由原理
 1 from flask import Flask, views, url_for
 2             from werkzeug.routing import BaseConverter
 3 
 4             app = Flask(import_name=__name__)
 5 
 6 
 7             class RegexConverter(BaseConverter):
 8                 """
 9                 自定义URL匹配正则表达式
10                 """
11                 def __init__(self, map, regex):
12                     super(RegexConverter, self).__init__(map)
13                     self.regex = regex
14 
15                 def to_python(self, value):
16                     """
17                     路由匹配时,匹配成功后传递给视图函数中参数的值
18                     :param value: 
19                     :return: 
20                     """
21                     return int(value)
22 
23                 def to_url(self, value):
24                     """
25                     使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
26                     :param value: 
27                     :return: 
28                     """
29                     val = super(RegexConverter, self).to_url(value)
30                     return val
31 
32             # 添加到flask中
33             app.url_map.converters['regex'] = RegexConverter
34 
35 
36             @app.route('/index/<regex("\d+"):nid>')
37             def index(nid):
38                 print(url_for('index', nid='888'))
39                 return 'Index'
40 
41 
42             if __name__ == '__main__':
43                 app.run()
44 
45 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后,就变成了&#39;ni&#39;

解决方法

利用js的tojson

var myGeocode = {{ num|tojson }};

posted @ 2018-06-12 17:13  人生不如戏  阅读(380)  评论(0编辑  收藏  举报