8、Flask實戰第8天:add_url_rule和app.route原理

來源:互聯網
上載者:User

標籤:info   end   ctrl   http   strong   word   bubuko   反轉   技術   

之前我們使用@app.route這個裝飾器來把視圖函數和url綁定

@app.route(‘/‘)def hell_world():    return ‘hello world‘

而且我們可以通過url_for(‘hello_world‘)反轉得到url ‘/‘

實際上我們可以給這個裝飾器再加上endpoint參數,給這個url命名

@app.route(‘/‘, endpoint=‘index‘)def hello_word():    return ‘hello world‘

一旦我們使用了endpoint參數,在使用url_for()反轉的時候就不能使用視圖函數名了,而是要用我們定義的url名

url_for(‘index‘)
另外一種方式綁定視圖函數和url,那就是add_url_rule

先在app = Flask(__name__)下面輸入app.add_url_rule, 然後按住ctrl點擊它查看源碼

  rule:  設定url

  endpoint:  給url設定的名字

  view_func:  視圖函數

因此,我們可以這樣用

def my_list():    return ‘my list‘app.add_url_rule(rule=‘/list/‘, endpoint=‘list‘, view_func=my_list)

如果要使用url_for反轉的話也是: url_for(‘list‘)

 

實際上,我們看@app.route這個裝飾器的源碼,也是用add_url_rule

8、Flask實戰第8天:add_url_rule和app.route原理

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.