Flask(MVC/路由 三)

MVC

M

model:数据相关逻辑

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

V

view:返回的内容展示

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

C

control:控制器,视图函数

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

MVC

路由

route源码

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请求。当我们需要改变请求方式的时候,我们就可以传入这个参数了。

多个路由同一个处理

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

使用其他装饰器

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

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

import time    
def log_time(func):
    def decorator(*args, **kwargs):
        print(time.time())
        return func(*args, **kwargs)

    return decorator
@app.route('/hello')
@app.route('/')
@log_time
def hello_world():
    return render_template('index.html')

重定向

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

  2. 在视图函数中执行redirect()

设置默认值

  1. 通过defaults

@app.route('/cases/<id>',defaults={'id':3})
  1. 在视图参数中定义默认

@app.route('/cases/<id>')
def hello_world(id=3):
    return render_template('index.html')

视图函数的分离

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

所以项目就变成了:

  • 启动文件

  • 视图函数

  • 数据处理

  • view

  • 其他的帮助函数

结构

main.py

from flask import Flask

app = Flask(__name__)
import urls

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

urls.py

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

def home():
    return 'home'


def cases():
    return 'cases'
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值