3.Flask:MVC/路由

Flask(MVC/路由 三)

MVC

M

model:数据相关逻辑

程序员编写程序应有的功能(实现算法等),DBA对数据库进行数据库管理和设计

V

view:返回的内容展示

界面设计人员进行图形界面设计

C

control:控制器,视图函数

负责转发请求,对请求进行处理

MVC

路由

route源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def route(self, rule, **options):
"""A decorator that is used to register a view function for a
given URL rule. This does the same thing as :meth:`add_url_rule`
but is intended for decorator usage::

@app.route('/')
def index():
return 'Hello World'

For more information refer to :ref:`url-route-registrations`.

:param rule: the URL rule as string
:param endpoint: the endpoint for the registered URL rule. Flask
itself assumes the name of the view function as
endpoint
:param options: the options to be forwarded to the underlying
:class:`~werkzeug.routing.Rule` object. A change
to Werkzeug is handling of method options. methods
is a list of methods this rule should be limited
to (``GET``, ``POST`` etc.). By default a rule
just listens for ``GET`` (and implicitly ``HEAD``).
Starting with Flask 0.6, ``OPTIONS`` is implicitly
added and handled by the standard request handling.
"""

def decorator(f):
endpoint = options.pop("endpoint", None)
self.add_url_rule(rule, endpoint, f, **options)
return f

return decorator

去除注释部分后可以看出route就是一个很简单的闭包

self.add_url_rule(rule, endpoint, f, **options)这里的self就是app

所以也可以直接通过app.add_url_rule('/',endpoint=xxx,view_func=xxx)来添加路由

  • 第一个参数:函数对应的url规则,满足条件和app.route()的第一个参数一样,必须以'/'开始
  • endpoint:站点,就是在使用url_for()进行反转的时候,这个里面传入的第一个参数就是这个endpoint对应的值。这个值也可以不指定,那么默认就会使用函数的名字作为endpoint的值
  • view_func:对应的函数,即这个url对应的是哪一个函数,注意,这里函数只需要写函数名字,不要加括号,加括号表示将函数的返回值传给了view_func参数了。程序就会直接报错。
  • methods:add_url_rule还可以传入一个methods参数,用来指定这个函数对应的访问规制,如post,get请求等,默认是get请求,并且只允许get请求。当我们需要改变请求方式的时候,我们就可以传入这个参数了。

多个路由同一个处理

1
2
3
4
@app.route('/hello')
@app.route('/')
def hello_world():
return render_template('index.html')

使用其他装饰器

其他装饰器要放在@app.route()下面

一个简单的打印时间的装饰器

1
2
3
4
5
6
7
import time	
def log_time(func):
def decorator(*args, **kwargs):
print(time.time())
return func(*args, **kwargs)

return decorator
1
2
3
4
5
@app.route('/hello')
@app.route('/')
@log_time
def hello_world():
return render_template('index.html')

重定向

  1. @app.route(redirect_to'/') 不会去执行视图函数
  2. 在视图函数中执行redirect()

设置默认值

  1. 通过defaults
1
@app.route('/cases/<id>',defaults={'id':3})
  1. 在视图参数中定义默认
1
2
3
@app.route('/cases/<id>')
def hello_world(id=3):
return render_template('index.html')

视图函数的分离

随着项目的增大,视图函数需要单独放在一起,不在一个文件里了。

所以项目就变成了:

  • 启动文件
  • 视图函数
  • 数据处理
  • view
  • 其他的帮助函数

结构

main.py

1
2
3
4
5
6
7
from flask import Flask

app = Flask(__name__)
import urls

if __name__ == '__main__':
app.run()

urls.py

1
2
3
4
5
from main import app
import views

app.add_url_rule('/', view_func=views.home)
app.add_url_rule('/cases', view_func=views.cases)

view.py

1
2
3
4
5
6
def home():
return 'home'


def cases():
return 'cases'
 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
您的支持将鼓励我继续创作!