Web框架——Flask系列之Flask創建app對象 & 路由(十二)

一、初始化參數

import_name: 當前模塊名
static_url_path:靜態資源的url前綴,默認爲‘static’
static_folder: 靜態文件目錄名,默認‘static’
template_folder: 模板文件目錄名,默認‘templates’
在這裏插入圖片描述

二、配置參數

app.config.from_pyfile(“yourconfig.cfg”) 或
app.config.from_object()
在這裏插入圖片描述
在這裏插入圖片描述

三、在視圖讀取配置參數

app.config.get() 或者 current_app.config.get()
在這裏插入圖片描述

四、app.run的參數

app.run(host=”0.0.0.0”, port=5000,debug=True)

五、Flask的Hello world程序

# 導入Flask類
from flask import Flask

#Flask類接收一個參數__name__
app = Flask(__name__)

# 裝飾器的作用是將路由映射到視圖函數index
@app.route('/')
def index():
    return 'Hello World'

# Flask應用程序實例的run方法啓動WEB服務器
if __name__ == '__main__':
    app.run()

六、app.url_map 查看所有路由

在這裏插入圖片描述

七、同一路由裝飾多個視圖函數

在這裏插入圖片描述

八、同一視圖多個路由裝飾器

在這裏插入圖片描述

九、利用methods限制訪問方式

@app.route(’/sample’, methods=[‘GET’, ‘POST’])
在這裏插入圖片描述

十、使用url_for進行反解析

在這裏插入圖片描述
在這裏插入圖片描述

十一、動態路由

路由傳遞的參數默認當做string處理,這裏指定int,尖括號中冒號後面的內容是動態的

# 路由傳遞的參數默認當做string處理,這裏指定int,尖括號中冒號後面的內容是動態的
@app.route('/user/<int:id>')
def hello_itcast(id):
    return 'hello itcast %d' %id

在這裏插入圖片描述
在這裏插入圖片描述

十二、自定義轉換器

from flask import Flask
from werkzeug.routing import BaseConverter

class Regex_url(BaseConverter):
    def __init__(self,url_map,*args):
        super(Regex_url,self).__init__(url_map)
        self.regex = args[0]

app = Flask(__name__)
app.url_map.converters['re'] = Regex_url

@app.route('/user/<re("[a-z]{3}"):id>')
def hello_itcast(id):
    return 'hello %s' %id

在這裏插入圖片描述

  1. 普通自定義轉換器:
    在這裏插入圖片描述
  2. 萬能自定義轉換器:
    在這裏插入圖片描述
    從路徑中取出來的18612345678並不是直接作爲參數傳遞給視圖函數send_sms()的形參的,而是先把18612345678傳遞給to_python()函數,然後把to_python()函數的返回值再傳遞給send_sms()函數的形參!
    在這裏插入圖片描述
    在這裏插入圖片描述
    在這裏插入圖片描述
    在這裏插入圖片描述
    在這裏插入圖片描述
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章