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'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章